blob: 1c277cebfeccb85859ff1b6dd0210bdaf268030d [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070034#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035
Dima Zavinfce7a472011-04-19 22:30:36 -070036#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080038#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039
Glenn Kastend3cee2f2012-03-13 17:55:35 -070040#undef ADD_BATTERY_DATA
41
42#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080043#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080044#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070045#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070046
47#include <private/media/AudioTrackShared.h>
48#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070049
Dima Zavin64760242011-05-11 14:15:23 -070050#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070051#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
53#include "AudioMixer.h"
54#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080055#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Mathias Agopian65ab4712010-07-14 17:59:35 -070057#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070058#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070059#include <audio_effects/effect_ns.h>
60#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061
Glenn Kasten3b21c502011-12-15 09:52:39 -080062#include <audio_utils/primitives.h>
63
Eric Laurentfeb0db62011-07-22 09:04:31 -070064#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080065
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070066// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080067#ifdef DEBUG_CPU_USAGE
68#include <cpustats/CentralTendencyStatistics.h>
69#include <cpustats/ThreadCpuUsage.h>
70#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070071
John Grossman4ff14ba2012-02-08 16:37:41 -080072#include <common_time/cc_helper.h>
73#include <common_time/local_clock.h>
74
Glenn Kasten58912562012-04-03 10:45:00 -070075#include "FastMixer.h"
76
77// NBAIO implementations
78#include "AudioStreamOutSink.h"
79#include "MonoPipe.h"
80#include "MonoPipeReader.h"
81#include "SourceAudioBufferProvider.h"
82
Glenn Kasten1dc28b72012-04-24 10:01:03 -070083#ifdef HAVE_REQUEST_PRIORITY
84#include "SchedulingPolicyService.h"
85#endif
86
Glenn Kasten58912562012-04-03 10:45:00 -070087#ifdef SOAKER
88#include "Soaker.h"
89#endif
90
Mathias Agopian65ab4712010-07-14 17:59:35 -070091// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070092
John Grossman1c345192012-03-27 14:00:17 -070093// Note: the following macro is used for extremely verbose logging message. In
94// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
95// 0; but one side effect of this is to turn all LOGV's as well. Some messages
96// are so verbose that we want to suppress them even when we have ALOG_ASSERT
97// turned on. Do not uncomment the #def below unless you really know what you
98// are doing and want to see all of the extremely verbose messages.
99//#define VERY_VERY_VERBOSE_LOGGING
100#ifdef VERY_VERY_VERBOSE_LOGGING
101#define ALOGVV ALOGV
102#else
103#define ALOGVV(a...) do { } while(0)
104#endif
Eric Laurentde070132010-07-13 04:45:46 -0700105
Mathias Agopian65ab4712010-07-14 17:59:35 -0700106namespace android {
107
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800108static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
109static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110
Mathias Agopian65ab4712010-07-14 17:59:35 -0700111static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800112static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700113
114// retry counts for buffer fill timeout
115// 50 * ~20msecs = 1 second
116static const int8_t kMaxTrackRetries = 50;
117static const int8_t kMaxTrackStartupRetries = 50;
118// allow less retry attempts on direct output thread.
119// direct outputs can be a scarce resource in audio hardware and should
120// be released as quickly as possible.
121static const int8_t kMaxTrackRetriesDirect = 2;
122
123static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -0800124static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700125
Glenn Kasten7dede872011-12-13 11:04:14 -0800126// don't warn about blocked writes or record buffer overflows more often than this
127static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700128
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700129// RecordThread loop sleep time upon application overrun or audio HAL read error
130static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700131
Glenn Kasten7dede872011-12-13 11:04:14 -0800132// maximum time to wait for setParameters to complete
133static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700134
Eric Laurent7cafbb32011-11-22 18:50:29 -0800135// minimum sleep time for the mixer thread loop when tracks are active but in underrun
136static const uint32_t kMinThreadSleepTimeUs = 5000;
137// maximum divider applied to the active sleep time in the mixer thread loop
138static const uint32_t kMaxThreadSleepTimeShift = 2;
139
Glenn Kasten58912562012-04-03 10:45:00 -0700140// minimum normal mix buffer size, expressed in milliseconds rather than frames
141static const uint32_t kMinNormalMixBufferSizeMs = 20;
142
John Grossman4ff14ba2012-02-08 16:37:41 -0800143nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800144
Mathias Agopian65ab4712010-07-14 17:59:35 -0700145// ----------------------------------------------------------------------------
146
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700147#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800148// To collect the amplifier usage
149static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800150 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
151 if (service == NULL) {
152 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800153 return;
154 }
155
156 service->addBatteryData(params);
157}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700158#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800159
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700160static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700161{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700162 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700163 int rc;
164
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700165 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
166 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
167 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
168 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700169 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700170 }
171 rc = audio_hw_device_open(mod, dev);
172 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
173 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
174 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700175 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700176 }
177 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
178 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
179 rc = BAD_VALUE;
180 goto out;
181 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700182 return 0;
183
184out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700185 *dev = NULL;
186 return rc;
187}
188
Mathias Agopian65ab4712010-07-14 17:59:35 -0700189// ----------------------------------------------------------------------------
190
191AudioFlinger::AudioFlinger()
192 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800193 mPrimaryHardwareDev(NULL),
194 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
195 mMasterVolume(1.0f),
196 mMasterVolumeSupportLvl(MVS_NONE),
197 mMasterMute(false),
198 mNextUniqueId(1),
199 mMode(AUDIO_MODE_INVALID),
200 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700201{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700202}
203
204void AudioFlinger::onFirstRef()
205{
Dima Zavin799a70e2011-04-18 16:57:27 -0700206 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700207
Eric Laurent93575202011-01-18 18:39:02 -0800208 Mutex::Autolock _l(mLock);
209
Dima Zavin799a70e2011-04-18 16:57:27 -0700210 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800211 char val_str[PROPERTY_VALUE_MAX] = { 0 };
212 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
213 uint32_t int_val;
214 if (1 == sscanf(val_str, "%u", &int_val)) {
215 mStandbyTimeInNsecs = milliseconds(int_val);
216 ALOGI("Using %u mSec as standby time.", int_val);
217 } else {
218 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
219 ALOGI("Using default %u mSec as standby time.",
220 (uint32_t)(mStandbyTimeInNsecs / 1000000));
221 }
222 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700223
Eric Laurenta4c5a552012-03-29 10:12:40 -0700224 mMode = AUDIO_MODE_NORMAL;
225 mMasterVolumeSW = 1.0;
226 mMasterVolume = 1.0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800227 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700228}
229
230AudioFlinger::~AudioFlinger()
231{
Dima Zavin799a70e2011-04-18 16:57:27 -0700232
Mathias Agopian65ab4712010-07-14 17:59:35 -0700233 while (!mRecordThreads.isEmpty()) {
234 // closeInput() will remove first entry from mRecordThreads
235 closeInput(mRecordThreads.keyAt(0));
236 }
237 while (!mPlaybackThreads.isEmpty()) {
238 // closeOutput() will remove first entry from mPlaybackThreads
239 closeOutput(mPlaybackThreads.keyAt(0));
240 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700241
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800242 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
243 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700244 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
245 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700246 }
247}
248
Eric Laurenta4c5a552012-03-29 10:12:40 -0700249static const char * const audio_interfaces[] = {
250 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
251 AUDIO_HARDWARE_MODULE_ID_A2DP,
252 AUDIO_HARDWARE_MODULE_ID_USB,
253};
254#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
255
256audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(audio_module_handle_t module, uint32_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700257{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700258 // if module is 0, the request comes from an old policy manager and we should load
259 // well known modules
260 if (module == 0) {
261 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
262 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
263 loadHwModule_l(audio_interfaces[i]);
264 }
265 } else {
266 // check a match for the requested module handle
267 AudioHwDevice *audioHwdevice = mAudioHwDevs.valueFor(module);
268 if (audioHwdevice != NULL) {
269 return audioHwdevice->hwDevice();
270 }
271 }
272 // then try to find a module supporting the requested device.
Dima Zavin799a70e2011-04-18 16:57:27 -0700273 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700274 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700275 if ((dev->get_supported_devices(dev) & devices) == devices)
276 return dev;
277 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700278
Dima Zavin799a70e2011-04-18 16:57:27 -0700279 return NULL;
280}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700281
282status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
283{
284 const size_t SIZE = 256;
285 char buffer[SIZE];
286 String8 result;
287
288 result.append("Clients:\n");
289 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800290 sp<Client> client = mClients.valueAt(i).promote();
291 if (client != 0) {
292 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
293 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700294 }
295 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700296
297 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800298 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700299 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
300 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800301 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700302 result.append(buffer);
303 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700304 write(fd, result.string(), result.size());
305 return NO_ERROR;
306}
307
308
309status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
310{
311 const size_t SIZE = 256;
312 char buffer[SIZE];
313 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800314 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700315
John Grossman4ff14ba2012-02-08 16:37:41 -0800316 snprintf(buffer, SIZE, "Hardware status: %d\n"
317 "Standby Time mSec: %u\n",
318 hardwareStatus,
319 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700320 result.append(buffer);
321 write(fd, result.string(), result.size());
322 return NO_ERROR;
323}
324
325status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
326{
327 const size_t SIZE = 256;
328 char buffer[SIZE];
329 String8 result;
330 snprintf(buffer, SIZE, "Permission Denial: "
331 "can't dump AudioFlinger from pid=%d, uid=%d\n",
332 IPCThreadState::self()->getCallingPid(),
333 IPCThreadState::self()->getCallingUid());
334 result.append(buffer);
335 write(fd, result.string(), result.size());
336 return NO_ERROR;
337}
338
339static bool tryLock(Mutex& mutex)
340{
341 bool locked = false;
342 for (int i = 0; i < kDumpLockRetries; ++i) {
343 if (mutex.tryLock() == NO_ERROR) {
344 locked = true;
345 break;
346 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800347 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700348 }
349 return locked;
350}
351
352status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
353{
Glenn Kasten44deb052012-02-05 18:09:08 -0800354 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700355 dumpPermissionDenial(fd, args);
356 } else {
357 // get state of hardware lock
358 bool hardwareLocked = tryLock(mHardwareLock);
359 if (!hardwareLocked) {
360 String8 result(kHardwareLockedString);
361 write(fd, result.string(), result.size());
362 } else {
363 mHardwareLock.unlock();
364 }
365
366 bool locked = tryLock(mLock);
367
368 // failed to lock - AudioFlinger is probably deadlocked
369 if (!locked) {
370 String8 result(kDeadlockedString);
371 write(fd, result.string(), result.size());
372 }
373
374 dumpClients(fd, args);
375 dumpInternals(fd, args);
376
377 // dump playback threads
378 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
379 mPlaybackThreads.valueAt(i)->dump(fd, args);
380 }
381
382 // dump record threads
383 for (size_t i = 0; i < mRecordThreads.size(); i++) {
384 mRecordThreads.valueAt(i)->dump(fd, args);
385 }
386
Dima Zavin799a70e2011-04-18 16:57:27 -0700387 // dump all hardware devs
388 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700389 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700390 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700391 }
392 if (locked) mLock.unlock();
393 }
394 return NO_ERROR;
395}
396
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800397sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
398{
399 // If pid is already in the mClients wp<> map, then use that entry
400 // (for which promote() is always != 0), otherwise create a new entry and Client.
401 sp<Client> client = mClients.valueFor(pid).promote();
402 if (client == 0) {
403 client = new Client(this, pid);
404 mClients.add(pid, client);
405 }
406
407 return client;
408}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700409
410// IAudioFlinger interface
411
412
413sp<IAudioTrack> AudioFlinger::createTrack(
414 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800415 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700416 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800417 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700418 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700419 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800420 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700421 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800422 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800423 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700424 int *sessionId,
425 status_t *status)
426{
427 sp<PlaybackThread::Track> track;
428 sp<TrackHandle> trackHandle;
429 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700430 status_t lStatus;
431 int lSessionId;
432
Glenn Kasten263709e2012-01-06 08:40:01 -0800433 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
434 // but if someone uses binder directly they could bypass that and cause us to crash
435 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000436 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700437 lStatus = BAD_VALUE;
438 goto Exit;
439 }
440
441 {
442 Mutex::Autolock _l(mLock);
443 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700444 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700445 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000446 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700447 lStatus = BAD_VALUE;
448 goto Exit;
449 }
450
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800451 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700452
Steve Block3856b092011-10-20 11:56:00 +0100453 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700454 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700455 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700456 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
457 if (mPlaybackThreads.keyAt(i) != output) {
458 // prevent same audio session on different output threads
459 uint32_t sessions = t->hasAudioSession(*sessionId);
460 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000461 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700462 lStatus = BAD_VALUE;
463 goto Exit;
464 }
465 // check if an effect with same session ID is waiting for a track to be created
466 if (sessions & PlaybackThread::EFFECT_SESSION) {
467 effectThread = t.get();
468 }
Eric Laurentde070132010-07-13 04:45:46 -0700469 }
470 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700471 lSessionId = *sessionId;
472 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700473 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700474 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700475 if (sessionId != NULL) {
476 *sessionId = lSessionId;
477 }
478 }
Steve Block3856b092011-10-20 11:56:00 +0100479 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700480
481 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800482 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700483
484 // move effect chain to this output thread if an effect on same session was waiting
485 // for a track to be created
486 if (lStatus == NO_ERROR && effectThread != NULL) {
487 Mutex::Autolock _dl(thread->mLock);
488 Mutex::Autolock _sl(effectThread->mLock);
489 moveEffectChain_l(lSessionId, effectThread, thread, true);
490 }
Eric Laurenta011e352012-03-29 15:51:43 -0700491
492 // Look for sync events awaiting for a session to be used.
493 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
494 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
495 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
496 track->setSyncEvent(mPendingSyncEvents[i]);
497 mPendingSyncEvents.removeAt(i);
498 i--;
499 }
500 }
501 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700502 }
503 if (lStatus == NO_ERROR) {
504 trackHandle = new TrackHandle(track);
505 } else {
506 // remove local strong reference to Client before deleting the Track so that the Client
507 // destructor is called by the TrackBase destructor with mLock held
508 client.clear();
509 track.clear();
510 }
511
512Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700513 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700514 *status = lStatus;
515 }
516 return trackHandle;
517}
518
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800519uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700520{
521 Mutex::Autolock _l(mLock);
522 PlaybackThread *thread = checkPlaybackThread_l(output);
523 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000524 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700525 return 0;
526 }
527 return thread->sampleRate();
528}
529
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800530int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700531{
532 Mutex::Autolock _l(mLock);
533 PlaybackThread *thread = checkPlaybackThread_l(output);
534 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000535 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700536 return 0;
537 }
538 return thread->channelCount();
539}
540
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800541audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700542{
543 Mutex::Autolock _l(mLock);
544 PlaybackThread *thread = checkPlaybackThread_l(output);
545 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000546 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800547 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700548 }
549 return thread->format();
550}
551
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800552size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700553{
554 Mutex::Autolock _l(mLock);
555 PlaybackThread *thread = checkPlaybackThread_l(output);
556 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000557 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700558 return 0;
559 }
Glenn Kasten58912562012-04-03 10:45:00 -0700560 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
561 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700562 return thread->frameCount();
563}
564
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800565uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700566{
567 Mutex::Autolock _l(mLock);
568 PlaybackThread *thread = checkPlaybackThread_l(output);
569 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000570 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700571 return 0;
572 }
573 return thread->latency();
574}
575
576status_t AudioFlinger::setMasterVolume(float value)
577{
Eric Laurenta1884f92011-08-23 08:25:03 -0700578 status_t ret = initCheck();
579 if (ret != NO_ERROR) {
580 return ret;
581 }
582
Mathias Agopian65ab4712010-07-14 17:59:35 -0700583 // check calling permissions
584 if (!settingsAllowed()) {
585 return PERMISSION_DENIED;
586 }
587
John Grossman4ff14ba2012-02-08 16:37:41 -0800588 float swmv = value;
589
Eric Laurenta4c5a552012-03-29 10:12:40 -0700590 Mutex::Autolock _l(mLock);
591
Mathias Agopian65ab4712010-07-14 17:59:35 -0700592 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800593 if (MVS_NONE != mMasterVolumeSupportLvl) {
594 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
595 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700596 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
John Grossman4ff14ba2012-02-08 16:37:41 -0800597
598 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
599 if (NULL != dev->set_master_volume) {
600 dev->set_master_volume(dev, value);
601 }
602 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800603 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800604
605 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700606 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700607
John Grossman4ff14ba2012-02-08 16:37:41 -0800608 mMasterVolume = value;
609 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800610 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700611 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700612
613 return NO_ERROR;
614}
615
Glenn Kastenf78aee72012-01-04 11:00:47 -0800616status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700617{
Eric Laurenta1884f92011-08-23 08:25:03 -0700618 status_t ret = initCheck();
619 if (ret != NO_ERROR) {
620 return ret;
621 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700622
623 // check calling permissions
624 if (!settingsAllowed()) {
625 return PERMISSION_DENIED;
626 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800627 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000628 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700629 return BAD_VALUE;
630 }
631
632 { // scope for the lock
633 AutoMutex lock(mHardwareLock);
634 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700635 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700636 mHardwareStatus = AUDIO_HW_IDLE;
637 }
638
639 if (NO_ERROR == ret) {
640 Mutex::Autolock _l(mLock);
641 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800642 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700643 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700644 }
645
646 return ret;
647}
648
649status_t AudioFlinger::setMicMute(bool state)
650{
Eric Laurenta1884f92011-08-23 08:25:03 -0700651 status_t ret = initCheck();
652 if (ret != NO_ERROR) {
653 return ret;
654 }
655
Mathias Agopian65ab4712010-07-14 17:59:35 -0700656 // check calling permissions
657 if (!settingsAllowed()) {
658 return PERMISSION_DENIED;
659 }
660
661 AutoMutex lock(mHardwareLock);
662 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700663 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700664 mHardwareStatus = AUDIO_HW_IDLE;
665 return ret;
666}
667
668bool AudioFlinger::getMicMute() const
669{
Eric Laurenta1884f92011-08-23 08:25:03 -0700670 status_t ret = initCheck();
671 if (ret != NO_ERROR) {
672 return false;
673 }
674
Dima Zavinfce7a472011-04-19 22:30:36 -0700675 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800676 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700677 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700678 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700679 mHardwareStatus = AUDIO_HW_IDLE;
680 return state;
681}
682
683status_t AudioFlinger::setMasterMute(bool muted)
684{
685 // check calling permissions
686 if (!settingsAllowed()) {
687 return PERMISSION_DENIED;
688 }
689
Eric Laurent93575202011-01-18 18:39:02 -0800690 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800691 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700692 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800693 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700694 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700695
696 return NO_ERROR;
697}
698
699float AudioFlinger::masterVolume() const
700{
Glenn Kasten98067102011-12-13 11:47:54 -0800701 Mutex::Autolock _l(mLock);
702 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700703}
704
John Grossman4ff14ba2012-02-08 16:37:41 -0800705float AudioFlinger::masterVolumeSW() const
706{
707 Mutex::Autolock _l(mLock);
708 return masterVolumeSW_l();
709}
710
Mathias Agopian65ab4712010-07-14 17:59:35 -0700711bool AudioFlinger::masterMute() const
712{
Glenn Kasten98067102011-12-13 11:47:54 -0800713 Mutex::Autolock _l(mLock);
714 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700715}
716
John Grossman4ff14ba2012-02-08 16:37:41 -0800717float AudioFlinger::masterVolume_l() const
718{
719 if (MVS_FULL == mMasterVolumeSupportLvl) {
720 float ret_val;
721 AutoMutex lock(mHardwareLock);
722
723 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800724 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
725 (NULL != mPrimaryHardwareDev->get_master_volume),
726 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800727
728 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
729 mHardwareStatus = AUDIO_HW_IDLE;
730 return ret_val;
731 }
732
733 return mMasterVolume;
734}
735
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800736status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
737 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700738{
739 // check calling permissions
740 if (!settingsAllowed()) {
741 return PERMISSION_DENIED;
742 }
743
Glenn Kasten263709e2012-01-06 08:40:01 -0800744 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000745 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700746 return BAD_VALUE;
747 }
748
749 AutoMutex lock(mLock);
750 PlaybackThread *thread = NULL;
751 if (output) {
752 thread = checkPlaybackThread_l(output);
753 if (thread == NULL) {
754 return BAD_VALUE;
755 }
756 }
757
758 mStreamTypes[stream].volume = value;
759
760 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800761 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700762 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700763 }
764 } else {
765 thread->setStreamVolume(stream, value);
766 }
767
768 return NO_ERROR;
769}
770
Glenn Kastenfff6d712012-01-12 16:38:12 -0800771status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700772{
773 // check calling permissions
774 if (!settingsAllowed()) {
775 return PERMISSION_DENIED;
776 }
777
Glenn Kasten263709e2012-01-06 08:40:01 -0800778 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700779 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000780 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700781 return BAD_VALUE;
782 }
783
Eric Laurent93575202011-01-18 18:39:02 -0800784 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700785 mStreamTypes[stream].mute = muted;
786 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700787 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700788
789 return NO_ERROR;
790}
791
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800792float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700793{
Glenn Kasten263709e2012-01-06 08:40:01 -0800794 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700795 return 0.0f;
796 }
797
798 AutoMutex lock(mLock);
799 float volume;
800 if (output) {
801 PlaybackThread *thread = checkPlaybackThread_l(output);
802 if (thread == NULL) {
803 return 0.0f;
804 }
805 volume = thread->streamVolume(stream);
806 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800807 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700808 }
809
810 return volume;
811}
812
Glenn Kastenfff6d712012-01-12 16:38:12 -0800813bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814{
Glenn Kasten263709e2012-01-06 08:40:01 -0800815 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700816 return true;
817 }
818
Glenn Kasten6637baa2012-01-09 09:40:36 -0800819 AutoMutex lock(mLock);
820 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821}
822
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800823status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700824{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800825 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700826 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
827 // check calling permissions
828 if (!settingsAllowed()) {
829 return PERMISSION_DENIED;
830 }
831
Mathias Agopian65ab4712010-07-14 17:59:35 -0700832 // ioHandle == 0 means the parameters are global to the audio hardware interface
833 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700834 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700835 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800836 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700837 AutoMutex lock(mHardwareLock);
838 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
839 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
840 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
841 status_t result = dev->set_parameters(dev, keyValuePairs.string());
842 final_result = result ?: final_result;
843 }
844 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800845 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700846 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
847 AudioParameter param = AudioParameter(keyValuePairs);
848 String8 value;
849 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700850 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
851 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700852 for (size_t i = 0; i < mRecordThreads.size(); i++) {
853 sp<RecordThread> thread = mRecordThreads.valueAt(i);
854 RecordThread::RecordTrack *track = thread->track();
855 if (track != NULL) {
856 audio_devices_t device = (audio_devices_t)(
857 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700858 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700859 thread->setEffectSuspended(FX_IID_AEC,
860 suspend,
861 track->sessionId());
862 thread->setEffectSuspended(FX_IID_NS,
863 suspend,
864 track->sessionId());
865 }
866 }
Eric Laurentbee53372011-08-29 12:42:48 -0700867 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700868 }
869 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700870 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700871 }
872
873 // hold a strong ref on thread in case closeOutput() or closeInput() is called
874 // and the thread is exited once the lock is released
875 sp<ThreadBase> thread;
876 {
877 Mutex::Autolock _l(mLock);
878 thread = checkPlaybackThread_l(ioHandle);
879 if (thread == NULL) {
880 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800881 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700882 // indicate output device change to all input threads for pre processing
883 AudioParameter param = AudioParameter(keyValuePairs);
884 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700885 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
886 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700887 for (size_t i = 0; i < mRecordThreads.size(); i++) {
888 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
889 }
890 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700891 }
892 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800893 if (thread != 0) {
894 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700895 }
896 return BAD_VALUE;
897}
898
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800899String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700900{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800901// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700902// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
903
Eric Laurenta4c5a552012-03-29 10:12:40 -0700904 Mutex::Autolock _l(mLock);
905
Mathias Agopian65ab4712010-07-14 17:59:35 -0700906 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700907 String8 out_s8;
908
Dima Zavin799a70e2011-04-18 16:57:27 -0700909 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800910 char *s;
911 {
912 AutoMutex lock(mHardwareLock);
913 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700914 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800915 s = dev->get_parameters(dev, keys.string());
916 mHardwareStatus = AUDIO_HW_IDLE;
917 }
John Grossmanef7740b2012-02-09 11:28:36 -0800918 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700919 free(s);
920 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700921 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700922 }
923
Mathias Agopian65ab4712010-07-14 17:59:35 -0700924 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
925 if (playbackThread != NULL) {
926 return playbackThread->getParameters(keys);
927 }
928 RecordThread *recordThread = checkRecordThread_l(ioHandle);
929 if (recordThread != NULL) {
930 return recordThread->getParameters(keys);
931 }
932 return String8("");
933}
934
Glenn Kastenf587ba52012-01-26 16:25:10 -0800935size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700936{
Eric Laurenta1884f92011-08-23 08:25:03 -0700937 status_t ret = initCheck();
938 if (ret != NO_ERROR) {
939 return 0;
940 }
941
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800942 AutoMutex lock(mHardwareLock);
943 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700944 struct audio_config config = {
945 sample_rate: sampleRate,
946 channel_mask: audio_channel_in_mask_from_count(channelCount),
947 format: format,
948 };
949 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800950 mHardwareStatus = AUDIO_HW_IDLE;
951 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700952}
953
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800954unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700955{
956 if (ioHandle == 0) {
957 return 0;
958 }
959
960 Mutex::Autolock _l(mLock);
961
962 RecordThread *recordThread = checkRecordThread_l(ioHandle);
963 if (recordThread != NULL) {
964 return recordThread->getInputFramesLost();
965 }
966 return 0;
967}
968
969status_t AudioFlinger::setVoiceVolume(float value)
970{
Eric Laurenta1884f92011-08-23 08:25:03 -0700971 status_t ret = initCheck();
972 if (ret != NO_ERROR) {
973 return ret;
974 }
975
Mathias Agopian65ab4712010-07-14 17:59:35 -0700976 // check calling permissions
977 if (!settingsAllowed()) {
978 return PERMISSION_DENIED;
979 }
980
981 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800982 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700983 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700984 mHardwareStatus = AUDIO_HW_IDLE;
985
986 return ret;
987}
988
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800989status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
990 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700991{
992 status_t status;
993
994 Mutex::Autolock _l(mLock);
995
996 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
997 if (playbackThread != NULL) {
998 return playbackThread->getRenderPosition(halFrames, dspFrames);
999 }
1000
1001 return BAD_VALUE;
1002}
1003
1004void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1005{
1006
1007 Mutex::Autolock _l(mLock);
1008
Glenn Kastenbb001922012-02-03 11:10:26 -08001009 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001010 if (mNotificationClients.indexOfKey(pid) < 0) {
1011 sp<NotificationClient> notificationClient = new NotificationClient(this,
1012 client,
1013 pid);
Steve Block3856b092011-10-20 11:56:00 +01001014 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001015
1016 mNotificationClients.add(pid, notificationClient);
1017
1018 sp<IBinder> binder = client->asBinder();
1019 binder->linkToDeath(notificationClient);
1020
1021 // the config change is always sent from playback or record threads to avoid deadlock
1022 // with AudioSystem::gLock
1023 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1024 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1025 }
1026
1027 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1028 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1029 }
1030 }
1031}
1032
1033void AudioFlinger::removeNotificationClient(pid_t pid)
1034{
1035 Mutex::Autolock _l(mLock);
1036
Glenn Kastena3b09252012-01-20 09:19:01 -08001037 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001038
Steve Block3856b092011-10-20 11:56:00 +01001039 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001040 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001041 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001042 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001043 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001044 ALOGV(" pid %d @ %d", ref->mPid, i);
1045 if (ref->mPid == pid) {
1046 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001047 mAudioSessionRefs.removeAt(i);
1048 delete ref;
1049 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001050 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001051 } else {
1052 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001053 }
1054 }
1055 if (removed) {
1056 purgeStaleEffects_l();
1057 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001058}
1059
1060// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001061void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001062{
1063 size_t size = mNotificationClients.size();
1064 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001065 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1066 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001067 }
1068}
1069
1070// removeClient_l() must be called with AudioFlinger::mLock held
1071void AudioFlinger::removeClient_l(pid_t pid)
1072{
Steve Block3856b092011-10-20 11:56:00 +01001073 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001074 mClients.removeItem(pid);
1075}
1076
1077
1078// ----------------------------------------------------------------------------
1079
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001080AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1081 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001082 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001083 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001084 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001085 // mChannelMask
1086 mChannelCount(0),
1087 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1088 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001089 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001090 mDevice(device),
1091 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001092{
1093}
1094
1095AudioFlinger::ThreadBase::~ThreadBase()
1096{
1097 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001098 // do not lock the mutex in destructor
1099 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001100 if (mPowerManager != 0) {
1101 sp<IBinder> binder = mPowerManager->asBinder();
1102 binder->unlinkToDeath(mDeathRecipient);
1103 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001104}
1105
1106void AudioFlinger::ThreadBase::exit()
1107{
Steve Block3856b092011-10-20 11:56:00 +01001108 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001109 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001110 // This lock prevents the following race in thread (uniprocessor for illustration):
1111 // if (!exitPending()) {
1112 // // context switch from here to exit()
1113 // // exit() calls requestExit(), what exitPending() observes
1114 // // exit() calls signal(), which is dropped since no waiters
1115 // // context switch back from exit() to here
1116 // mWaitWorkCV.wait(...);
1117 // // now thread is hung
1118 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001119 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001120 requestExit();
1121 mWaitWorkCV.signal();
1122 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001123 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1124 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001125 requestExitAndWait();
1126}
1127
Mathias Agopian65ab4712010-07-14 17:59:35 -07001128status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1129{
1130 status_t status;
1131
Steve Block3856b092011-10-20 11:56:00 +01001132 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001133 Mutex::Autolock _l(mLock);
1134
1135 mNewParameters.add(keyValuePairs);
1136 mWaitWorkCV.signal();
1137 // wait condition with timeout in case the thread loop has exited
1138 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001139 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001140 status = mParamStatus;
1141 mWaitWorkCV.signal();
1142 } else {
1143 status = TIMED_OUT;
1144 }
1145 return status;
1146}
1147
1148void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1149{
1150 Mutex::Autolock _l(mLock);
1151 sendConfigEvent_l(event, param);
1152}
1153
1154// sendConfigEvent_l() must be called with ThreadBase::mLock held
1155void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1156{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001157 ConfigEvent configEvent;
1158 configEvent.mEvent = event;
1159 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001160 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001161 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001162 mWaitWorkCV.signal();
1163}
1164
1165void AudioFlinger::ThreadBase::processConfigEvents()
1166{
1167 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001168 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001169 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001170 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001171 mConfigEvents.removeAt(0);
1172 // release mLock before locking AudioFlinger mLock: lock order is always
1173 // AudioFlinger then ThreadBase to avoid cross deadlock
1174 mLock.unlock();
1175 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001176 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001177 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001178 mLock.lock();
1179 }
1180 mLock.unlock();
1181}
1182
1183status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1184{
1185 const size_t SIZE = 256;
1186 char buffer[SIZE];
1187 String8 result;
1188
1189 bool locked = tryLock(mLock);
1190 if (!locked) {
1191 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1192 write(fd, buffer, strlen(buffer));
1193 }
1194
Eric Laurent612bbb52012-03-14 15:03:26 -07001195 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1196 result.append(buffer);
1197 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1198 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001199 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1200 result.append(buffer);
1201 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1202 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001203 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1204 result.append(buffer);
1205 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001206 result.append(buffer);
1207 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1208 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001209 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1210 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001211 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1212 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001213 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001214 result.append(buffer);
1215
1216 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1217 result.append(buffer);
1218 result.append(" Index Command");
1219 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1220 snprintf(buffer, SIZE, "\n %02d ", i);
1221 result.append(buffer);
1222 result.append(mNewParameters[i]);
1223 }
1224
1225 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1226 result.append(buffer);
1227 snprintf(buffer, SIZE, " Index event param\n");
1228 result.append(buffer);
1229 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001230 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001231 result.append(buffer);
1232 }
1233 result.append("\n");
1234
1235 write(fd, result.string(), result.size());
1236
1237 if (locked) {
1238 mLock.unlock();
1239 }
1240 return NO_ERROR;
1241}
1242
Eric Laurent1d2bff02011-07-24 17:49:51 -07001243status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1244{
1245 const size_t SIZE = 256;
1246 char buffer[SIZE];
1247 String8 result;
1248
1249 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1250 write(fd, buffer, strlen(buffer));
1251
1252 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1253 sp<EffectChain> chain = mEffectChains[i];
1254 if (chain != 0) {
1255 chain->dump(fd, args);
1256 }
1257 }
1258 return NO_ERROR;
1259}
1260
Eric Laurentfeb0db62011-07-22 09:04:31 -07001261void AudioFlinger::ThreadBase::acquireWakeLock()
1262{
1263 Mutex::Autolock _l(mLock);
1264 acquireWakeLock_l();
1265}
1266
1267void AudioFlinger::ThreadBase::acquireWakeLock_l()
1268{
1269 if (mPowerManager == 0) {
1270 // use checkService() to avoid blocking if power service is not up yet
1271 sp<IBinder> binder =
1272 defaultServiceManager()->checkService(String16("power"));
1273 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001274 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001275 } else {
1276 mPowerManager = interface_cast<IPowerManager>(binder);
1277 binder->linkToDeath(mDeathRecipient);
1278 }
1279 }
1280 if (mPowerManager != 0) {
1281 sp<IBinder> binder = new BBinder();
1282 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1283 binder,
1284 String16(mName));
1285 if (status == NO_ERROR) {
1286 mWakeLockToken = binder;
1287 }
Steve Block3856b092011-10-20 11:56:00 +01001288 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001289 }
1290}
1291
1292void AudioFlinger::ThreadBase::releaseWakeLock()
1293{
1294 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001295 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001296}
1297
1298void AudioFlinger::ThreadBase::releaseWakeLock_l()
1299{
1300 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001301 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001302 if (mPowerManager != 0) {
1303 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1304 }
1305 mWakeLockToken.clear();
1306 }
1307}
1308
1309void AudioFlinger::ThreadBase::clearPowerManager()
1310{
1311 Mutex::Autolock _l(mLock);
1312 releaseWakeLock_l();
1313 mPowerManager.clear();
1314}
1315
1316void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1317{
1318 sp<ThreadBase> thread = mThread.promote();
1319 if (thread != 0) {
1320 thread->clearPowerManager();
1321 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001322 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001323}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001324
Eric Laurent59255e42011-07-27 19:49:51 -07001325void AudioFlinger::ThreadBase::setEffectSuspended(
1326 const effect_uuid_t *type, bool suspend, int sessionId)
1327{
1328 Mutex::Autolock _l(mLock);
1329 setEffectSuspended_l(type, suspend, sessionId);
1330}
1331
1332void AudioFlinger::ThreadBase::setEffectSuspended_l(
1333 const effect_uuid_t *type, bool suspend, int sessionId)
1334{
Glenn Kasten090f0192012-01-30 13:00:02 -08001335 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001336 if (chain != 0) {
1337 if (type != NULL) {
1338 chain->setEffectSuspended_l(type, suspend);
1339 } else {
1340 chain->setEffectSuspendedAll_l(suspend);
1341 }
1342 }
1343
1344 updateSuspendedSessions_l(type, suspend, sessionId);
1345}
1346
1347void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1348{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001349 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001350 if (index < 0) {
1351 return;
1352 }
1353
1354 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1355 mSuspendedSessions.editValueAt(index);
1356
1357 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001358 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001359 for (int j = 0; j < desc->mRefCount; j++) {
1360 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1361 chain->setEffectSuspendedAll_l(true);
1362 } else {
Steve Block3856b092011-10-20 11:56:00 +01001363 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001364 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001365 chain->setEffectSuspended_l(&desc->mType, true);
1366 }
1367 }
1368 }
1369}
1370
Eric Laurent59255e42011-07-27 19:49:51 -07001371void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1372 bool suspend,
1373 int sessionId)
1374{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001375 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001376
1377 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1378
1379 if (suspend) {
1380 if (index >= 0) {
1381 sessionEffects = mSuspendedSessions.editValueAt(index);
1382 } else {
1383 mSuspendedSessions.add(sessionId, sessionEffects);
1384 }
1385 } else {
1386 if (index < 0) {
1387 return;
1388 }
1389 sessionEffects = mSuspendedSessions.editValueAt(index);
1390 }
1391
1392
1393 int key = EffectChain::kKeyForSuspendAll;
1394 if (type != NULL) {
1395 key = type->timeLow;
1396 }
1397 index = sessionEffects.indexOfKey(key);
1398
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001399 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001400 if (suspend) {
1401 if (index >= 0) {
1402 desc = sessionEffects.valueAt(index);
1403 } else {
1404 desc = new SuspendedSessionDesc();
1405 if (type != NULL) {
1406 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1407 }
1408 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001409 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001410 }
1411 desc->mRefCount++;
1412 } else {
1413 if (index < 0) {
1414 return;
1415 }
1416 desc = sessionEffects.valueAt(index);
1417 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001418 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001419 sessionEffects.removeItemsAt(index);
1420 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001421 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001422 sessionId);
1423 mSuspendedSessions.removeItem(sessionId);
1424 }
1425 }
1426 }
1427 if (!sessionEffects.isEmpty()) {
1428 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1429 }
1430}
1431
1432void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1433 bool enabled,
1434 int sessionId)
1435{
1436 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001437 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1438}
Eric Laurent59255e42011-07-27 19:49:51 -07001439
Eric Laurenta85a74a2011-10-19 11:44:54 -07001440void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1441 bool enabled,
1442 int sessionId)
1443{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001444 if (mType != RECORD) {
1445 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1446 // another session. This gives the priority to well behaved effect control panels
1447 // and applications not using global effects.
1448 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1449 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1450 }
1451 }
Eric Laurent59255e42011-07-27 19:49:51 -07001452
1453 sp<EffectChain> chain = getEffectChain_l(sessionId);
1454 if (chain != 0) {
1455 chain->checkSuspendOnEffectEnabled(effect, enabled);
1456 }
1457}
1458
Mathias Agopian65ab4712010-07-14 17:59:35 -07001459// ----------------------------------------------------------------------------
1460
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001461AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1462 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001463 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001464 uint32_t device,
1465 type_t type)
1466 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001467 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1468 // Assumes constructor is called by AudioFlinger with it's mLock held,
1469 // but it would be safer to explicitly pass initial masterMute as parameter
1470 mMasterMute(audioFlinger->masterMute_l()),
1471 // mStreamTypes[] initialized in constructor body
1472 mOutput(output),
1473 // Assumes constructor is called by AudioFlinger with it's mLock held,
1474 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001475 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001476 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001477 mMixerStatus(MIXER_IDLE),
Glenn Kasten66fcab92012-02-24 14:59:21 -08001478 mPrevMixerStatus(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001479 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
1480 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1481 mFastTrackNewMask(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001482{
Glenn Kasten58912562012-04-03 10:45:00 -07001483#if !LOG_NDEBUG
1484 memset(mFastTrackNewArray, 0, sizeof(mFastTrackNewArray));
1485#endif
Glenn Kasten480b4682012-02-28 12:30:08 -08001486 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001487
Mathias Agopian65ab4712010-07-14 17:59:35 -07001488 readOutputParameters();
1489
Glenn Kasten263709e2012-01-06 08:40:01 -08001490 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001491 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1492 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1493 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001494 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1495 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001496 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001497 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1498 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001499}
1500
1501AudioFlinger::PlaybackThread::~PlaybackThread()
1502{
1503 delete [] mMixBuffer;
1504}
1505
1506status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1507{
1508 dumpInternals(fd, args);
1509 dumpTracks(fd, args);
1510 dumpEffectChains(fd, args);
1511 return NO_ERROR;
1512}
1513
1514status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1515{
1516 const size_t SIZE = 256;
1517 char buffer[SIZE];
1518 String8 result;
1519
Glenn Kasten58912562012-04-03 10:45:00 -07001520 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1521 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1522 const stream_type_t *st = &mStreamTypes[i];
1523 if (i > 0) {
1524 result.appendFormat(", ");
1525 }
1526 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1527 if (st->mute) {
1528 result.append("M");
1529 }
1530 }
1531 result.append("\n");
1532 write(fd, result.string(), result.length());
1533 result.clear();
1534
Mathias Agopian65ab4712010-07-14 17:59:35 -07001535 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1536 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001537 result.append(" Name Client Type Fmt Chn mask Session Frames S M F SRate L dB R dB "
1538 "Server User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001539 for (size_t i = 0; i < mTracks.size(); ++i) {
1540 sp<Track> track = mTracks[i];
1541 if (track != 0) {
1542 track->dump(buffer, SIZE);
1543 result.append(buffer);
1544 }
1545 }
1546
1547 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1548 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001549 result.append(" Name Client Type Fmt Chn mask Session Frames S M F SRate L dB R dB "
1550 "Server User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001551 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001552 sp<Track> track = mActiveTracks[i].promote();
1553 if (track != 0) {
1554 track->dump(buffer, SIZE);
1555 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001556 }
1557 }
1558 write(fd, result.string(), result.size());
1559 return NO_ERROR;
1560}
1561
Mathias Agopian65ab4712010-07-14 17:59:35 -07001562status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1563{
1564 const size_t SIZE = 256;
1565 char buffer[SIZE];
1566 String8 result;
1567
1568 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1569 result.append(buffer);
1570 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1571 result.append(buffer);
1572 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1573 result.append(buffer);
1574 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1575 result.append(buffer);
1576 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1577 result.append(buffer);
1578 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1579 result.append(buffer);
1580 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1581 result.append(buffer);
1582 write(fd, result.string(), result.size());
1583
1584 dumpBase(fd, args);
1585
1586 return NO_ERROR;
1587}
1588
1589// Thread virtuals
1590status_t AudioFlinger::PlaybackThread::readyToRun()
1591{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001592 status_t status = initCheck();
1593 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001594 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001595 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001596 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001597 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001598 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001599}
1600
1601void AudioFlinger::PlaybackThread::onFirstRef()
1602{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001603 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001604}
1605
1606// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001607sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001608 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001609 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001611 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001612 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001613 int frameCount,
1614 const sp<IMemory>& sharedBuffer,
1615 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001616 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001617 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001618 status_t *status)
1619{
1620 sp<Track> track;
1621 status_t lStatus;
1622
Glenn Kasten73d22752012-03-19 13:38:30 -07001623 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1624
1625 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001626 if (flags & IAudioFlinger::TRACK_FAST) {
1627 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001628 // not timed
1629 (!isTimed) &&
1630 // either of these use cases:
1631 (
1632 // use case 1: shared buffer with any frame count
1633 (
1634 (sharedBuffer != 0)
1635 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001636 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001637 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001638 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001639 ((frameCount == 0) ||
1640 (frameCount >= (int) mFrameCount)) // FIXME int cast is due to wrong parameter type
Glenn Kasten73d22752012-03-19 13:38:30 -07001641 )
1642 ) &&
1643 // PCM data
1644 audio_is_linear_pcm(format) &&
1645 // mono or stereo
1646 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1647 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001648#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001649 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001650 (sampleRate == mSampleRate) &&
1651#endif
1652 // normal mixer has an associated fast mixer
1653 hasFastMixer() &&
1654 // there are sufficient fast track slots available
1655 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001656 // FIXME test that MixerThread for this fast track has a capable output HAL
1657 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001658 ) {
1659 ALOGI("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1660 frameCount, mFrameCount);
1661 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1662 if (frameCount == 0) {
1663 frameCount = mFrameCount;
1664 }
1665 } else {
1666 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001667 "mFrameCount=%d format=%d isLinear=%d channelMask=%d sampleRate=%d mSampleRate=%d "
1668 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1669 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1670 audio_is_linear_pcm(format),
1671 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001672 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001673 // For compatibility with AudioTrack calculation, buffer depth is forced
1674 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1675 // This is probably too conservative, but legacy application code may depend on it.
1676 // If you change this calculation, also review the start threshold which is related.
1677 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1678 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1679 if (minBufCount < 2) {
1680 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001681 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001682 int minFrameCount = mNormalFrameCount * minBufCount;
1683 if (frameCount < minFrameCount) {
1684 frameCount = minFrameCount;
1685 }
1686 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001687 }
1688
Mathias Agopian65ab4712010-07-14 17:59:35 -07001689 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001690 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1691 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001692 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001693 "for output %p with format %d",
1694 sampleRate, format, channelMask, mOutput, mFormat);
1695 lStatus = BAD_VALUE;
1696 goto Exit;
1697 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001698 }
1699 } else {
1700 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1701 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001702 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001703 lStatus = BAD_VALUE;
1704 goto Exit;
1705 }
1706 }
1707
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001708 lStatus = initCheck();
1709 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001710 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001711 goto Exit;
1712 }
1713
1714 { // scope for mLock
1715 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001716
1717 // all tracks in same audio session must share the same routing strategy otherwise
1718 // conflicts will happen when tracks are moved from one output to another by audio policy
1719 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001720 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001721 for (size_t i = 0; i < mTracks.size(); ++i) {
1722 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001723 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001724 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001725 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001726 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001727 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001728 lStatus = BAD_VALUE;
1729 goto Exit;
1730 }
1731 }
1732 }
1733
John Grossman4ff14ba2012-02-08 16:37:41 -08001734 if (!isTimed) {
1735 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001736 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001737 } else {
1738 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1739 channelMask, frameCount, sharedBuffer, sessionId);
1740 }
1741 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742 lStatus = NO_MEMORY;
1743 goto Exit;
1744 }
1745 mTracks.add(track);
1746
1747 sp<EffectChain> chain = getEffectChain_l(sessionId);
1748 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001749 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001750 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001751 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001752 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001753 }
1754 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001755
1756#ifdef HAVE_REQUEST_PRIORITY
1757 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1758 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1759 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1760 // so ask activity manager to do this on our behalf
1761 int err = requestPriority(callingPid, tid, 1);
1762 if (err != 0) {
1763 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1764 1, callingPid, tid, err);
1765 }
1766 }
1767#endif
1768
Mathias Agopian65ab4712010-07-14 17:59:35 -07001769 lStatus = NO_ERROR;
1770
1771Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001772 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001773 *status = lStatus;
1774 }
1775 return track;
1776}
1777
1778uint32_t AudioFlinger::PlaybackThread::latency() const
1779{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001780 Mutex::Autolock _l(mLock);
1781 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001782 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001783 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001784 return 0;
1785 }
1786}
1787
Glenn Kasten6637baa2012-01-09 09:40:36 -08001788void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001789{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001790 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001791 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001792}
1793
Glenn Kasten6637baa2012-01-09 09:40:36 -08001794void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001795{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001796 Mutex::Autolock _l(mLock);
1797 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001798}
1799
Glenn Kasten6637baa2012-01-09 09:40:36 -08001800void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001801{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001802 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001803 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001804}
1805
Glenn Kasten6637baa2012-01-09 09:40:36 -08001806void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001807{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001808 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001809 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001810}
1811
Glenn Kastenfff6d712012-01-12 16:38:12 -08001812float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001813{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001814 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001815 return mStreamTypes[stream].volume;
1816}
1817
Mathias Agopian65ab4712010-07-14 17:59:35 -07001818// addTrack_l() must be called with ThreadBase::mLock held
1819status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1820{
1821 status_t status = ALREADY_EXISTS;
1822
1823 // set retry count for buffer fill
1824 track->mRetryCount = kMaxTrackStartupRetries;
1825 if (mActiveTracks.indexOf(track) < 0) {
1826 // the track is newly added, make sure it fills up all its
1827 // buffers before playing. This is to ensure the client will
1828 // effectively get the latency it requested.
1829 track->mFillingUpStatus = Track::FS_FILLING;
1830 track->mResetDone = false;
1831 mActiveTracks.add(track);
1832 if (track->mainBuffer() != mMixBuffer) {
1833 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1834 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001835 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001836 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001837 }
1838 }
1839
1840 status = NO_ERROR;
1841 }
1842
Steve Block3856b092011-10-20 11:56:00 +01001843 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001844 mWaitWorkCV.broadcast();
1845
1846 return status;
1847}
1848
1849// destroyTrack_l() must be called with ThreadBase::mLock held
1850void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1851{
1852 track->mState = TrackBase::TERMINATED;
1853 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001854 removeTrack_l(track);
1855 }
1856}
1857
1858void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1859{
1860 mTracks.remove(track);
1861 deleteTrackName_l(track->name());
1862 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1863 if (chain != 0) {
1864 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001865 }
1866}
1867
1868String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1869{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001870 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001871 char *s;
1872
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001873 Mutex::Autolock _l(mLock);
1874 if (initCheck() != NO_ERROR) {
1875 return out_s8;
1876 }
1877
Dima Zavin799a70e2011-04-18 16:57:27 -07001878 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001879 out_s8 = String8(s);
1880 free(s);
1881 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001882}
1883
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001884// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001885void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1886 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001887 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001888
Steve Block3856b092011-10-20 11:56:00 +01001889 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001890
1891 switch (event) {
1892 case AudioSystem::OUTPUT_OPENED:
1893 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001894 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001895 desc.samplingRate = mSampleRate;
1896 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001897 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001898 desc.latency = latency();
1899 param2 = &desc;
1900 break;
1901
1902 case AudioSystem::STREAM_CONFIG_CHANGED:
1903 param2 = &param;
1904 case AudioSystem::OUTPUT_CLOSED:
1905 default:
1906 break;
1907 }
1908 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1909}
1910
1911void AudioFlinger::PlaybackThread::readOutputParameters()
1912{
Dima Zavin799a70e2011-04-18 16:57:27 -07001913 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001914 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1915 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001916 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001917 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001918 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001919 if (mFrameCount & 15) {
1920 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1921 mFrameCount);
1922 }
1923
1924 // Calculate size of normal mix buffer
1925 if (mType == MIXER) {
1926 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1927 mNormalFrameCount = ((minNormalFrameCount + mFrameCount - 1) / mFrameCount) * mFrameCount;
1928 if (mNormalFrameCount & 15) {
1929 ALOGW("Normal mix buffer size is %u frames but AudioMixer requires multiples of 16 "
1930 "frames", mNormalFrameCount);
1931 }
1932 } else {
1933 mNormalFrameCount = mFrameCount;
1934 }
1935 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001936
1937 // FIXME - Current mixer implementation only supports stereo output: Always
1938 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001939 delete[] mMixBuffer;
Glenn Kasten58912562012-04-03 10:45:00 -07001940 mMixBuffer = new int16_t[mNormalFrameCount * 2];
1941 memset(mMixBuffer, 0, mNormalFrameCount * 2 * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001942
Eric Laurentde070132010-07-13 04:45:46 -07001943 // force reconfiguration of effect chains and engines to take new buffer size and audio
1944 // parameters into account
1945 // Note that mLock is not held when readOutputParameters() is called from the constructor
1946 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1947 // matter.
1948 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1949 Vector< sp<EffectChain> > effectChains = mEffectChains;
1950 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001951 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001952 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001953}
1954
1955status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1956{
Glenn Kastena0d68332012-01-27 16:47:15 -08001957 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001958 return BAD_VALUE;
1959 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001960 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001961 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001962 return INVALID_OPERATION;
1963 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001964 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001965
Dima Zavin799a70e2011-04-18 16:57:27 -07001966 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001967}
1968
Eric Laurent39e94f82010-07-28 01:32:47 -07001969uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001970{
1971 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001972 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001973 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001974 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001975 }
1976
1977 for (size_t i = 0; i < mTracks.size(); ++i) {
1978 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001979 if (sessionId == track->sessionId() &&
1980 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001981 result |= TRACK_SESSION;
1982 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001983 }
1984 }
1985
Eric Laurent39e94f82010-07-28 01:32:47 -07001986 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001987}
1988
Eric Laurentde070132010-07-13 04:45:46 -07001989uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1990{
Dima Zavinfce7a472011-04-19 22:30:36 -07001991 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001992 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001993 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1994 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001995 }
1996 for (size_t i = 0; i < mTracks.size(); i++) {
1997 sp<Track> track = mTracks[i];
1998 if (sessionId == track->sessionId() &&
1999 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002000 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002001 }
2002 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002003 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002004}
2005
Mathias Agopian65ab4712010-07-14 17:59:35 -07002006
Glenn Kastenaed850d2012-01-26 09:46:34 -08002007AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002008{
2009 Mutex::Autolock _l(mLock);
2010 return mOutput;
2011}
2012
2013AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2014{
2015 Mutex::Autolock _l(mLock);
2016 AudioStreamOut *output = mOutput;
2017 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002018 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2019 // must push a NULL and wait for ack
2020 mOutputSink.clear();
2021 mPipeSink.clear();
2022 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002023 return output;
2024}
2025
2026// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002027audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002028{
2029 if (mOutput == NULL) {
2030 return NULL;
2031 }
2032 return &mOutput->stream->common;
2033}
2034
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002035uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002036{
2037 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
2038 // decoding and transfer time. So sleeping for half of the latency would likely cause
2039 // underruns
2040 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002041 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002042 } else {
2043 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
2044 }
2045}
2046
Eric Laurenta011e352012-03-29 15:51:43 -07002047status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2048{
2049 if (!isValidSyncEvent(event)) {
2050 return BAD_VALUE;
2051 }
2052
2053 Mutex::Autolock _l(mLock);
2054
2055 for (size_t i = 0; i < mTracks.size(); ++i) {
2056 sp<Track> track = mTracks[i];
2057 if (event->triggerSession() == track->sessionId()) {
2058 track->setSyncEvent(event);
2059 return NO_ERROR;
2060 }
2061 }
2062
2063 return NAME_NOT_FOUND;
2064}
2065
2066bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2067{
2068 switch (event->type()) {
2069 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2070 return true;
2071 default:
2072 break;
2073 }
2074 return false;
2075}
2076
Mathias Agopian65ab4712010-07-14 17:59:35 -07002077// ----------------------------------------------------------------------------
2078
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002079AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002080 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002081 : PlaybackThread(audioFlinger, output, id, device, type),
2082 // mAudioMixer below
2083#ifdef SOAKER
2084 mSoaker(NULL),
2085#endif
2086 // mFastMixer below
2087 mFastMixerFutex(0)
2088 // mOutputSink below
2089 // mPipeSink below
2090 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002091{
Glenn Kasten58912562012-04-03 10:45:00 -07002092 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2093 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2094 "mFrameCount=%d, mNormalFrameCount=%d",
2095 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2096 mNormalFrameCount);
2097 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2098
Mathias Agopian65ab4712010-07-14 17:59:35 -07002099 // FIXME - Current mixer implementation only supports stereo output
2100 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002101 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002102 }
Glenn Kasten58912562012-04-03 10:45:00 -07002103
2104 // create an NBAIO sink for the HAL output stream, and negotiate
2105 mOutputSink = new AudioStreamOutSink(output->stream);
2106 size_t numCounterOffers = 0;
2107 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2108 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2109 ALOG_ASSERT(index == 0);
2110
2111 // initialize fast mixer if needed
2112 if (mFrameCount < mNormalFrameCount) {
2113
2114 // create a MonoPipe to connect our submix to FastMixer
2115 NBAIO_Format format = mOutputSink->format();
2116 // frame count will be rounded up to a power of 2, so this formula should work well
2117 MonoPipe *monoPipe = new MonoPipe((mNormalFrameCount * 3) / 2, format,
2118 true /*writeCanBlock*/);
2119 const NBAIO_Format offers[1] = {format};
2120 size_t numCounterOffers = 0;
2121 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2122 ALOG_ASSERT(index == 0);
2123 mPipeSink = monoPipe;
2124
2125#ifdef SOAKER
2126 // create a soaker as workaround for governor issues
2127 mSoaker = new Soaker();
2128 // FIXME Soaker should only run when needed, i.e. when FastMixer is not in COLD_IDLE
2129 mSoaker->run("Soaker", PRIORITY_LOWEST);
2130#endif
2131
2132 // create fast mixer and configure it initially with just one fast track for our submix
2133 mFastMixer = new FastMixer();
2134 FastMixerStateQueue *sq = mFastMixer->sq();
2135 FastMixerState *state = sq->begin();
2136 FastTrack *fastTrack = &state->mFastTracks[0];
2137 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2138 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2139 fastTrack->mVolumeProvider = NULL;
2140 fastTrack->mGeneration++;
2141 state->mFastTracksGen++;
2142 state->mTrackMask = 1;
2143 // fast mixer will use the HAL output sink
2144 state->mOutputSink = mOutputSink.get();
2145 state->mOutputSinkGen++;
2146 state->mFrameCount = mFrameCount;
2147 state->mCommand = FastMixerState::COLD_IDLE;
2148 // already done in constructor initialization list
2149 //mFastMixerFutex = 0;
2150 state->mColdFutexAddr = &mFastMixerFutex;
2151 state->mColdGen++;
2152 state->mDumpState = &mFastMixerDumpState;
2153 sq->end();
2154 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2155
2156 // start the fast mixer
2157 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2158#ifdef HAVE_REQUEST_PRIORITY
2159 pid_t tid = mFastMixer->getTid();
2160 int err = requestPriority(getpid_cached, tid, 2);
2161 if (err != 0) {
2162 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2163 2, getpid_cached, tid, err);
2164 }
2165#endif
2166
2167 } else {
2168 mFastMixer = NULL;
2169 }
2170 mNormalSink = mOutputSink;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002171}
2172
2173AudioFlinger::MixerThread::~MixerThread()
2174{
Glenn Kasten58912562012-04-03 10:45:00 -07002175 if (mFastMixer != NULL) {
2176 FastMixerStateQueue *sq = mFastMixer->sq();
2177 FastMixerState *state = sq->begin();
2178 if (state->mCommand == FastMixerState::COLD_IDLE) {
2179 int32_t old = android_atomic_inc(&mFastMixerFutex);
2180 if (old == -1) {
2181 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2182 }
2183 }
2184 state->mCommand = FastMixerState::EXIT;
2185 sq->end();
2186 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2187 mFastMixer->join();
2188 // Though the fast mixer thread has exited, it's state queue is still valid.
2189 // We'll use that extract the final state which contains one remaining fast track
2190 // corresponding to our sub-mix.
2191 state = sq->begin();
2192 ALOG_ASSERT(state->mTrackMask == 1);
2193 FastTrack *fastTrack = &state->mFastTracks[0];
2194 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2195 delete fastTrack->mBufferProvider;
2196 sq->end(false /*didModify*/);
2197 delete mFastMixer;
2198#ifdef SOAKER
2199 if (mSoaker != NULL) {
2200 mSoaker->requestExitAndWait();
2201 }
2202 delete mSoaker;
2203#endif
2204 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002205 delete mAudioMixer;
2206}
2207
Glenn Kasten83efdd02012-02-24 07:21:32 -08002208class CpuStats {
2209public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002210 CpuStats();
2211 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002212#ifdef DEBUG_CPU_USAGE
2213private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002214 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2215 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2216
2217 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2218
2219 int mCpuNum; // thread's current CPU number
2220 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002221#endif
2222};
2223
Glenn Kasten190a46f2012-03-06 11:27:10 -08002224CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002225#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002226 : mCpuNum(-1), mCpukHz(-1)
2227#endif
2228{
2229}
2230
2231void CpuStats::sample(const String8 &title) {
2232#ifdef DEBUG_CPU_USAGE
2233 // get current thread's delta CPU time in wall clock ns
2234 double wcNs;
2235 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2236
2237 // record sample for wall clock statistics
2238 if (valid) {
2239 mWcStats.sample(wcNs);
2240 }
2241
2242 // get the current CPU number
2243 int cpuNum = sched_getcpu();
2244
2245 // get the current CPU frequency in kHz
2246 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2247
2248 // check if either CPU number or frequency changed
2249 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2250 mCpuNum = cpuNum;
2251 mCpukHz = cpukHz;
2252 // ignore sample for purposes of cycles
2253 valid = false;
2254 }
2255
2256 // if no change in CPU number or frequency, then record sample for cycle statistics
2257 if (valid && mCpukHz > 0) {
2258 double cycles = wcNs * cpukHz * 0.000001;
2259 mHzStats.sample(cycles);
2260 }
2261
2262 unsigned n = mWcStats.n();
2263 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002264 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002265 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002266 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2267 double perLoop = elapsed / (double) n;
2268 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002269 double perLoop1k = perLoop * 0.001;
2270 double mean = mWcStats.mean();
2271 double stddev = mWcStats.stddev();
2272 double minimum = mWcStats.minimum();
2273 double maximum = mWcStats.maximum();
2274 double meanCycles = mHzStats.mean();
2275 double stddevCycles = mHzStats.stddev();
2276 double minCycles = mHzStats.minimum();
2277 double maxCycles = mHzStats.maximum();
2278 mCpuUsage.resetElapsed();
2279 mWcStats.reset();
2280 mHzStats.reset();
2281 ALOGD("CPU usage for %s over past %.1f secs\n"
2282 " (%u mixer loops at %.1f mean ms per loop):\n"
2283 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2284 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2285 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2286 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002287 elapsed * .000000001, n, perLoop * .000001,
2288 mean * .001,
2289 stddev * .001,
2290 minimum * .001,
2291 maximum * .001,
2292 mean / perLoop100,
2293 stddev / perLoop100,
2294 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002295 maximum / perLoop100,
2296 meanCycles / perLoop1k,
2297 stddevCycles / perLoop1k,
2298 minCycles / perLoop1k,
2299 maxCycles / perLoop1k);
2300
Glenn Kasten83efdd02012-02-24 07:21:32 -08002301 }
2302 }
2303#endif
2304};
2305
Glenn Kasten37d825e2012-02-24 07:21:48 -08002306void AudioFlinger::PlaybackThread::checkSilentMode_l()
2307{
2308 if (!mMasterMute) {
2309 char value[PROPERTY_VALUE_MAX];
2310 if (property_get("ro.audio.silent", value, "0") > 0) {
2311 char *endptr;
2312 unsigned long ul = strtoul(value, &endptr, 0);
2313 if (*endptr == '\0' && ul != 0) {
2314 ALOGD("Silence is golden");
2315 // The setprop command will not allow a property to be changed after
2316 // the first time it is set, so we don't have to worry about un-muting.
2317 setMasterMute_l(true);
2318 }
2319 }
2320 }
2321}
2322
Glenn Kasten000f0e32012-03-01 17:10:56 -08002323bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002324{
2325 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002326
Glenn Kasten000f0e32012-03-01 17:10:56 -08002327 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002328
2329 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002330 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002331if (mType == MIXER) {
2332 longStandbyExit = false;
2333}
Glenn Kasten688a6402012-02-29 07:57:06 -08002334
Glenn Kasten000f0e32012-03-01 17:10:56 -08002335 // DUPLICATING
2336 // FIXME could this be made local to while loop?
2337 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002338
Glenn Kasten66fcab92012-02-24 14:59:21 -08002339 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002340 sleepTime = idleSleepTime;
2341
2342if (mType == MIXER) {
2343 sleepTimeShift = 0;
2344}
2345
Glenn Kasten83efdd02012-02-24 07:21:32 -08002346 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002347 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002348
Eric Laurentfeb0db62011-07-22 09:04:31 -07002349 acquireWakeLock();
2350
Mathias Agopian65ab4712010-07-14 17:59:35 -07002351 while (!exitPending())
2352 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002353 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002354
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002355 Vector< sp<EffectChain> > effectChains;
2356
Mathias Agopian65ab4712010-07-14 17:59:35 -07002357 processConfigEvents();
2358
Mathias Agopian65ab4712010-07-14 17:59:35 -07002359 { // scope for mLock
2360
2361 Mutex::Autolock _l(mLock);
2362
2363 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002364 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002365 }
2366
Glenn Kastenfa26a852012-03-06 11:28:04 -08002367 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002368
Mathias Agopian65ab4712010-07-14 17:59:35 -07002369 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002370 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002371 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002372 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002373
2374 threadLoop_standby();
2375
Mathias Agopian65ab4712010-07-14 17:59:35 -07002376 mStandby = true;
2377 mBytesWritten = 0;
2378 }
2379
Glenn Kasten3e074702012-02-28 18:40:35 -08002380 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002381 // we're about to wait, flush the binder command buffer
2382 IPCThreadState::self()->flushCommands();
2383
Glenn Kastenfa26a852012-03-06 11:28:04 -08002384 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002385
Mathias Agopian65ab4712010-07-14 17:59:35 -07002386 if (exitPending()) break;
2387
Eric Laurentfeb0db62011-07-22 09:04:31 -07002388 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002389 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002390 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002391 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002392 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002393 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002394
Eric Laurent27741442012-01-17 19:20:12 -08002395 mPrevMixerStatus = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002396
Glenn Kasten37d825e2012-02-24 07:21:48 -08002397 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002398
Glenn Kasten000f0e32012-03-01 17:10:56 -08002399 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002400 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002401 if (mType == MIXER) {
2402 sleepTimeShift = 0;
2403 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002404
Mathias Agopian65ab4712010-07-14 17:59:35 -07002405 continue;
2406 }
2407 }
2408
Glenn Kastenfec279f2012-03-08 07:47:15 -08002409 mixer_state newMixerStatus = prepareTracks_l(&tracksToRemove);
2410 // Shift in the new status; this could be a queue if it's
2411 // useful to filter the mixer status over several cycles.
2412 mPrevMixerStatus = mMixerStatus;
2413 mMixerStatus = newMixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002414
2415 // prevent any changes in effect chain list and in each effect chain
2416 // during mixing and effect process as the audio buffers could be deleted
2417 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002418 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002419 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002420
Glenn Kastenfec279f2012-03-08 07:47:15 -08002421 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002422 threadLoop_mix();
2423 } else {
2424 threadLoop_sleepTime();
2425 }
2426
2427 if (mSuspended > 0) {
2428 sleepTime = suspendSleepTimeUs();
2429 }
2430
2431 // only process effects if we're going to write
2432 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002433 for (size_t i = 0; i < effectChains.size(); i ++) {
2434 effectChains[i]->process_l();
2435 }
2436 }
2437
2438 // enable changes in effect chain
2439 unlockEffectChains(effectChains);
2440
2441 // sleepTime == 0 means we must write to audio hardware
2442 if (sleepTime == 0) {
2443
2444 threadLoop_write();
2445
2446if (mType == MIXER) {
2447 // write blocked detection
2448 nsecs_t now = systemTime();
2449 nsecs_t delta = now - mLastWriteTime;
2450 if (!mStandby && delta > maxPeriod) {
2451 mNumDelayedWrites++;
2452 if ((now - lastWarning) > kWarningThrottleNs) {
2453 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2454 ns2ms(delta), mNumDelayedWrites, this);
2455 lastWarning = now;
2456 }
2457 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2458 // a different threshold. Or completely removed for what it is worth anyway...
2459 if (mStandby) {
2460 longStandbyExit = true;
2461 }
2462 }
2463}
2464
2465 mStandby = false;
2466 } else {
2467 usleep(sleepTime);
2468 }
2469
Glenn Kasten58912562012-04-03 10:45:00 -07002470 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002471 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002472 // same lock. This will also mutate and push a new fast mixer state.
2473 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002474 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002475
Glenn Kastenfa26a852012-03-06 11:28:04 -08002476 // FIXME I don't understand the need for this here;
2477 // it was in the original code but maybe the
2478 // assignment in saveOutputTracks() makes this unnecessary?
2479 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002480
2481 // Effect chains will be actually deleted here if they were removed from
2482 // mEffectChains list during mixing or effects processing
2483 effectChains.clear();
2484
2485 // FIXME Note that the above .clear() is no longer necessary since effectChains
2486 // is now local to this block, but will keep it for now (at least until merge done).
2487 }
2488
2489if (mType == MIXER || mType == DIRECT) {
2490 // put output stream into standby mode
2491 if (!mStandby) {
2492 mOutput->stream->common.standby(&mOutput->stream->common);
2493 }
2494}
2495if (mType == DUPLICATING) {
2496 // for DuplicatingThread, standby mode is handled by the outputTracks
2497}
2498
2499 releaseWakeLock();
2500
2501 ALOGV("Thread %p type %d exiting", this, mType);
2502 return false;
2503}
2504
Glenn Kasten58912562012-04-03 10:45:00 -07002505// FIXME This method needs a better name.
2506// It pushes a new fast mixer state and returns (via tracksToRemove) a set of tracks to remove.
2507void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2508{
2509 // were any of the removed tracks also fast tracks?
2510 unsigned removedMask = 0;
2511 for (size_t i = 0; i < tracksToRemove.size(); ++i) {
2512 if (tracksToRemove[i]->isFastTrack()) {
2513 int j = tracksToRemove[i]->mFastIndex;
2514 ALOG_ASSERT(0 < j && j < FastMixerState::kMaxFastTracks);
2515 removedMask |= 1 << j;
2516 }
2517 }
2518 Track* newArray[FastMixerState::kMaxFastTracks];
2519 unsigned newMask;
2520 {
2521 AutoMutex _l(mLock);
2522 mFastTrackAvailMask |= removedMask;
2523 newMask = mFastTrackNewMask;
2524 if (newMask) {
2525 mFastTrackNewMask = 0;
2526 memcpy(newArray, mFastTrackNewArray, sizeof(mFastTrackNewArray));
2527#if !LOG_NDEBUG
2528 memset(mFastTrackNewArray, 0, sizeof(mFastTrackNewArray));
2529#endif
2530 }
2531 }
2532 unsigned changedMask = newMask | removedMask;
2533 // are there any newly added or removed fast tracks?
2534 if (changedMask) {
2535
2536 // This assert would be incorrect because it's theoretically possible (though unlikely)
2537 // for a track to be created and then removed within the same normal mix cycle:
2538 // ALOG_ASSERT(!(newMask & removedMask));
2539 // The converse, of removing a track and then creating a new track at the identical slot
2540 // within the same normal mix cycle, is impossible because the slot isn't marked available.
2541
2542 // prepare a new state to push
2543 FastMixerStateQueue *sq = mFastMixer->sq();
2544 FastMixerState *state = sq->begin();
2545 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2546 while (changedMask) {
2547 int j = __builtin_ctz(changedMask);
2548 ALOG_ASSERT(0 < j && j < FastMixerState::kMaxFastTracks);
2549 changedMask &= ~(1 << j);
2550 FastTrack *fastTrack = &state->mFastTracks[j];
2551 // must first do new tracks, then removed tracks, in case same track in both
2552 if (newMask & (1 << j)) {
2553 ALOG_ASSERT(!(state->mTrackMask & (1 << j)));
2554 ALOG_ASSERT(fastTrack->mBufferProvider == NULL &&
2555 fastTrack->mVolumeProvider == NULL);
2556 Track *track = newArray[j];
2557 AudioBufferProvider *abp = track;
2558 VolumeProvider *vp = track;
2559 fastTrack->mBufferProvider = abp;
2560 fastTrack->mVolumeProvider = vp;
2561 fastTrack->mSampleRate = track->mSampleRate;
2562 fastTrack->mChannelMask = track->mChannelMask;
2563 state->mTrackMask |= 1 << j;
2564 }
2565 if (removedMask & (1 << j)) {
2566 ALOG_ASSERT(state->mTrackMask & (1 << j));
2567 ALOG_ASSERT(fastTrack->mBufferProvider != NULL &&
2568 fastTrack->mVolumeProvider != NULL);
2569 fastTrack->mBufferProvider = NULL;
2570 fastTrack->mVolumeProvider = NULL;
2571 fastTrack->mSampleRate = mSampleRate;
2572 fastTrack->mChannelMask = AUDIO_CHANNEL_OUT_STEREO;
2573 state->mTrackMask &= ~(1 << j);
2574 }
2575 fastTrack->mGeneration++;
2576 }
2577 state->mFastTracksGen++;
2578 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
2579 if (state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
2580 state->mCommand = FastMixerState::COLD_IDLE;
2581 state->mColdFutexAddr = &mFastMixerFutex;
2582 state->mColdGen++;
2583 mFastMixerFutex = 0;
2584 mNormalSink = mOutputSink;
2585 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2586 }
2587 sq->end();
2588 // If any fast tracks were removed, we must wait for acknowledgement
2589 // because we're about to decrement the last sp<> on those tracks.
2590 // Similarly if we put it into cold idle, need to wait for acknowledgement
2591 // so that it stops doing I/O.
2592 if (removedMask) {
2593 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2594 }
2595 sq->push(block);
2596 }
2597 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2598}
2599
2600void AudioFlinger::MixerThread::threadLoop_write()
2601{
2602 // FIXME we should only do one push per cycle; confirm this is true
2603 // Start the fast mixer if it's not already running
2604 if (mFastMixer != NULL) {
2605 FastMixerStateQueue *sq = mFastMixer->sq();
2606 FastMixerState *state = sq->begin();
2607 if (state->mCommand != FastMixerState::MIX_WRITE && state->mTrackMask > 1) {
2608 if (state->mCommand == FastMixerState::COLD_IDLE) {
2609 int32_t old = android_atomic_inc(&mFastMixerFutex);
2610 if (old == -1) {
2611 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2612 }
2613 }
2614 state->mCommand = FastMixerState::MIX_WRITE;
2615 sq->end();
2616 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2617 mNormalSink = mPipeSink;
2618 } else {
2619 sq->end(false /*didModify*/);
2620 }
2621 }
2622 PlaybackThread::threadLoop_write();
2623}
2624
Glenn Kasten000f0e32012-03-01 17:10:56 -08002625// shared by MIXER and DIRECT, overridden by DUPLICATING
2626void AudioFlinger::PlaybackThread::threadLoop_write()
2627{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002628 // FIXME rewrite to reduce number of system calls
2629 mLastWriteTime = systemTime();
2630 mInWrite = true;
Glenn Kasten58912562012-04-03 10:45:00 -07002631 int bytesWritten;
2632
2633 // If an NBAIO sink is present, use it to write the normal mixer's submix
2634 if (mNormalSink != 0) {
2635#define mBitShift 2 // FIXME
2636 size_t count = mixBufferSize >> mBitShift;
2637 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
2638 if (framesWritten > 0) {
2639 bytesWritten = framesWritten << mBitShift;
2640 } else {
2641 bytesWritten = framesWritten;
2642 }
2643
2644 // otherwise use the HAL / AudioStreamOut directly
2645 } else {
2646 // FIXME legacy, remove
2647 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2648 }
2649
2650 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002651 mNumWrites++;
2652 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002653}
2654
Glenn Kasten58912562012-04-03 10:45:00 -07002655void AudioFlinger::MixerThread::threadLoop_standby()
2656{
2657 // Idle the fast mixer if it's currently running
2658 if (mFastMixer != NULL) {
2659 FastMixerStateQueue *sq = mFastMixer->sq();
2660 FastMixerState *state = sq->begin();
2661 if (!(state->mCommand & FastMixerState::IDLE)) {
2662 state->mCommand = FastMixerState::COLD_IDLE;
2663 state->mColdFutexAddr = &mFastMixerFutex;
2664 state->mColdGen++;
2665 mFastMixerFutex = 0;
2666 sq->end();
2667 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2668 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2669 mNormalSink = mOutputSink;
2670 } else {
2671 sq->end(false /*didModify*/);
2672 }
2673 }
2674 PlaybackThread::threadLoop_standby();
2675}
2676
Glenn Kasten000f0e32012-03-01 17:10:56 -08002677// shared by MIXER and DIRECT, overridden by DUPLICATING
2678void AudioFlinger::PlaybackThread::threadLoop_standby()
2679{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002680 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2681 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002682}
2683
2684void AudioFlinger::MixerThread::threadLoop_mix()
2685{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002686 // obtain the presentation timestamp of the next output buffer
2687 int64_t pts;
2688 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002689
Glenn Kasten952eeb22012-03-06 11:30:57 -08002690 if (NULL != mOutput->stream->get_next_write_timestamp) {
2691 status = mOutput->stream->get_next_write_timestamp(
2692 mOutput->stream, &pts);
2693 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002694
Glenn Kasten952eeb22012-03-06 11:30:57 -08002695 if (status != NO_ERROR) {
2696 pts = AudioBufferProvider::kInvalidPTS;
2697 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002698
Glenn Kasten952eeb22012-03-06 11:30:57 -08002699 // mix buffers...
2700 mAudioMixer->process(pts);
2701 // increase sleep time progressively when application underrun condition clears.
2702 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2703 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2704 // such that we would underrun the audio HAL.
2705 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2706 sleepTimeShift--;
2707 }
2708 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002709 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002710 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002711}
2712
2713void AudioFlinger::MixerThread::threadLoop_sleepTime()
2714{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002715 // If no tracks are ready, sleep once for the duration of an output
2716 // buffer size, then write 0s to the output
2717 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002718 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002719 sleepTime = activeSleepTime >> sleepTimeShift;
2720 if (sleepTime < kMinThreadSleepTimeUs) {
2721 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002722 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002723 // reduce sleep time in case of consecutive application underruns to avoid
2724 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2725 // duration we would end up writing less data than needed by the audio HAL if
2726 // the condition persists.
2727 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2728 sleepTimeShift++;
2729 }
2730 } else {
2731 sleepTime = idleSleepTime;
2732 }
2733 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002734 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002735 memset (mMixBuffer, 0, mixBufferSize);
2736 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002737 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002738 }
2739 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002740}
2741
2742// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002743AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002744 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002745{
2746
Glenn Kasten29c23c32012-01-26 13:37:52 -08002747 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002748 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002749 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002750 size_t mixedTracks = 0;
2751 size_t tracksWithEffect = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07002752 size_t fastTracks = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002753
2754 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002755 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002756
Eric Laurent571d49c2010-08-11 05:20:11 -07002757 if (masterMute) {
2758 masterVolume = 0;
2759 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002760 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002761 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002762 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002763 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002764 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002765 masterVolume = (float)((v + (1 << 23)) >> 24);
2766 chain.clear();
2767 }
2768
2769 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002770 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002771 if (t == 0) continue;
2772
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002773 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002774 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002775
2776 if (track->isFastTrack()) {
2777 // cache the combined master volume and stream type volume for fast mixer;
2778 // this lacks any synchronization or barrier so VolumeProvider may read a stale value
2779 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
2780 ++fastTracks;
2781 if (track->isTerminated()) {
2782 tracksToRemove->add(track);
2783 }
2784 continue;
2785 }
2786
2787 { // local variable scope to avoid goto warning
2788
Mathias Agopian65ab4712010-07-14 17:59:35 -07002789 audio_track_cblk_t* cblk = track->cblk();
2790
2791 // The first time a track is added we wait
2792 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002793 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002794 // make sure that we have enough frames to mix one full buffer.
2795 // enforce this condition only once to enable draining the buffer in case the client
2796 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002797 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002798 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002799 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002800 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002801 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002802 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07002803 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07002804 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002805 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07002806 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08002807 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07002808 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08002809 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2810 // the minimum track buffer size is normally twice the number of frames necessary
2811 // to fill one buffer and the resampler should not leave more than one buffer worth
2812 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002813 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002814 }
2815 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002816 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002817 !track->isPaused() && !track->isTerminated())
2818 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002819 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002820
2821 mixedTracks++;
2822
2823 // track->mainBuffer() != mMixBuffer means there is an effect chain
2824 // connected to the track
2825 chain.clear();
2826 if (track->mainBuffer() != mMixBuffer) {
2827 chain = getEffectChain_l(track->sessionId());
2828 // Delegate volume control to effect in track effect chain if needed
2829 if (chain != 0) {
2830 tracksWithEffect++;
2831 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002832 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002833 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834 }
2835 }
2836
2837
2838 int param = AudioMixer::VOLUME;
2839 if (track->mFillingUpStatus == Track::FS_FILLED) {
2840 // no ramp for the first volume setting
2841 track->mFillingUpStatus = Track::FS_ACTIVE;
2842 if (track->mState == TrackBase::RESUMING) {
2843 track->mState = TrackBase::ACTIVE;
2844 param = AudioMixer::RAMP_VOLUME;
2845 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002846 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002847 } else if (cblk->server != 0) {
2848 // If the track is stopped before the first frame was mixed,
2849 // do not apply ramp
2850 param = AudioMixer::RAMP_VOLUME;
2851 }
2852
2853 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002854 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002855 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002856 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002857 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002858 if (track->isPausing()) {
2859 track->setPaused();
2860 }
2861 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002862
Mathias Agopian65ab4712010-07-14 17:59:35 -07002863 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002864 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002865 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002866 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002867 vl = vlr & 0xFFFF;
2868 vr = vlr >> 16;
2869 // track volumes come from shared memory, so can't be trusted and must be clamped
2870 if (vl > MAX_GAIN_INT) {
2871 ALOGV("Track left volume out of range: %04X", vl);
2872 vl = MAX_GAIN_INT;
2873 }
2874 if (vr > MAX_GAIN_INT) {
2875 ALOGV("Track right volume out of range: %04X", vr);
2876 vr = MAX_GAIN_INT;
2877 }
2878 // now apply the master volume and stream type volume
2879 vl = (uint32_t)(v * vl) << 12;
2880 vr = (uint32_t)(v * vr) << 12;
2881 // assuming master volume and stream type volume each go up to 1.0,
2882 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002883
Glenn Kasten05632a52012-01-03 14:22:33 -08002884 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2885 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002886 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002887 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002888 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002889 }
2890 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002891 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002892 // Delegate volume control to effect in track effect chain if needed
2893 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2894 // Do not ramp volume if volume is controlled by effect
2895 param = AudioMixer::VOLUME;
2896 track->mHasVolumeController = true;
2897 } else {
2898 // force no volume ramp when volume controller was just disabled or removed
2899 // from effect chain to avoid volume spike
2900 if (track->mHasVolumeController) {
2901 param = AudioMixer::VOLUME;
2902 }
2903 track->mHasVolumeController = false;
2904 }
2905
2906 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002907 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002908 vl = (vl + (1 << 11)) >> 12;
2909 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2910 vr = (vr + (1 << 11)) >> 12;
2911 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002912
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002913 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
Mathias Agopian65ab4712010-07-14 17:59:35 -07002914
Mathias Agopian65ab4712010-07-14 17:59:35 -07002915 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002916 mAudioMixer->setBufferProvider(name, track);
2917 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002918
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002919 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2920 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2921 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002922 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002923 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002924 AudioMixer::TRACK,
2925 AudioMixer::FORMAT, (void *)track->format());
2926 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002927 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002928 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002929 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002930 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002931 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002932 AudioMixer::RESAMPLE,
2933 AudioMixer::SAMPLE_RATE,
2934 (void *)(cblk->sampleRate));
2935 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002936 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002937 AudioMixer::TRACK,
2938 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2939 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002940 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002941 AudioMixer::TRACK,
2942 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2943
2944 // reset retry count
2945 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002946
Eric Laurent27741442012-01-17 19:20:12 -08002947 // If one track is ready, set the mixer ready if:
2948 // - the mixer was not ready during previous round OR
2949 // - no other track is not ready
2950 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2951 mixerStatus != MIXER_TRACKS_ENABLED) {
2952 mixerStatus = MIXER_TRACKS_READY;
2953 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002954 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002955 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002956 if (track->isStopped()) {
2957 track->reset();
2958 }
2959 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2960 // We have consumed all the buffers of this track.
2961 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07002962 // TODO: use actual buffer filling status instead of latency when available from
2963 // audio HAL
2964 size_t audioHALFrames =
2965 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2966 size_t framesWritten =
2967 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2968 if (track->presentationComplete(framesWritten, audioHALFrames)) {
2969 tracksToRemove->add(track);
2970 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002971 } else {
2972 // No buffers for this track. Give it a few chances to
2973 // fill a buffer, then remove it from active list.
2974 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002975 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002976 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002977 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002978 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002979 // If one track is not ready, mark the mixer also not ready if:
2980 // - the mixer was ready during previous round OR
2981 // - no other track is ready
2982 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2983 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002984 mixerStatus = MIXER_TRACKS_ENABLED;
2985 }
2986 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002987 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002988 }
Glenn Kasten58912562012-04-03 10:45:00 -07002989
2990 } // local variable scope to avoid goto warning
2991track_is_ready: ;
2992
Mathias Agopian65ab4712010-07-14 17:59:35 -07002993 }
2994
Glenn Kasten58912562012-04-03 10:45:00 -07002995 // FIXME Here is where we would push the new FastMixer state if necessary
2996
Mathias Agopian65ab4712010-07-14 17:59:35 -07002997 // remove all the tracks that need to be...
2998 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002999 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003000 for (size_t i=0 ; i<count ; i++) {
3001 const sp<Track>& track = tracksToRemove->itemAt(i);
3002 mActiveTracks.remove(track);
3003 if (track->mainBuffer() != mMixBuffer) {
3004 chain = getEffectChain_l(track->sessionId());
3005 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003006 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003007 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003008 }
3009 }
3010 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003011 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003012 }
3013 }
3014 }
3015
3016 // mix buffer must be cleared if all tracks are connected to an
3017 // effect chain as in this case the mixer will not write to
3018 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003019 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3020 // FIXME as a performance optimization, should remember previous zero status
3021 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003022 }
3023
Glenn Kasten58912562012-04-03 10:45:00 -07003024 // if any fast tracks, then status is ready
3025 if (fastTracks > 0) {
3026 mixerStatus = MIXER_TRACKS_READY;
3027 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003028 return mixerStatus;
3029}
3030
Glenn Kasten66fcab92012-02-24 14:59:21 -08003031/*
3032The derived values that are cached:
3033 - mixBufferSize from frame count * frame size
3034 - activeSleepTime from activeSleepTimeUs()
3035 - idleSleepTime from idleSleepTimeUs()
3036 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3037 - maxPeriod from frame count and sample rate (MIXER only)
3038
3039The parameters that affect these derived values are:
3040 - frame count
3041 - frame size
3042 - sample rate
3043 - device type: A2DP or not
3044 - device latency
3045 - format: PCM or not
3046 - active sleep time
3047 - idle sleep time
3048*/
3049
3050void AudioFlinger::PlaybackThread::cacheParameters_l()
3051{
Glenn Kasten58912562012-04-03 10:45:00 -07003052 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003053 activeSleepTime = activeSleepTimeUs();
3054 idleSleepTime = idleSleepTimeUs();
3055}
3056
Glenn Kastenfff6d712012-01-12 16:38:12 -08003057void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003058{
Steve Block3856b092011-10-20 11:56:00 +01003059 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003060 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003061 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003062
Mathias Agopian65ab4712010-07-14 17:59:35 -07003063 size_t size = mTracks.size();
3064 for (size_t i = 0; i < size; i++) {
3065 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003066 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003067 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003068 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003069 }
3070 }
3071}
3072
Mathias Agopian65ab4712010-07-14 17:59:35 -07003073// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003074int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003075{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003076 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003077}
3078
3079// deleteTrackName_l() must be called with ThreadBase::mLock held
3080void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3081{
Steve Block3856b092011-10-20 11:56:00 +01003082 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003083 mAudioMixer->deleteTrackName(name);
3084}
3085
3086// checkForNewParameters_l() must be called with ThreadBase::mLock held
3087bool AudioFlinger::MixerThread::checkForNewParameters_l()
3088{
Glenn Kasten58912562012-04-03 10:45:00 -07003089 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3090 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003091 bool reconfig = false;
3092
3093 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003094
3095 if (mFastMixer != NULL) {
3096 FastMixerStateQueue *sq = mFastMixer->sq();
3097 FastMixerState *state = sq->begin();
3098 if (!(state->mCommand & FastMixerState::IDLE)) {
3099 previousCommand = state->mCommand;
3100 state->mCommand = FastMixerState::HOT_IDLE;
3101 sq->end();
3102 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3103 } else {
3104 sq->end(false /*didModify*/);
3105 }
3106 }
3107
Mathias Agopian65ab4712010-07-14 17:59:35 -07003108 status_t status = NO_ERROR;
3109 String8 keyValuePair = mNewParameters[0];
3110 AudioParameter param = AudioParameter(keyValuePair);
3111 int value;
3112
3113 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3114 reconfig = true;
3115 }
3116 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003117 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003118 status = BAD_VALUE;
3119 } else {
3120 reconfig = true;
3121 }
3122 }
3123 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003124 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003125 status = BAD_VALUE;
3126 } else {
3127 reconfig = true;
3128 }
3129 }
3130 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3131 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003132 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003133 // if frame count is changed after track creation
3134 if (!mTracks.isEmpty()) {
3135 status = INVALID_OPERATION;
3136 } else {
3137 reconfig = true;
3138 }
3139 }
3140 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003141#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003142 // when changing the audio output device, call addBatteryData to notify
3143 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003144 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003145 uint32_t params = 0;
3146 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003147 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003148 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3149 }
3150
3151 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003152 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003153 // check if any other device (except speaker) is on
3154 if (value & deviceWithoutSpeaker ) {
3155 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3156 }
3157
3158 if (params != 0) {
3159 addBatteryData(params);
3160 }
3161 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003162#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003163
Mathias Agopian65ab4712010-07-14 17:59:35 -07003164 // forward device change to effects that have requested to be
3165 // aware of attached audio device.
3166 mDevice = (uint32_t)value;
3167 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003168 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003169 }
3170 }
3171
3172 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003173 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003174 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003175 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003176 mOutput->stream->common.standby(&mOutput->stream->common);
3177 mStandby = true;
3178 mBytesWritten = 0;
3179 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003180 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003181 }
3182 if (status == NO_ERROR && reconfig) {
3183 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003184 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3185 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003186 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003187 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003188 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003189 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003190 if (name < 0) break;
3191 mTracks[i]->mName = name;
3192 // limit track sample rate to 2 x new output sample rate
3193 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3194 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3195 }
3196 }
3197 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3198 }
3199 }
3200
3201 mNewParameters.removeAt(0);
3202
3203 mParamStatus = status;
3204 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003205 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3206 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003207 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003208 }
Glenn Kasten58912562012-04-03 10:45:00 -07003209
3210 if (!(previousCommand & FastMixerState::IDLE)) {
3211 ALOG_ASSERT(mFastMixer != NULL);
3212 FastMixerStateQueue *sq = mFastMixer->sq();
3213 FastMixerState *state = sq->begin();
3214 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3215 state->mCommand = previousCommand;
3216 sq->end();
3217 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3218 }
3219
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220 return reconfig;
3221}
3222
3223status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3224{
3225 const size_t SIZE = 256;
3226 char buffer[SIZE];
3227 String8 result;
3228
3229 PlaybackThread::dumpInternals(fd, args);
3230
3231 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3232 result.append(buffer);
3233 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003234
3235 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3236 FastMixerDumpState copy = mFastMixerDumpState;
3237 copy.dump(fd);
3238
Mathias Agopian65ab4712010-07-14 17:59:35 -07003239 return NO_ERROR;
3240}
3241
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003242uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003243{
Glenn Kasten58912562012-04-03 10:45:00 -07003244 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003245}
3246
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003247uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003248{
Glenn Kasten58912562012-04-03 10:45:00 -07003249 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003250}
3251
Glenn Kasten66fcab92012-02-24 14:59:21 -08003252void AudioFlinger::MixerThread::cacheParameters_l()
3253{
3254 PlaybackThread::cacheParameters_l();
3255
3256 // FIXME: Relaxed timing because of a certain device that can't meet latency
3257 // Should be reduced to 2x after the vendor fixes the driver issue
3258 // increase threshold again due to low power audio mode. The way this warning
3259 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003260 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003261}
3262
Mathias Agopian65ab4712010-07-14 17:59:35 -07003263// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003264AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3265 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003266 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003267 // mLeftVolFloat, mRightVolFloat
3268 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07003269{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003270}
3271
3272AudioFlinger::DirectOutputThread::~DirectOutputThread()
3273{
3274}
3275
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003276AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3277 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003278)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003279{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003280 sp<Track> trackToRemove;
3281
Glenn Kastenfec279f2012-03-08 07:47:15 -08003282 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003283
Glenn Kasten952eeb22012-03-06 11:30:57 -08003284 // find out which tracks need to be processed
3285 if (mActiveTracks.size() != 0) {
3286 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003287 // The track died recently
3288 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003289
Glenn Kasten952eeb22012-03-06 11:30:57 -08003290 Track* const track = t.get();
3291 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003292
Glenn Kasten952eeb22012-03-06 11:30:57 -08003293 // The first time a track is added we wait
3294 // for all its buffers to be filled before processing it
3295 if (cblk->framesReady() && track->isReady() &&
3296 !track->isPaused() && !track->isTerminated())
3297 {
3298 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003299
Glenn Kasten952eeb22012-03-06 11:30:57 -08003300 if (track->mFillingUpStatus == Track::FS_FILLED) {
3301 track->mFillingUpStatus = Track::FS_ACTIVE;
3302 mLeftVolFloat = mRightVolFloat = 0;
3303 mLeftVolShort = mRightVolShort = 0;
3304 if (track->mState == TrackBase::RESUMING) {
3305 track->mState = TrackBase::ACTIVE;
3306 rampVolume = true;
3307 }
3308 } else if (cblk->server != 0) {
3309 // If the track is stopped before the first frame was mixed,
3310 // do not apply ramp
3311 rampVolume = true;
3312 }
3313 // compute volume for this track
3314 float left, right;
3315 if (track->isMuted() || mMasterMute || track->isPausing() ||
3316 mStreamTypes[track->streamType()].mute) {
3317 left = right = 0;
3318 if (track->isPausing()) {
3319 track->setPaused();
3320 }
3321 } else {
3322 float typeVolume = mStreamTypes[track->streamType()].volume;
3323 float v = mMasterVolume * typeVolume;
3324 uint32_t vlr = cblk->getVolumeLR();
3325 float v_clamped = v * (vlr & 0xFFFF);
3326 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3327 left = v_clamped/MAX_GAIN;
3328 v_clamped = v * (vlr >> 16);
3329 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3330 right = v_clamped/MAX_GAIN;
3331 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003332
Glenn Kasten952eeb22012-03-06 11:30:57 -08003333 if (left != mLeftVolFloat || right != mRightVolFloat) {
3334 mLeftVolFloat = left;
3335 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003336
Glenn Kasten952eeb22012-03-06 11:30:57 -08003337 // If audio HAL implements volume control,
3338 // force software volume to nominal value
3339 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
3340 left = 1.0f;
3341 right = 1.0f;
3342 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003343
Glenn Kasten952eeb22012-03-06 11:30:57 -08003344 // Convert volumes from float to 8.24
3345 uint32_t vl = (uint32_t)(left * (1 << 24));
3346 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003347
Glenn Kasten952eeb22012-03-06 11:30:57 -08003348 // Delegate volume control to effect in track effect chain if needed
3349 // only one effect chain can be present on DirectOutputThread, so if
3350 // there is one, the track is connected to it
3351 if (!mEffectChains.isEmpty()) {
3352 // Do not ramp volume if volume is controlled by effect
3353 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003354 rampVolume = false;
3355 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003356 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003357
Glenn Kasten952eeb22012-03-06 11:30:57 -08003358 // Convert volumes from 8.24 to 4.12 format
3359 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
3360 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3361 leftVol = (uint16_t)v_clamped;
3362 v_clamped = (vr + (1 << 11)) >> 12;
3363 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3364 rightVol = (uint16_t)v_clamped;
3365 } else {
3366 leftVol = mLeftVolShort;
3367 rightVol = mRightVolShort;
3368 rampVolume = false;
3369 }
3370
3371 // reset retry count
3372 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003373 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003374 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003375 } else {
3376 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
3377 if (track->isStopped()) {
3378 track->reset();
3379 }
3380 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
3381 // We have consumed all the buffers of this track.
3382 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003383 // TODO: implement behavior for compressed audio
3384 size_t audioHALFrames =
3385 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3386 size_t framesWritten =
3387 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3388 if (track->presentationComplete(framesWritten, audioHALFrames)) {
3389 trackToRemove = track;
3390 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003391 } else {
3392 // No buffers for this track. Give it a few chances to
3393 // fill a buffer, then remove it from active list.
3394 if (--(track->mRetryCount) <= 0) {
3395 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3396 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003397 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003398 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003399 }
3400 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003401 }
3402 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003403
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003404 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003405 // remove all the tracks that need to be...
3406 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003407 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003408 mActiveTracks.remove(trackToRemove);
3409 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003410 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003411 trackToRemove->sessionId());
3412 mEffectChains[0]->decActiveTrackCnt();
3413 }
3414 if (trackToRemove->isTerminated()) {
3415 removeTrack_l(trackToRemove);
3416 }
3417 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003418
Glenn Kastenfec279f2012-03-08 07:47:15 -08003419 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003420}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003421
Glenn Kasten000f0e32012-03-01 17:10:56 -08003422void AudioFlinger::DirectOutputThread::threadLoop_mix()
3423{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003424 AudioBufferProvider::Buffer buffer;
3425 size_t frameCount = mFrameCount;
3426 int8_t *curBuf = (int8_t *)mMixBuffer;
3427 // output audio to hardware
3428 while (frameCount) {
3429 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003430 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003431 if (CC_UNLIKELY(buffer.raw == NULL)) {
3432 memset(curBuf, 0, frameCount * mFrameSize);
3433 break;
3434 }
3435 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3436 frameCount -= buffer.frameCount;
3437 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003438 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003439 }
3440 sleepTime = 0;
3441 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003442 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003443
3444 // apply volume
3445
3446 // Do not apply volume on compressed audio
3447 if (!audio_is_linear_pcm(mFormat)) {
3448 return;
3449 }
3450
3451 // convert to signed 16 bit before volume calculation
3452 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3453 size_t count = mFrameCount * mChannelCount;
3454 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
3455 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003456 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003457 *dst-- = (int16_t)(*src--^0x80) << 8;
3458 }
3459 }
3460
3461 frameCount = mFrameCount;
3462 int16_t *out = mMixBuffer;
3463 if (rampVolume) {
3464 if (mChannelCount == 1) {
3465 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3466 int32_t vlInc = d / (int32_t)frameCount;
3467 int32_t vl = ((int32_t)mLeftVolShort << 16);
3468 do {
3469 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3470 out++;
3471 vl += vlInc;
3472 } while (--frameCount);
3473
3474 } else {
3475 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3476 int32_t vlInc = d / (int32_t)frameCount;
3477 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
3478 int32_t vrInc = d / (int32_t)frameCount;
3479 int32_t vl = ((int32_t)mLeftVolShort << 16);
3480 int32_t vr = ((int32_t)mRightVolShort << 16);
3481 do {
3482 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3483 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3484 out += 2;
3485 vl += vlInc;
3486 vr += vrInc;
3487 } while (--frameCount);
3488 }
3489 } else {
3490 if (mChannelCount == 1) {
3491 do {
3492 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3493 out++;
3494 } while (--frameCount);
3495 } else {
3496 do {
3497 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3498 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3499 out += 2;
3500 } while (--frameCount);
3501 }
3502 }
3503
3504 // convert back to unsigned 8 bit after volume calculation
3505 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3506 size_t count = mFrameCount * mChannelCount;
3507 int16_t *src = mMixBuffer;
3508 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003509 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003510 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3511 }
3512 }
3513
3514 mLeftVolShort = leftVol;
3515 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003516}
3517
3518void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3519{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003520 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003521 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003522 sleepTime = activeSleepTime;
3523 } else {
3524 sleepTime = idleSleepTime;
3525 }
3526 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003527 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003528 sleepTime = 0;
3529 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003530}
3531
3532// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003533int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003534{
3535 return 0;
3536}
3537
3538// deleteTrackName_l() must be called with ThreadBase::mLock held
3539void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3540{
3541}
3542
3543// checkForNewParameters_l() must be called with ThreadBase::mLock held
3544bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3545{
3546 bool reconfig = false;
3547
3548 while (!mNewParameters.isEmpty()) {
3549 status_t status = NO_ERROR;
3550 String8 keyValuePair = mNewParameters[0];
3551 AudioParameter param = AudioParameter(keyValuePair);
3552 int value;
3553
3554 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3555 // do not accept frame count changes if tracks are open as the track buffer
3556 // size depends on frame count and correct behavior would not be garantied
3557 // if frame count is changed after track creation
3558 if (!mTracks.isEmpty()) {
3559 status = INVALID_OPERATION;
3560 } else {
3561 reconfig = true;
3562 }
3563 }
3564 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003565 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003566 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003567 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003568 mOutput->stream->common.standby(&mOutput->stream->common);
3569 mStandby = true;
3570 mBytesWritten = 0;
3571 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003572 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003573 }
3574 if (status == NO_ERROR && reconfig) {
3575 readOutputParameters();
3576 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3577 }
3578 }
3579
3580 mNewParameters.removeAt(0);
3581
3582 mParamStatus = status;
3583 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003584 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3585 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003586 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003587 }
3588 return reconfig;
3589}
3590
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003591uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003592{
3593 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003594 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003595 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003596 } else {
3597 time = 10000;
3598 }
3599 return time;
3600}
3601
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003602uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003603{
3604 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003605 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003606 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003607 } else {
3608 time = 10000;
3609 }
3610 return time;
3611}
3612
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003613uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003614{
3615 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003616 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003617 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3618 } else {
3619 time = 10000;
3620 }
3621 return time;
3622}
3623
Glenn Kasten66fcab92012-02-24 14:59:21 -08003624void AudioFlinger::DirectOutputThread::cacheParameters_l()
3625{
3626 PlaybackThread::cacheParameters_l();
3627
3628 // use shorter standby delay as on normal output to release
3629 // hardware resources as soon as possible
3630 standbyDelay = microseconds(activeSleepTime*2);
3631}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003632
Mathias Agopian65ab4712010-07-14 17:59:35 -07003633// ----------------------------------------------------------------------------
3634
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003635AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003636 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003637 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3638 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003639{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003640 addOutputTrack(mainThread);
3641}
3642
3643AudioFlinger::DuplicatingThread::~DuplicatingThread()
3644{
3645 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3646 mOutputTracks[i]->destroy();
3647 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003648}
3649
Glenn Kasten000f0e32012-03-01 17:10:56 -08003650void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003651{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003652 // mix buffers...
3653 if (outputsReady(outputTracks)) {
3654 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3655 } else {
3656 memset(mMixBuffer, 0, mixBufferSize);
3657 }
3658 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003659 writeFrames = mNormalFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003660}
3661
3662void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3663{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003664 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003665 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003666 sleepTime = activeSleepTime;
3667 } else {
3668 sleepTime = idleSleepTime;
3669 }
3670 } else if (mBytesWritten != 0) {
3671 // flush remaining overflow buffers in output tracks
3672 for (size_t i = 0; i < outputTracks.size(); i++) {
3673 if (outputTracks[i]->isActive()) {
3674 sleepTime = 0;
3675 writeFrames = 0;
3676 memset(mMixBuffer, 0, mixBufferSize);
3677 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003678 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003679 }
3680 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003681}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003682
Glenn Kasten000f0e32012-03-01 17:10:56 -08003683void AudioFlinger::DuplicatingThread::threadLoop_write()
3684{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003685 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003686 for (size_t i = 0; i < outputTracks.size(); i++) {
3687 outputTracks[i]->write(mMixBuffer, writeFrames);
3688 }
3689 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003690}
Glenn Kasten688a6402012-02-29 07:57:06 -08003691
Glenn Kasten000f0e32012-03-01 17:10:56 -08003692void AudioFlinger::DuplicatingThread::threadLoop_standby()
3693{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003694 // DuplicatingThread implements standby by stopping all tracks
3695 for (size_t i = 0; i < outputTracks.size(); i++) {
3696 outputTracks[i]->stop();
3697 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003698}
3699
Glenn Kastenfa26a852012-03-06 11:28:04 -08003700void AudioFlinger::DuplicatingThread::saveOutputTracks()
3701{
3702 outputTracks = mOutputTracks;
3703}
3704
3705void AudioFlinger::DuplicatingThread::clearOutputTracks()
3706{
3707 outputTracks.clear();
3708}
3709
Mathias Agopian65ab4712010-07-14 17:59:35 -07003710void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3711{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003712 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003713 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07003714 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003715 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003716 this,
3717 mSampleRate,
3718 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003719 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003720 frameCount);
3721 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003722 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003723 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003724 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003725 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003726 }
3727}
3728
3729void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3730{
3731 Mutex::Autolock _l(mLock);
3732 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003733 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003734 mOutputTracks[i]->destroy();
3735 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003736 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003737 return;
3738 }
3739 }
Steve Block3856b092011-10-20 11:56:00 +01003740 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003741}
3742
Glenn Kasten438b0362012-03-06 11:24:48 -08003743// caller must hold mLock
3744void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003745{
3746 mWaitTimeMs = UINT_MAX;
3747 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3748 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003749 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003750 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3751 if (waitTimeMs < mWaitTimeMs) {
3752 mWaitTimeMs = waitTimeMs;
3753 }
3754 }
3755 }
3756}
3757
3758
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003759bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003760{
3761 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003762 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003763 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003764 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003765 return false;
3766 }
3767 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3768 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003769 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003770 return false;
3771 }
3772 }
3773 return true;
3774}
3775
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003776uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003777{
3778 return (mWaitTimeMs * 1000) / 2;
3779}
3780
Glenn Kasten66fcab92012-02-24 14:59:21 -08003781void AudioFlinger::DuplicatingThread::cacheParameters_l()
3782{
3783 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3784 updateWaitTime_l();
3785
3786 MixerThread::cacheParameters_l();
3787}
3788
Mathias Agopian65ab4712010-07-14 17:59:35 -07003789// ----------------------------------------------------------------------------
3790
3791// TrackBase constructor must be called with AudioFlinger::mLock held
3792AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003793 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003794 const sp<Client>& client,
3795 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003796 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003797 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003798 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003799 const sp<IMemory>& sharedBuffer,
3800 int sessionId)
3801 : RefBase(),
3802 mThread(thread),
3803 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003804 mCblk(NULL),
3805 // mBuffer
3806 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003807 mFrameCount(0),
3808 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07003809 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003810 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003811 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003812 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003813 // mChannelCount
3814 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003815{
Steve Block3856b092011-10-20 11:56:00 +01003816 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003817
Steve Blockb8a80522011-12-20 16:23:08 +00003818 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003819 size_t size = sizeof(audio_track_cblk_t);
3820 uint8_t channelCount = popcount(channelMask);
3821 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3822 if (sharedBuffer == 0) {
3823 size += bufferSize;
3824 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003825
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003826 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003827 mCblkMemory = client->heap()->allocate(size);
3828 if (mCblkMemory != 0) {
3829 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003830 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003831 new(mCblk) audio_track_cblk_t();
3832 // clear all buffers
3833 mCblk->frameCount = frameCount;
3834 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003835// uncomment the following lines to quickly test 32-bit wraparound
3836// mCblk->user = 0xffff0000;
3837// mCblk->server = 0xffff0000;
3838// mCblk->userBase = 0xffff0000;
3839// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003840 mChannelCount = channelCount;
3841 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003842 if (sharedBuffer == 0) {
3843 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3844 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3845 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003846 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003847 mCblk->flags = CBLK_UNDERRUN_ON;
3848 } else {
3849 mBuffer = sharedBuffer->pointer();
3850 }
3851 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3852 }
3853 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003854 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003855 client->heap()->dump("AudioTrack");
3856 return;
3857 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003858 } else {
3859 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07003860 // construct the shared structure in-place.
3861 new(mCblk) audio_track_cblk_t();
3862 // clear all buffers
3863 mCblk->frameCount = frameCount;
3864 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003865// uncomment the following lines to quickly test 32-bit wraparound
3866// mCblk->user = 0xffff0000;
3867// mCblk->server = 0xffff0000;
3868// mCblk->userBase = 0xffff0000;
3869// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003870 mChannelCount = channelCount;
3871 mChannelMask = channelMask;
3872 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3873 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3874 // Force underrun condition to avoid false underrun callback until first data is
3875 // written to buffer (other flags are cleared)
3876 mCblk->flags = CBLK_UNDERRUN_ON;
3877 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003878 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003879}
3880
3881AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3882{
Glenn Kastena0d68332012-01-27 16:47:15 -08003883 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003884 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003885 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003886 } else {
3887 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003888 }
3889 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003890 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003891 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003892 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003893 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003894 // If the client's reference count drops to zero, the associated destructor
3895 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3896 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003897 mClient.clear();
3898 }
3899}
3900
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003901// AudioBufferProvider interface
3902// getNextBuffer() = 0;
3903// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07003904void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3905{
Glenn Kastene0feee32011-12-13 11:53:26 -08003906 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003907 mFrameCount = buffer->frameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003908 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003909 buffer->frameCount = 0;
3910}
3911
3912bool AudioFlinger::ThreadBase::TrackBase::step() {
3913 bool result;
3914 audio_track_cblk_t* cblk = this->cblk();
3915
3916 result = cblk->stepServer(mFrameCount);
3917 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003918 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003919 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003920 }
3921 return result;
3922}
3923
3924void AudioFlinger::ThreadBase::TrackBase::reset() {
3925 audio_track_cblk_t* cblk = this->cblk();
3926
3927 cblk->user = 0;
3928 cblk->server = 0;
3929 cblk->userBase = 0;
3930 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003931 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01003932 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003933}
3934
Mathias Agopian65ab4712010-07-14 17:59:35 -07003935int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3936 return (int)mCblk->sampleRate;
3937}
3938
Mathias Agopian65ab4712010-07-14 17:59:35 -07003939void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3940 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003941 size_t frameSize = cblk->frameSize;
3942 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3943 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003944
3945 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07003946 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
3947 "TrackBase::getBuffer buffer out of range:\n"
3948 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
3949 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003950 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07003951 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003952
3953 return bufferStart;
3954}
3955
Eric Laurenta011e352012-03-29 15:51:43 -07003956status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
3957{
3958 mSyncEvents.add(event);
3959 return NO_ERROR;
3960}
3961
Mathias Agopian65ab4712010-07-14 17:59:35 -07003962// ----------------------------------------------------------------------------
3963
3964// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3965AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003966 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003967 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003968 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003969 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003970 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003971 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003972 int frameCount,
3973 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07003974 int sessionId,
3975 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003976 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07003977 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07003978 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07003979 // mRetryCount initialized later when needed
3980 mSharedBuffer(sharedBuffer),
3981 mStreamType(streamType),
3982 mName(-1), // see note below
3983 mMainBuffer(thread->mixBuffer()),
3984 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07003985 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07003986 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07003987 mFlags(flags),
3988 mFastIndex(-1),
3989 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003990{
3991 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003992 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3993 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003994 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten58912562012-04-03 10:45:00 -07003995 if (flags & IAudioFlinger::TRACK_FAST) {
3996 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
3997 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
3998 int i = __builtin_ctz(thread->mFastTrackAvailMask);
3999 ALOG_ASSERT(0 < i && i < FastMixerState::kMaxFastTracks);
4000 mFastIndex = i;
4001 thread->mFastTrackAvailMask &= ~(1 << i);
4002 // Although we've allocated an index, we can't mutate or push a new fast track state
4003 // here, because that data structure can only be changed within the normal mixer
4004 // threadLoop(). So instead, make a note to mutate and push later.
4005 thread->mFastTrackNewArray[i] = this;
4006 thread->mFastTrackNewMask |= 1 << i;
4007 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004008 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07004009 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
Glenn Kastenf9959012012-03-19 11:14:37 -07004010 if (mName < 0) {
4011 ALOGE("no more track names available");
4012 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004013 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004014 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004015}
4016
4017AudioFlinger::PlaybackThread::Track::~Track()
4018{
Steve Block3856b092011-10-20 11:56:00 +01004019 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004020 sp<ThreadBase> thread = mThread.promote();
4021 if (thread != 0) {
4022 Mutex::Autolock _l(thread->mLock);
4023 mState = TERMINATED;
4024 }
4025}
4026
4027void AudioFlinger::PlaybackThread::Track::destroy()
4028{
4029 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4030 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004031 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004032 // we must acquire a strong reference on this Track before locking mLock
4033 // here so that the destructor is called only when exiting this function.
4034 // On the other hand, as long as Track::destroy() is only called by
4035 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4036 // this Track with its member mTrack.
4037 sp<Track> keep(this);
4038 { // scope for mLock
4039 sp<ThreadBase> thread = mThread.promote();
4040 if (thread != 0) {
4041 if (!isOutputTrack()) {
4042 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004043 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004044
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004045#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004046 // to track the speaker usage
4047 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004048#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004049 }
4050 AudioSystem::releaseOutput(thread->id());
4051 }
4052 Mutex::Autolock _l(thread->mLock);
4053 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4054 playbackThread->destroyTrack_l(this);
4055 }
4056 }
4057}
4058
4059void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4060{
Glenn Kasten83d86532012-01-17 14:39:34 -08004061 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004062 if (isFastTrack()) {
4063 strcpy(buffer, " fast");
4064 } else {
4065 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4066 }
4067 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %1d %1d %1d %5u %5.2g %5.2g 0x%08x 0x%08x 0x%08x 0x%08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004068 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004069 mStreamType,
4070 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004071 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004072 mSessionId,
4073 mFrameCount,
4074 mState,
4075 mMute,
4076 mFillingUpStatus,
4077 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004078 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4079 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004080 mCblk->server,
4081 mCblk->user,
4082 (int)mMainBuffer,
4083 (int)mAuxBuffer);
4084}
4085
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004086// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004087status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004088 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004089{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004090 audio_track_cblk_t* cblk = this->cblk();
4091 uint32_t framesReady;
4092 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004093
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004094 // Check if last stepServer failed, try to step now
4095 if (mStepServerFailed) {
4096 if (!step()) goto getNextBuffer_exit;
4097 ALOGV("stepServer recovered");
4098 mStepServerFailed = false;
4099 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004100
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004101 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004102
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004103 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004104 uint32_t s = cblk->server;
4105 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4106
4107 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4108 if (framesReq > framesReady) {
4109 framesReq = framesReady;
4110 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004111 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004112 framesReq = bufferEnd - s;
4113 }
4114
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004115 buffer->raw = getBuffer(s, framesReq);
4116 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004117
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004118 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004119 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004120 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004121
4122getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004123 buffer->raw = NULL;
4124 buffer->frameCount = 0;
4125 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4126 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004127}
4128
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004129uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004130 return mCblk->framesReady();
4131}
4132
Mathias Agopian65ab4712010-07-14 17:59:35 -07004133bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004134 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004135
John Grossman4ff14ba2012-02-08 16:37:41 -08004136 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004137 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4138 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004139 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004140 return true;
4141 }
4142 return false;
4143}
4144
Glenn Kasten3acbd052012-02-28 10:39:56 -08004145status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004146 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004147{
4148 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004149 ALOGV("start(%d), calling pid %d session %d",
4150 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004151
Mathias Agopian65ab4712010-07-14 17:59:35 -07004152 sp<ThreadBase> thread = mThread.promote();
4153 if (thread != 0) {
4154 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004155 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004156 // here the track could be either new, or restarted
4157 // in both cases "unstop" the track
4158 if (mState == PAUSED) {
4159 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004160 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004161 } else {
4162 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004163 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004164 }
4165
4166 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4167 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004168 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004169 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004170
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004171#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004172 // to track the speaker usage
4173 if (status == NO_ERROR) {
4174 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4175 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004176#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004177 }
4178 if (status == NO_ERROR) {
4179 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4180 playbackThread->addTrack_l(this);
4181 } else {
4182 mState = state;
4183 }
4184 } else {
4185 status = BAD_VALUE;
4186 }
4187 return status;
4188}
4189
4190void AudioFlinger::PlaybackThread::Track::stop()
4191{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004192 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004193 sp<ThreadBase> thread = mThread.promote();
4194 if (thread != 0) {
4195 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004196 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004197 if (mState > STOPPED) {
4198 mState = STOPPED;
4199 // If the track is not active (PAUSED and buffers full), flush buffers
4200 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4201 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4202 reset();
4203 }
Steve Block3856b092011-10-20 11:56:00 +01004204 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004205 }
4206 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4207 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004208 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004209 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004210
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004211#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004212 // to track the speaker usage
4213 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004214#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004215 }
4216 }
4217}
4218
4219void AudioFlinger::PlaybackThread::Track::pause()
4220{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004221 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004222 sp<ThreadBase> thread = mThread.promote();
4223 if (thread != 0) {
4224 Mutex::Autolock _l(thread->mLock);
4225 if (mState == ACTIVE || mState == RESUMING) {
4226 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004227 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004228 if (!isOutputTrack()) {
4229 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004230 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004231 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004232
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004233#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004234 // to track the speaker usage
4235 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004236#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004237 }
4238 }
4239 }
4240}
4241
4242void AudioFlinger::PlaybackThread::Track::flush()
4243{
Steve Block3856b092011-10-20 11:56:00 +01004244 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004245 sp<ThreadBase> thread = mThread.promote();
4246 if (thread != 0) {
4247 Mutex::Autolock _l(thread->mLock);
4248 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
4249 return;
4250 }
4251 // No point remaining in PAUSED state after a flush => go to
4252 // STOPPED state
4253 mState = STOPPED;
4254
Eric Laurent38ccae22011-03-28 18:37:07 -07004255 // do not reset the track if it is still in the process of being stopped or paused.
4256 // this will be done by prepareTracks_l() when the track is stopped.
4257 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4258 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4259 reset();
4260 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004261 }
4262}
4263
4264void AudioFlinger::PlaybackThread::Track::reset()
4265{
4266 // Do not reset twice to avoid discarding data written just after a flush and before
4267 // the audioflinger thread detects the track is stopped.
4268 if (!mResetDone) {
4269 TrackBase::reset();
4270 // Force underrun condition to avoid false underrun callback until first data is
4271 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004272 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4273 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004274 mFillingUpStatus = FS_FILLING;
4275 mResetDone = true;
Eric Laurenta011e352012-03-29 15:51:43 -07004276 mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004277 }
4278}
4279
4280void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4281{
4282 mMute = muted;
4283}
4284
Mathias Agopian65ab4712010-07-14 17:59:35 -07004285status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4286{
4287 status_t status = DEAD_OBJECT;
4288 sp<ThreadBase> thread = mThread.promote();
4289 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004290 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4291 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004292 }
4293 return status;
4294}
4295
4296void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4297{
4298 mAuxEffectId = EffectId;
4299 mAuxBuffer = buffer;
4300}
4301
Eric Laurenta011e352012-03-29 15:51:43 -07004302bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4303 size_t audioHalFrames)
4304{
4305 // a track is considered presented when the total number of frames written to audio HAL
4306 // corresponds to the number of frames written when presentationComplete() is called for the
4307 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4308 if (mPresentationCompleteFrames == 0) {
4309 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4310 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4311 mPresentationCompleteFrames, audioHalFrames);
4312 }
4313 if (framesWritten >= mPresentationCompleteFrames) {
4314 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4315 mSessionId, framesWritten);
4316 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
4317 mPresentationCompleteFrames = 0;
4318 return true;
4319 }
4320 return false;
4321}
4322
4323void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4324{
4325 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4326 if (mSyncEvents[i]->type() == type) {
4327 mSyncEvents[i]->trigger();
4328 mSyncEvents.removeAt(i);
4329 i--;
4330 }
4331 }
4332}
4333
Glenn Kasten58912562012-04-03 10:45:00 -07004334// implement VolumeBufferProvider interface
4335
4336uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4337{
4338 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4339 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4340 uint32_t vlr = mCblk->getVolumeLR();
4341 uint32_t vl = vlr & 0xFFFF;
4342 uint32_t vr = vlr >> 16;
4343 // track volumes come from shared memory, so can't be trusted and must be clamped
4344 if (vl > MAX_GAIN_INT) {
4345 vl = MAX_GAIN_INT;
4346 }
4347 if (vr > MAX_GAIN_INT) {
4348 vr = MAX_GAIN_INT;
4349 }
4350 // now apply the cached master volume and stream type volume;
4351 // this is trusted but lacks any synchronization or barrier so may be stale
4352 float v = mCachedVolume;
4353 vl *= v;
4354 vr *= v;
4355 // re-combine into U4.16
4356 vlr = (vr << 16) | (vl & 0xFFFF);
4357 // FIXME look at mute, pause, and stop flags
4358 return vlr;
4359}
Eric Laurenta011e352012-03-29 15:51:43 -07004360
John Grossman4ff14ba2012-02-08 16:37:41 -08004361// timed audio tracks
4362
4363sp<AudioFlinger::PlaybackThread::TimedTrack>
4364AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004365 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004366 const sp<Client>& client,
4367 audio_stream_type_t streamType,
4368 uint32_t sampleRate,
4369 audio_format_t format,
4370 uint32_t channelMask,
4371 int frameCount,
4372 const sp<IMemory>& sharedBuffer,
4373 int sessionId) {
4374 if (!client->reserveTimedTrack())
4375 return NULL;
4376
Glenn Kastena0356762012-03-19 10:38:51 -07004377 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004378 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4379 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004380}
4381
4382AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004383 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004384 const sp<Client>& client,
4385 audio_stream_type_t streamType,
4386 uint32_t sampleRate,
4387 audio_format_t format,
4388 uint32_t channelMask,
4389 int frameCount,
4390 const sp<IMemory>& sharedBuffer,
4391 int sessionId)
4392 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004393 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004394 mQueueHeadInFlight(false),
4395 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004396 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004397 mTimedSilenceBuffer(NULL),
4398 mTimedSilenceBufferSize(0),
4399 mTimedAudioOutputOnTime(false),
4400 mMediaTimeTransformValid(false)
4401{
4402 LocalClock lc;
4403 mLocalTimeFreq = lc.getLocalFreq();
4404
4405 mLocalTimeToSampleTransform.a_zero = 0;
4406 mLocalTimeToSampleTransform.b_zero = 0;
4407 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4408 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4409 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4410 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004411
4412 mMediaTimeToSampleTransform.a_zero = 0;
4413 mMediaTimeToSampleTransform.b_zero = 0;
4414 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4415 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4416 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4417 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004418}
4419
4420AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4421 mClient->releaseTimedTrack();
4422 delete [] mTimedSilenceBuffer;
4423}
4424
4425status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4426 size_t size, sp<IMemory>* buffer) {
4427
4428 Mutex::Autolock _l(mTimedBufferQueueLock);
4429
4430 trimTimedBufferQueue_l();
4431
4432 // lazily initialize the shared memory heap for timed buffers
4433 if (mTimedMemoryDealer == NULL) {
4434 const int kTimedBufferHeapSize = 512 << 10;
4435
4436 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4437 "AudioFlingerTimed");
4438 if (mTimedMemoryDealer == NULL)
4439 return NO_MEMORY;
4440 }
4441
4442 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4443 if (newBuffer == NULL) {
4444 newBuffer = mTimedMemoryDealer->allocate(size);
4445 if (newBuffer == NULL)
4446 return NO_MEMORY;
4447 }
4448
4449 *buffer = newBuffer;
4450 return NO_ERROR;
4451}
4452
4453// caller must hold mTimedBufferQueueLock
4454void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4455 int64_t mediaTimeNow;
4456 {
4457 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4458 if (!mMediaTimeTransformValid)
4459 return;
4460
4461 int64_t targetTimeNow;
4462 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4463 ? mCCHelper.getCommonTime(&targetTimeNow)
4464 : mCCHelper.getLocalTime(&targetTimeNow);
4465
4466 if (OK != res)
4467 return;
4468
4469 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4470 &mediaTimeNow)) {
4471 return;
4472 }
4473 }
4474
John Grossman1c345192012-03-27 14:00:17 -07004475 size_t trimEnd;
4476 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004477 int64_t bufEnd;
4478
John Grossmanc95cfbb2012-04-12 11:53:11 -07004479 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4480 // We have a next buffer. Just use its PTS as the PTS of the frame
4481 // following the last frame in this buffer. If the stream is sparse
4482 // (ie, there are deliberate gaps left in the stream which should be
4483 // filled with silence by the TimedAudioTrack), then this can result
4484 // in one extra buffer being left un-trimmed when it could have
4485 // been. In general, this is not typical, and we would rather
4486 // optimized away the TS calculation below for the more common case
4487 // where PTSes are contiguous.
4488 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4489 } else {
4490 // We have no next buffer. Compute the PTS of the frame following
4491 // the last frame in this buffer by computing the duration of of
4492 // this frame in media time units and adding it to the PTS of the
4493 // buffer.
4494 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4495 / mCblk->frameSize;
4496
4497 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4498 &bufEnd)) {
4499 ALOGE("Failed to convert frame count of %lld to media time"
4500 " duration" " (scale factor %d/%u) in %s",
4501 frameCount,
4502 mMediaTimeToSampleTransform.a_to_b_numer,
4503 mMediaTimeToSampleTransform.a_to_b_denom,
4504 __PRETTY_FUNCTION__);
4505 break;
4506 }
4507 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004508 }
John Grossman9fbdee12012-03-26 17:51:46 -07004509
4510 if (bufEnd > mediaTimeNow)
4511 break;
4512
4513 // Is the buffer we want to use in the middle of a mix operation right
4514 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4515 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004516 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004517 mTrimQueueHeadOnRelease = true;
4518 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004519 }
4520
John Grossman9fbdee12012-03-26 17:51:46 -07004521 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004522 if (trimStart < trimEnd) {
4523 // Update the bookkeeping for framesReady()
4524 for (size_t i = trimStart; i < trimEnd; ++i) {
4525 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4526 }
4527
4528 // Now actually remove the buffers from the queue.
4529 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004530 }
4531}
4532
John Grossman1c345192012-03-27 14:00:17 -07004533void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4534 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004535 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4536 "%s called (reason \"%s\"), but timed buffer queue has no"
4537 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004538
4539 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4540 mTimedBufferQueue.removeAt(0);
4541}
4542
4543void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4544 const TimedBuffer& buf,
4545 const char* logTag) {
4546 uint32_t bufBytes = buf.buffer()->size();
4547 uint32_t consumedAlready = buf.position();
4548
Eric Laurentb388e532012-04-14 13:32:48 -07004549 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004550 "Bad bookkeeping while updating frames pending. Timed buffer is"
4551 " only %u bytes long, but claims to have consumed %u"
4552 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004553 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004554
4555 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004556 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4557 "Bad bookkeeping while updating frames pending. Should have at"
4558 " least %u queued frames, but we think we have only %u. (update"
4559 " reason: \"%s\")",
4560 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004561
4562 mFramesPendingInQueue -= bufFrames;
4563}
4564
John Grossman4ff14ba2012-02-08 16:37:41 -08004565status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4566 const sp<IMemory>& buffer, int64_t pts) {
4567
4568 {
4569 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4570 if (!mMediaTimeTransformValid)
4571 return INVALID_OPERATION;
4572 }
4573
4574 Mutex::Autolock _l(mTimedBufferQueueLock);
4575
John Grossman1c345192012-03-27 14:00:17 -07004576 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4577 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004578 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4579
4580 return NO_ERROR;
4581}
4582
4583status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4584 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4585
John Grossman1c345192012-03-27 14:00:17 -07004586 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4587 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4588 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08004589
4590 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4591 target == TimedAudioTrack::COMMON_TIME)) {
4592 return BAD_VALUE;
4593 }
4594
4595 Mutex::Autolock lock(mMediaTimeTransformLock);
4596 mMediaTimeTransform = xform;
4597 mMediaTimeTransformTarget = target;
4598 mMediaTimeTransformValid = true;
4599
4600 return NO_ERROR;
4601}
4602
4603#define min(a, b) ((a) < (b) ? (a) : (b))
4604
4605// implementation of getNextBuffer for tracks whose buffers have timestamps
4606status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4607 AudioBufferProvider::Buffer* buffer, int64_t pts)
4608{
4609 if (pts == AudioBufferProvider::kInvalidPTS) {
4610 buffer->raw = 0;
4611 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07004612 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004613 return INVALID_OPERATION;
4614 }
4615
John Grossman4ff14ba2012-02-08 16:37:41 -08004616 Mutex::Autolock _l(mTimedBufferQueueLock);
4617
John Grossman9fbdee12012-03-26 17:51:46 -07004618 ALOG_ASSERT(!mQueueHeadInFlight,
4619 "getNextBuffer called without releaseBuffer!");
4620
John Grossman4ff14ba2012-02-08 16:37:41 -08004621 while (true) {
4622
4623 // if we have no timed buffers, then fail
4624 if (mTimedBufferQueue.isEmpty()) {
4625 buffer->raw = 0;
4626 buffer->frameCount = 0;
4627 return NOT_ENOUGH_DATA;
4628 }
4629
4630 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4631
4632 // calculate the PTS of the head of the timed buffer queue expressed in
4633 // local time
4634 int64_t headLocalPTS;
4635 {
4636 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4637
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004638 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08004639
4640 if (mMediaTimeTransform.a_to_b_denom == 0) {
4641 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07004642 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004643 return NO_ERROR;
4644 }
4645
4646 int64_t transformedPTS;
4647 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4648 &transformedPTS)) {
4649 // the transform failed. this shouldn't happen, but if it does
4650 // then just drop this buffer
4651 ALOGW("timedGetNextBuffer transform failed");
4652 buffer->raw = 0;
4653 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07004654 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08004655 return NO_ERROR;
4656 }
4657
4658 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
4659 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
4660 &headLocalPTS)) {
4661 buffer->raw = 0;
4662 buffer->frameCount = 0;
4663 return INVALID_OPERATION;
4664 }
4665 } else {
4666 headLocalPTS = transformedPTS;
4667 }
4668 }
4669
4670 // adjust the head buffer's PTS to reflect the portion of the head buffer
4671 // that has already been consumed
4672 int64_t effectivePTS = headLocalPTS +
4673 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4674
4675 // Calculate the delta in samples between the head of the input buffer
4676 // queue and the start of the next output buffer that will be written.
4677 // If the transformation fails because of over or underflow, it means
4678 // that the sample's position in the output stream is so far out of
4679 // whack that it should just be dropped.
4680 int64_t sampleDelta;
4681 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4682 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004683 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
4684 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08004685 continue;
4686 }
4687 if (!mLocalTimeToSampleTransform.doForwardTransform(
4688 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07004689 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004690 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08004691 continue;
4692 }
4693
John Grossman1c345192012-03-27 14:00:17 -07004694 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
4695 " sampleDelta=[%d.%08x]",
4696 head.pts(), head.position(), pts,
4697 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
4698 + (sampleDelta >> 32)),
4699 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08004700
4701 // if the delta between the ideal placement for the next input sample and
4702 // the current output position is within this threshold, then we will
4703 // concatenate the next input samples to the previous output
4704 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07004705 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08004706
4707 // if this is the first buffer of audio that we're emitting from this track
4708 // then it should be almost exactly on time.
4709 const int64_t kSampleStartupThreshold = 1LL << 32;
4710
4711 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07004712 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004713 // the next input is close enough to being on time, so concatenate it
4714 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07004715 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004716
John Grossman1c345192012-03-27 14:00:17 -07004717 ALOGVV("*** on time: head.pos=%d frameCount=%u",
4718 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08004719 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07004720 }
4721
4722 // Looks like our output is not on time. Reset our on timed status.
4723 // Next time we mix samples from our input queue, then should be within
4724 // the StartupThreshold.
4725 mTimedAudioOutputOnTime = false;
4726 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004727 // the gap between the current output position and the proper start of
4728 // the next input sample is too big, so fill it with silence
4729 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4730
John Grossman9fbdee12012-03-26 17:51:46 -07004731 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004732 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4733 return NO_ERROR;
4734 } else {
4735 // the next input sample is late
4736 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4737 size_t onTimeSamplePosition =
4738 head.position() + lateFrames * mCblk->frameSize;
4739
4740 if (onTimeSamplePosition > head.buffer()->size()) {
4741 // all the remaining samples in the head are too late, so
4742 // drop it and move on
4743 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004744 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08004745 continue;
4746 } else {
4747 // skip over the late samples
4748 head.setPosition(onTimeSamplePosition);
4749
4750 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07004751 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004752
4753 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4754 return NO_ERROR;
4755 }
4756 }
4757 }
4758}
4759
4760// Yield samples from the timed buffer queue head up to the given output
4761// buffer's capacity.
4762//
4763// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004764void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004765 AudioBufferProvider::Buffer* buffer) {
4766
4767 const TimedBuffer& head = mTimedBufferQueue[0];
4768
4769 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4770 head.position());
4771
4772 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4773 mCblk->frameSize);
4774 size_t framesRequested = buffer->frameCount;
4775 buffer->frameCount = min(framesLeftInHead, framesRequested);
4776
John Grossman9fbdee12012-03-26 17:51:46 -07004777 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08004778 mTimedAudioOutputOnTime = true;
4779}
4780
4781// Yield samples of silence up to the given output buffer's capacity
4782//
4783// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004784void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004785 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4786
4787 // lazily allocate a buffer filled with silence
4788 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4789 delete [] mTimedSilenceBuffer;
4790 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4791 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4792 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4793 }
4794
4795 buffer->raw = mTimedSilenceBuffer;
4796 size_t framesRequested = buffer->frameCount;
4797 buffer->frameCount = min(numFrames, framesRequested);
4798
4799 mTimedAudioOutputOnTime = false;
4800}
4801
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004802// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004803void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4804 AudioBufferProvider::Buffer* buffer) {
4805
4806 Mutex::Autolock _l(mTimedBufferQueueLock);
4807
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004808 // If the buffer which was just released is part of the buffer at the head
4809 // of the queue, be sure to update the amt of the buffer which has been
4810 // consumed. If the buffer being returned is not part of the head of the
4811 // queue, its either because the buffer is part of the silence buffer, or
4812 // because the head of the timed queue was trimmed after the mixer called
4813 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07004814 if (buffer->raw == mTimedSilenceBuffer) {
4815 ALOG_ASSERT(!mQueueHeadInFlight,
4816 "Queue head in flight during release of silence buffer!");
4817 goto done;
4818 }
4819
4820 ALOG_ASSERT(mQueueHeadInFlight,
4821 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
4822 " head in flight.");
4823
4824 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004825 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004826
4827 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07004828 void* end = reinterpret_cast<void*>(
4829 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
4830 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004831
John Grossman9fbdee12012-03-26 17:51:46 -07004832 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
4833 "released buffer not within the head of the timed buffer"
4834 " queue; qHead = [%p, %p], released buffer = %p",
4835 start, end, buffer->raw);
4836
4837 head.setPosition(head.position() +
4838 (buffer->frameCount * mCblk->frameSize));
4839 mQueueHeadInFlight = false;
4840
John Grossman1c345192012-03-27 14:00:17 -07004841 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
4842 "Bad bookkeeping during releaseBuffer! Should have at"
4843 " least %u queued frames, but we think we have only %u",
4844 buffer->frameCount, mFramesPendingInQueue);
4845
4846 mFramesPendingInQueue -= buffer->frameCount;
4847
John Grossman9fbdee12012-03-26 17:51:46 -07004848 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
4849 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07004850 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07004851 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004852 }
John Grossman9fbdee12012-03-26 17:51:46 -07004853 } else {
4854 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
4855 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08004856 }
4857
John Grossman9fbdee12012-03-26 17:51:46 -07004858done:
John Grossman4ff14ba2012-02-08 16:37:41 -08004859 buffer->raw = 0;
4860 buffer->frameCount = 0;
4861}
4862
4863uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4864 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07004865 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08004866}
4867
4868AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4869 : mPTS(0), mPosition(0) {}
4870
4871AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4872 const sp<IMemory>& buffer, int64_t pts)
4873 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4874
Mathias Agopian65ab4712010-07-14 17:59:35 -07004875// ----------------------------------------------------------------------------
4876
4877// RecordTrack constructor must be called with AudioFlinger::mLock held
4878AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004879 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004880 const sp<Client>& client,
4881 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004882 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004883 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004884 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004885 int sessionId)
4886 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004887 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004888 mOverflow(false)
4889{
4890 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004891 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
4892 if (format == AUDIO_FORMAT_PCM_16_BIT) {
4893 mCblk->frameSize = mChannelCount * sizeof(int16_t);
4894 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
4895 mCblk->frameSize = mChannelCount * sizeof(int8_t);
4896 } else {
4897 mCblk->frameSize = sizeof(int8_t);
4898 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004899 }
4900}
4901
4902AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4903{
4904 sp<ThreadBase> thread = mThread.promote();
4905 if (thread != 0) {
4906 AudioSystem::releaseInput(thread->id());
4907 }
4908}
4909
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004910// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004911status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004912{
4913 audio_track_cblk_t* cblk = this->cblk();
4914 uint32_t framesAvail;
4915 uint32_t framesReq = buffer->frameCount;
4916
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004917 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004918 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004919 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004920 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004921 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004922 }
4923
4924 framesAvail = cblk->framesAvailable_l();
4925
Glenn Kastenf6b16782011-12-15 09:51:17 -08004926 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004927 uint32_t s = cblk->server;
4928 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4929
4930 if (framesReq > framesAvail) {
4931 framesReq = framesAvail;
4932 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004933 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004934 framesReq = bufferEnd - s;
4935 }
4936
4937 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004938 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004939
4940 buffer->frameCount = framesReq;
4941 return NO_ERROR;
4942 }
4943
4944getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004945 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004946 buffer->frameCount = 0;
4947 return NOT_ENOUGH_DATA;
4948}
4949
Glenn Kasten3acbd052012-02-28 10:39:56 -08004950status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004951 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004952{
4953 sp<ThreadBase> thread = mThread.promote();
4954 if (thread != 0) {
4955 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08004956 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004957 } else {
4958 return BAD_VALUE;
4959 }
4960}
4961
4962void AudioFlinger::RecordThread::RecordTrack::stop()
4963{
4964 sp<ThreadBase> thread = mThread.promote();
4965 if (thread != 0) {
4966 RecordThread *recordThread = (RecordThread *)thread.get();
4967 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004968 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08004969 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07004970 // read from buffer
4971 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004972 }
4973}
4974
4975void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4976{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004977 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004978 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004979 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004980 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004981 mSessionId,
4982 mFrameCount,
4983 mState,
4984 mCblk->sampleRate,
4985 mCblk->server,
4986 mCblk->user);
4987}
4988
4989
4990// ----------------------------------------------------------------------------
4991
4992AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004993 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004994 DuplicatingThread *sourceThread,
4995 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004996 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004997 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004998 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07004999 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5000 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005001 mActive(false), mSourceThread(sourceThread)
5002{
5003
Mathias Agopian65ab4712010-07-14 17:59:35 -07005004 if (mCblk != NULL) {
5005 mCblk->flags |= CBLK_DIRECTION_OUT;
5006 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005007 mOutBuffer.frameCount = 0;
5008 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005009 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005010 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5011 mCblk, mBuffer, mCblk->buffers,
5012 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005013 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005014 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005015 }
5016}
5017
5018AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5019{
5020 clearBufferQueue();
5021}
5022
Glenn Kasten3acbd052012-02-28 10:39:56 -08005023status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005024 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005025{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005026 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005027 if (status != NO_ERROR) {
5028 return status;
5029 }
5030
5031 mActive = true;
5032 mRetryCount = 127;
5033 return status;
5034}
5035
5036void AudioFlinger::PlaybackThread::OutputTrack::stop()
5037{
5038 Track::stop();
5039 clearBufferQueue();
5040 mOutBuffer.frameCount = 0;
5041 mActive = false;
5042}
5043
5044bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5045{
5046 Buffer *pInBuffer;
5047 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005048 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005049 bool outputBufferFull = false;
5050 inBuffer.frameCount = frames;
5051 inBuffer.i16 = data;
5052
5053 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5054
5055 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005056 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005057 sp<ThreadBase> thread = mThread.promote();
5058 if (thread != 0) {
5059 MixerThread *mixerThread = (MixerThread *)thread.get();
5060 if (mCblk->frameCount > frames){
5061 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5062 uint32_t startFrames = (mCblk->frameCount - frames);
5063 pInBuffer = new Buffer;
5064 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5065 pInBuffer->frameCount = startFrames;
5066 pInBuffer->i16 = pInBuffer->mBuffer;
5067 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5068 mBufferQueue.add(pInBuffer);
5069 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005070 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005071 }
5072 }
5073 }
5074 }
5075
5076 while (waitTimeLeftMs) {
5077 // First write pending buffers, then new data
5078 if (mBufferQueue.size()) {
5079 pInBuffer = mBufferQueue.itemAt(0);
5080 } else {
5081 pInBuffer = &inBuffer;
5082 }
5083
5084 if (pInBuffer->frameCount == 0) {
5085 break;
5086 }
5087
5088 if (mOutBuffer.frameCount == 0) {
5089 mOutBuffer.frameCount = pInBuffer->frameCount;
5090 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005091 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005092 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005093 outputBufferFull = true;
5094 break;
5095 }
5096 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5097 if (waitTimeLeftMs >= waitTimeMs) {
5098 waitTimeLeftMs -= waitTimeMs;
5099 } else {
5100 waitTimeLeftMs = 0;
5101 }
5102 }
5103
5104 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5105 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5106 mCblk->stepUser(outFrames);
5107 pInBuffer->frameCount -= outFrames;
5108 pInBuffer->i16 += outFrames * channelCount;
5109 mOutBuffer.frameCount -= outFrames;
5110 mOutBuffer.i16 += outFrames * channelCount;
5111
5112 if (pInBuffer->frameCount == 0) {
5113 if (mBufferQueue.size()) {
5114 mBufferQueue.removeAt(0);
5115 delete [] pInBuffer->mBuffer;
5116 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005117 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005118 } else {
5119 break;
5120 }
5121 }
5122 }
5123
5124 // If we could not write all frames, allocate a buffer and queue it for next time.
5125 if (inBuffer.frameCount) {
5126 sp<ThreadBase> thread = mThread.promote();
5127 if (thread != 0 && !thread->standby()) {
5128 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5129 pInBuffer = new Buffer;
5130 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5131 pInBuffer->frameCount = inBuffer.frameCount;
5132 pInBuffer->i16 = pInBuffer->mBuffer;
5133 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5134 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005135 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005136 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005137 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005138 }
5139 }
5140 }
5141
5142 // Calling write() with a 0 length buffer, means that no more data will be written:
5143 // If no more buffers are pending, fill output track buffer to make sure it is started
5144 // by output mixer.
5145 if (frames == 0 && mBufferQueue.size() == 0) {
5146 if (mCblk->user < mCblk->frameCount) {
5147 frames = mCblk->frameCount - mCblk->user;
5148 pInBuffer = new Buffer;
5149 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5150 pInBuffer->frameCount = frames;
5151 pInBuffer->i16 = pInBuffer->mBuffer;
5152 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5153 mBufferQueue.add(pInBuffer);
5154 } else if (mActive) {
5155 stop();
5156 }
5157 }
5158
5159 return outputBufferFull;
5160}
5161
5162status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5163{
5164 int active;
5165 status_t result;
5166 audio_track_cblk_t* cblk = mCblk;
5167 uint32_t framesReq = buffer->frameCount;
5168
Steve Block3856b092011-10-20 11:56:00 +01005169// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005170 buffer->frameCount = 0;
5171
5172 uint32_t framesAvail = cblk->framesAvailable();
5173
5174
5175 if (framesAvail == 0) {
5176 Mutex::Autolock _l(cblk->lock);
5177 goto start_loop_here;
5178 while (framesAvail == 0) {
5179 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005180 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005181 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005182 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005183 }
5184 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5185 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005186 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005187 }
5188 // read the server count again
5189 start_loop_here:
5190 framesAvail = cblk->framesAvailable_l();
5191 }
5192 }
5193
5194// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005195// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005196// }
5197
5198 if (framesReq > framesAvail) {
5199 framesReq = framesAvail;
5200 }
5201
5202 uint32_t u = cblk->user;
5203 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5204
Marco Nelissena1472d92012-03-30 14:36:54 -07005205 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005206 framesReq = bufferEnd - u;
5207 }
5208
5209 buffer->frameCount = framesReq;
5210 buffer->raw = (void *)cblk->buffer(u);
5211 return NO_ERROR;
5212}
5213
5214
5215void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5216{
5217 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005218
5219 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005220 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005221 delete [] pBuffer->mBuffer;
5222 delete pBuffer;
5223 }
5224 mBufferQueue.clear();
5225}
5226
5227// ----------------------------------------------------------------------------
5228
5229AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5230 : RefBase(),
5231 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005232 // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below
Mathias Agopian65ab4712010-07-14 17:59:35 -07005233 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005234 mPid(pid),
5235 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005236{
5237 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5238}
5239
5240// Client destructor must be called with AudioFlinger::mLock held
5241AudioFlinger::Client::~Client()
5242{
5243 mAudioFlinger->removeClient_l(mPid);
5244}
5245
Glenn Kasten435dbe62012-01-30 10:15:48 -08005246sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005247{
5248 return mMemoryDealer;
5249}
5250
John Grossman4ff14ba2012-02-08 16:37:41 -08005251// Reserve one of the limited slots for a timed audio track associated
5252// with this client
5253bool AudioFlinger::Client::reserveTimedTrack()
5254{
5255 const int kMaxTimedTracksPerClient = 4;
5256
5257 Mutex::Autolock _l(mTimedTrackLock);
5258
5259 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5260 ALOGW("can not create timed track - pid %d has exceeded the limit",
5261 mPid);
5262 return false;
5263 }
5264
5265 mTimedTrackCount++;
5266 return true;
5267}
5268
5269// Release a slot for a timed audio track
5270void AudioFlinger::Client::releaseTimedTrack()
5271{
5272 Mutex::Autolock _l(mTimedTrackLock);
5273 mTimedTrackCount--;
5274}
5275
Mathias Agopian65ab4712010-07-14 17:59:35 -07005276// ----------------------------------------------------------------------------
5277
5278AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5279 const sp<IAudioFlingerClient>& client,
5280 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005281 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005282{
5283}
5284
5285AudioFlinger::NotificationClient::~NotificationClient()
5286{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005287}
5288
5289void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5290{
5291 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005292 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005293}
5294
5295// ----------------------------------------------------------------------------
5296
5297AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5298 : BnAudioTrack(),
5299 mTrack(track)
5300{
5301}
5302
5303AudioFlinger::TrackHandle::~TrackHandle() {
5304 // just stop the track on deletion, associated resources
5305 // will be freed from the main thread once all pending buffers have
5306 // been played. Unless it's not in the active track list, in which
5307 // case we free everything now...
5308 mTrack->destroy();
5309}
5310
Glenn Kasten90716c52012-01-26 13:40:12 -08005311sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5312 return mTrack->getCblk();
5313}
5314
Glenn Kasten3acbd052012-02-28 10:39:56 -08005315status_t AudioFlinger::TrackHandle::start() {
5316 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005317}
5318
5319void AudioFlinger::TrackHandle::stop() {
5320 mTrack->stop();
5321}
5322
5323void AudioFlinger::TrackHandle::flush() {
5324 mTrack->flush();
5325}
5326
5327void AudioFlinger::TrackHandle::mute(bool e) {
5328 mTrack->mute(e);
5329}
5330
5331void AudioFlinger::TrackHandle::pause() {
5332 mTrack->pause();
5333}
5334
Mathias Agopian65ab4712010-07-14 17:59:35 -07005335status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5336{
5337 return mTrack->attachAuxEffect(EffectId);
5338}
5339
John Grossman4ff14ba2012-02-08 16:37:41 -08005340status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5341 sp<IMemory>* buffer) {
5342 if (!mTrack->isTimedTrack())
5343 return INVALID_OPERATION;
5344
5345 PlaybackThread::TimedTrack* tt =
5346 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5347 return tt->allocateTimedBuffer(size, buffer);
5348}
5349
5350status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5351 int64_t pts) {
5352 if (!mTrack->isTimedTrack())
5353 return INVALID_OPERATION;
5354
5355 PlaybackThread::TimedTrack* tt =
5356 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5357 return tt->queueTimedBuffer(buffer, pts);
5358}
5359
5360status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5361 const LinearTransform& xform, int target) {
5362
5363 if (!mTrack->isTimedTrack())
5364 return INVALID_OPERATION;
5365
5366 PlaybackThread::TimedTrack* tt =
5367 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5368 return tt->setMediaTimeTransform(
5369 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5370}
5371
Mathias Agopian65ab4712010-07-14 17:59:35 -07005372status_t AudioFlinger::TrackHandle::onTransact(
5373 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5374{
5375 return BnAudioTrack::onTransact(code, data, reply, flags);
5376}
5377
5378// ----------------------------------------------------------------------------
5379
5380sp<IAudioRecord> AudioFlinger::openRecord(
5381 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005382 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005383 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005384 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005385 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005386 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005387 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005388 int *sessionId,
5389 status_t *status)
5390{
5391 sp<RecordThread::RecordTrack> recordTrack;
5392 sp<RecordHandle> recordHandle;
5393 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005394 status_t lStatus;
5395 RecordThread *thread;
5396 size_t inFrameCount;
5397 int lSessionId;
5398
5399 // check calling permissions
5400 if (!recordingAllowed()) {
5401 lStatus = PERMISSION_DENIED;
5402 goto Exit;
5403 }
5404
5405 // add client to list
5406 { // scope for mLock
5407 Mutex::Autolock _l(mLock);
5408 thread = checkRecordThread_l(input);
5409 if (thread == NULL) {
5410 lStatus = BAD_VALUE;
5411 goto Exit;
5412 }
5413
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005414 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005415
5416 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005417 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005418 lSessionId = *sessionId;
5419 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005420 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005421 if (sessionId != NULL) {
5422 *sessionId = lSessionId;
5423 }
5424 }
5425 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005426 recordTrack = thread->createRecordTrack_l(client,
5427 sampleRate,
5428 format,
5429 channelMask,
5430 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005431 lSessionId,
5432 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005433 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005434 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005435 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5436 // destructor is called by the TrackBase destructor with mLock held
5437 client.clear();
5438 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005439 goto Exit;
5440 }
5441
5442 // return to handle to client
5443 recordHandle = new RecordHandle(recordTrack);
5444 lStatus = NO_ERROR;
5445
5446Exit:
5447 if (status) {
5448 *status = lStatus;
5449 }
5450 return recordHandle;
5451}
5452
5453// ----------------------------------------------------------------------------
5454
5455AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5456 : BnAudioRecord(),
5457 mRecordTrack(recordTrack)
5458{
5459}
5460
5461AudioFlinger::RecordHandle::~RecordHandle() {
5462 stop();
5463}
5464
Glenn Kasten90716c52012-01-26 13:40:12 -08005465sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5466 return mRecordTrack->getCblk();
5467}
5468
Glenn Kasten3acbd052012-02-28 10:39:56 -08005469status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005470 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005471 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005472}
5473
5474void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005475 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005476 mRecordTrack->stop();
5477}
5478
Mathias Agopian65ab4712010-07-14 17:59:35 -07005479status_t AudioFlinger::RecordHandle::onTransact(
5480 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5481{
5482 return BnAudioRecord::onTransact(code, data, reply, flags);
5483}
5484
5485// ----------------------------------------------------------------------------
5486
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005487AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5488 AudioStreamIn *input,
5489 uint32_t sampleRate,
5490 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005491 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005492 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005493 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005494 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5495 // mRsmpInIndex and mInputBytes set by readInputParameters()
5496 mReqChannelCount(popcount(channels)),
5497 mReqSampleRate(sampleRate)
5498 // mBytesRead is only meaningful while active, and so is cleared in start()
5499 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005500{
Glenn Kasten480b4682012-02-28 12:30:08 -08005501 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005502
Mathias Agopian65ab4712010-07-14 17:59:35 -07005503 readInputParameters();
5504}
5505
5506
5507AudioFlinger::RecordThread::~RecordThread()
5508{
5509 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005510 delete mResampler;
5511 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005512}
5513
5514void AudioFlinger::RecordThread::onFirstRef()
5515{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005516 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005517}
5518
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005519status_t AudioFlinger::RecordThread::readyToRun()
5520{
5521 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005522 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005523 return status;
5524}
5525
Mathias Agopian65ab4712010-07-14 17:59:35 -07005526bool AudioFlinger::RecordThread::threadLoop()
5527{
5528 AudioBufferProvider::Buffer buffer;
5529 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005530 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005531
Eric Laurent44d98482010-09-30 16:12:31 -07005532 nsecs_t lastWarning = 0;
5533
Eric Laurentfeb0db62011-07-22 09:04:31 -07005534 acquireWakeLock();
5535
Mathias Agopian65ab4712010-07-14 17:59:35 -07005536 // start recording
5537 while (!exitPending()) {
5538
5539 processConfigEvents();
5540
5541 { // scope for mLock
5542 Mutex::Autolock _l(mLock);
5543 checkForNewParameters_l();
5544 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5545 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005546 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005547 mStandby = true;
5548 }
5549
5550 if (exitPending()) break;
5551
Eric Laurentfeb0db62011-07-22 09:04:31 -07005552 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005553 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005554 // go to sleep
5555 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005556 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005557 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005558 continue;
5559 }
5560 if (mActiveTrack != 0) {
5561 if (mActiveTrack->mState == TrackBase::PAUSING) {
5562 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005563 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005564 mStandby = true;
5565 }
5566 mActiveTrack.clear();
5567 mStartStopCond.broadcast();
5568 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5569 if (mReqChannelCount != mActiveTrack->channelCount()) {
5570 mActiveTrack.clear();
5571 mStartStopCond.broadcast();
5572 } else if (mBytesRead != 0) {
5573 // record start succeeds only if first read from audio input
5574 // succeeds
5575 if (mBytesRead > 0) {
5576 mActiveTrack->mState = TrackBase::ACTIVE;
5577 } else {
5578 mActiveTrack.clear();
5579 }
5580 mStartStopCond.broadcast();
5581 }
5582 mStandby = false;
5583 }
5584 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005585 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005586 }
5587
5588 if (mActiveTrack != 0) {
5589 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5590 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005591 unlockEffectChains(effectChains);
5592 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005593 continue;
5594 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005595 for (size_t i = 0; i < effectChains.size(); i ++) {
5596 effectChains[i]->process_l();
5597 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005598
Mathias Agopian65ab4712010-07-14 17:59:35 -07005599 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005600 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005601 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08005602 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005603 // no resampling
5604 while (framesOut) {
5605 size_t framesIn = mFrameCount - mRsmpInIndex;
5606 if (framesIn) {
5607 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
5608 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
5609 if (framesIn > framesOut)
5610 framesIn = framesOut;
5611 mRsmpInIndex += framesIn;
5612 framesOut -= framesIn;
5613 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07005614 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005615 memcpy(dst, src, framesIn * mFrameSize);
5616 } else {
5617 int16_t *src16 = (int16_t *)src;
5618 int16_t *dst16 = (int16_t *)dst;
5619 if (mChannelCount == 1) {
5620 while (framesIn--) {
5621 *dst16++ = *src16;
5622 *dst16++ = *src16++;
5623 }
5624 } else {
5625 while (framesIn--) {
5626 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
5627 src16 += 2;
5628 }
5629 }
5630 }
5631 }
5632 if (framesOut && mFrameCount == mRsmpInIndex) {
5633 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005634 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005635 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005636 framesOut = 0;
5637 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07005638 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005639 mRsmpInIndex = 0;
5640 }
5641 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005642 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005643 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5644 // Force input into standby so that it tries to
5645 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005646 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005647 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005648 }
5649 mRsmpInIndex = mFrameCount;
5650 framesOut = 0;
5651 buffer.frameCount = 0;
5652 }
5653 }
5654 }
5655 } else {
5656 // resampling
5657
5658 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
5659 // alter output frame count as if we were expecting stereo samples
5660 if (mChannelCount == 1 && mReqChannelCount == 1) {
5661 framesOut >>= 1;
5662 }
5663 mResampler->resample(mRsmpOutBuffer, framesOut, this);
5664 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
5665 // are 32 bit aligned which should be always true.
5666 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005667 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005668 // the resampler always outputs stereo samples: do post stereo to mono conversion
5669 int16_t *src = (int16_t *)mRsmpOutBuffer;
5670 int16_t *dst = buffer.i16;
5671 while (framesOut--) {
5672 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
5673 src += 2;
5674 }
5675 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005676 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005677 }
5678
5679 }
Eric Laurenta011e352012-03-29 15:51:43 -07005680 if (mFramestoDrop == 0) {
5681 mActiveTrack->releaseBuffer(&buffer);
5682 } else {
5683 if (mFramestoDrop > 0) {
5684 mFramestoDrop -= buffer.frameCount;
5685 if (mFramestoDrop < 0) {
5686 mFramestoDrop = 0;
5687 }
5688 }
5689 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005690 mActiveTrack->overflow();
5691 }
5692 // client isn't retrieving buffers fast enough
5693 else {
Eric Laurent44d98482010-09-30 16:12:31 -07005694 if (!mActiveTrack->setOverflow()) {
5695 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08005696 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005697 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07005698 lastWarning = now;
5699 }
5700 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005701 // Release the processor for a while before asking for a new buffer.
5702 // This will give the application more chance to read from the buffer and
5703 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005704 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005705 }
5706 }
Eric Laurentec437d82011-07-26 20:54:46 -07005707 // enable changes in effect chain
5708 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005709 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005710 }
5711
5712 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005713 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005714 }
5715 mActiveTrack.clear();
5716
5717 mStartStopCond.broadcast();
5718
Eric Laurentfeb0db62011-07-22 09:04:31 -07005719 releaseWakeLock();
5720
Steve Block3856b092011-10-20 11:56:00 +01005721 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005722 return false;
5723}
5724
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005725
5726sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5727 const sp<AudioFlinger::Client>& client,
5728 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005729 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005730 int channelMask,
5731 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005732 int sessionId,
5733 status_t *status)
5734{
5735 sp<RecordTrack> track;
5736 status_t lStatus;
5737
5738 lStatus = initCheck();
5739 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005740 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005741 goto Exit;
5742 }
5743
5744 { // scope for mLock
5745 Mutex::Autolock _l(mLock);
5746
5747 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005748 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005749
Glenn Kasten7378ca52012-01-20 13:44:40 -08005750 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005751 lStatus = NO_MEMORY;
5752 goto Exit;
5753 }
5754
5755 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005756 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5757 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005758 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005759 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5760 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005761 }
5762 lStatus = NO_ERROR;
5763
5764Exit:
5765 if (status) {
5766 *status = lStatus;
5767 }
5768 return track;
5769}
5770
Eric Laurenta011e352012-03-29 15:51:43 -07005771status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08005772 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005773 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005774{
Glenn Kasten58912562012-04-03 10:45:00 -07005775 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005776 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005777 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07005778
5779 if (event == AudioSystem::SYNC_EVENT_NONE) {
5780 mSyncStartEvent.clear();
5781 mFramestoDrop = 0;
5782 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
5783 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
5784 triggerSession,
5785 recordTrack->sessionId(),
5786 syncStartEventCallback,
5787 this);
5788 mFramestoDrop = -1;
5789 }
5790
Mathias Agopian65ab4712010-07-14 17:59:35 -07005791 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005792 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005793 if (mActiveTrack != 0) {
5794 if (recordTrack != mActiveTrack.get()) {
5795 status = -EBUSY;
5796 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5797 mActiveTrack->mState = TrackBase::ACTIVE;
5798 }
5799 return status;
5800 }
5801
5802 recordTrack->mState = TrackBase::IDLE;
5803 mActiveTrack = recordTrack;
5804 mLock.unlock();
5805 status_t status = AudioSystem::startInput(mId);
5806 mLock.lock();
5807 if (status != NO_ERROR) {
5808 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07005809 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005810 return status;
5811 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005812 mRsmpInIndex = mFrameCount;
5813 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005814 if (mResampler != NULL) {
5815 mResampler->reset();
5816 }
5817 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005818 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005819 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005820 mWaitWorkCV.signal();
5821 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005822 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005823 mActiveTrack.clear();
5824 status = INVALID_OPERATION;
5825 goto startError;
5826 }
5827 mStartStopCond.wait(mLock);
5828 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005829 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005830 status = BAD_VALUE;
5831 goto startError;
5832 }
Steve Block3856b092011-10-20 11:56:00 +01005833 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005834 return status;
5835 }
5836startError:
5837 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07005838 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005839 return status;
5840}
5841
Eric Laurenta011e352012-03-29 15:51:43 -07005842void AudioFlinger::RecordThread::clearSyncStartEvent()
5843{
5844 if (mSyncStartEvent != 0) {
5845 mSyncStartEvent->cancel();
5846 }
5847 mSyncStartEvent.clear();
5848}
5849
5850void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5851{
5852 sp<SyncEvent> strongEvent = event.promote();
5853
5854 if (strongEvent != 0) {
5855 RecordThread *me = (RecordThread *)strongEvent->cookie();
5856 me->handleSyncStartEvent(strongEvent);
5857 }
5858}
5859
5860void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
5861{
5862 ALOGV("handleSyncStartEvent() mActiveTrack %p session %d event->listenerSession() %d",
5863 mActiveTrack.get(),
5864 mActiveTrack.get() ? mActiveTrack->sessionId() : 0,
5865 event->listenerSession());
5866
5867 if (mActiveTrack != 0 &&
5868 event == mSyncStartEvent) {
5869 // TODO: use actual buffer filling status instead of 2 buffers when info is available
5870 // from audio HAL
5871 mFramestoDrop = mFrameCount * 2;
5872 mSyncStartEvent.clear();
5873 }
5874}
5875
Mathias Agopian65ab4712010-07-14 17:59:35 -07005876void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005877 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005878 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005879 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005880 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005881 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5882 mActiveTrack->mState = TrackBase::PAUSING;
5883 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005884 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005885 return;
5886 }
5887 mStartStopCond.wait(mLock);
5888 // if we have been restarted, recordTrack == mActiveTrack.get() here
5889 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5890 mLock.unlock();
5891 AudioSystem::stopInput(mId);
5892 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005893 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005894 }
5895 }
5896 }
5897}
5898
Eric Laurenta011e352012-03-29 15:51:43 -07005899bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
5900{
5901 return false;
5902}
5903
5904status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
5905{
5906 if (!isValidSyncEvent(event)) {
5907 return BAD_VALUE;
5908 }
5909
5910 Mutex::Autolock _l(mLock);
5911
5912 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
5913 mTrack->setSyncEvent(event);
5914 return NO_ERROR;
5915 }
5916 return NAME_NOT_FOUND;
5917}
5918
Mathias Agopian65ab4712010-07-14 17:59:35 -07005919status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5920{
5921 const size_t SIZE = 256;
5922 char buffer[SIZE];
5923 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005924
5925 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5926 result.append(buffer);
5927
5928 if (mActiveTrack != 0) {
5929 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005930 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005931 mActiveTrack->dump(buffer, SIZE);
5932 result.append(buffer);
5933
5934 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5935 result.append(buffer);
5936 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5937 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005938 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005939 result.append(buffer);
5940 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5941 result.append(buffer);
5942 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5943 result.append(buffer);
5944
5945
5946 } else {
5947 result.append("No record client\n");
5948 }
5949 write(fd, result.string(), result.size());
5950
5951 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005952 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005953
5954 return NO_ERROR;
5955}
5956
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005957// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005958status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005959{
5960 size_t framesReq = buffer->frameCount;
5961 size_t framesReady = mFrameCount - mRsmpInIndex;
5962 int channelCount;
5963
5964 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005965 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005966 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005967 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005968 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5969 // Force input into standby so that it tries to
5970 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005971 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005972 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005973 }
Glenn Kastene0feee32011-12-13 11:53:26 -08005974 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005975 buffer->frameCount = 0;
5976 return NOT_ENOUGH_DATA;
5977 }
5978 mRsmpInIndex = 0;
5979 framesReady = mFrameCount;
5980 }
5981
5982 if (framesReq > framesReady) {
5983 framesReq = framesReady;
5984 }
5985
5986 if (mChannelCount == 1 && mReqChannelCount == 2) {
5987 channelCount = 1;
5988 } else {
5989 channelCount = 2;
5990 }
5991 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5992 buffer->frameCount = framesReq;
5993 return NO_ERROR;
5994}
5995
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005996// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07005997void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5998{
5999 mRsmpInIndex += buffer->frameCount;
6000 buffer->frameCount = 0;
6001}
6002
6003bool AudioFlinger::RecordThread::checkForNewParameters_l()
6004{
6005 bool reconfig = false;
6006
6007 while (!mNewParameters.isEmpty()) {
6008 status_t status = NO_ERROR;
6009 String8 keyValuePair = mNewParameters[0];
6010 AudioParameter param = AudioParameter(keyValuePair);
6011 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006012 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006013 int reqSamplingRate = mReqSampleRate;
6014 int reqChannelCount = mReqChannelCount;
6015
6016 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6017 reqSamplingRate = value;
6018 reconfig = true;
6019 }
6020 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006021 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006022 reconfig = true;
6023 }
6024 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006025 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006026 reconfig = true;
6027 }
6028 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6029 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006030 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006031 // if frame count is changed after track creation
6032 if (mActiveTrack != 0) {
6033 status = INVALID_OPERATION;
6034 } else {
6035 reconfig = true;
6036 }
6037 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006038 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6039 // forward device change to effects that have requested to be
6040 // aware of attached audio device.
6041 for (size_t i = 0; i < mEffectChains.size(); i++) {
6042 mEffectChains[i]->setDevice_l(value);
6043 }
6044 // store input device and output device but do not forward output device to audio HAL.
6045 // Note that status is ignored by the caller for output device
6046 // (see AudioFlinger::setParameters()
6047 if (value & AUDIO_DEVICE_OUT_ALL) {
6048 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6049 status = BAD_VALUE;
6050 } else {
6051 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006052 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6053 if (mTrack != NULL) {
6054 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006055 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006056 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6057 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6058 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006059 }
6060 mDevice |= (uint32_t)value;
6061 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006062 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006063 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006064 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006065 mInput->stream->common.standby(&mInput->stream->common);
6066 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6067 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006068 }
6069 if (reconfig) {
6070 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006071 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006072 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006073 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006074 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6075 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006076 status = NO_ERROR;
6077 }
6078 if (status == NO_ERROR) {
6079 readInputParameters();
6080 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6081 }
6082 }
6083 }
6084
6085 mNewParameters.removeAt(0);
6086
6087 mParamStatus = status;
6088 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006089 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6090 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006091 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006092 }
6093 return reconfig;
6094}
6095
6096String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6097{
Dima Zavinfce7a472011-04-19 22:30:36 -07006098 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006099 String8 out_s8 = String8();
6100
6101 Mutex::Autolock _l(mLock);
6102 if (initCheck() != NO_ERROR) {
6103 return out_s8;
6104 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006105
Dima Zavin799a70e2011-04-18 16:57:27 -07006106 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006107 out_s8 = String8(s);
6108 free(s);
6109 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006110}
6111
6112void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6113 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006114 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006115
6116 switch (event) {
6117 case AudioSystem::INPUT_OPENED:
6118 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006119 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006120 desc.samplingRate = mSampleRate;
6121 desc.format = mFormat;
6122 desc.frameCount = mFrameCount;
6123 desc.latency = 0;
6124 param2 = &desc;
6125 break;
6126
6127 case AudioSystem::INPUT_CLOSED:
6128 default:
6129 break;
6130 }
6131 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6132}
6133
6134void AudioFlinger::RecordThread::readInputParameters()
6135{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006136 delete mRsmpInBuffer;
6137 // mRsmpInBuffer is always assigned a new[] below
6138 delete mRsmpOutBuffer;
6139 mRsmpOutBuffer = NULL;
6140 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006141 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006142
Dima Zavin799a70e2011-04-18 16:57:27 -07006143 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006144 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6145 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006146 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006147 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006148 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006149 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006150 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006151 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6152
Glenn Kasten53d76db2012-03-08 12:32:47 -08006153 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006154 {
6155 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006156 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6157 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006158 if (mChannelCount == 1 && mReqChannelCount == 2) {
6159 channelCount = 1;
6160 } else {
6161 channelCount = 2;
6162 }
6163 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6164 mResampler->setSampleRate(mSampleRate);
6165 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6166 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6167
6168 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6169 if (mChannelCount == 1 && mReqChannelCount == 1) {
6170 mFrameCount >>= 1;
6171 }
6172
6173 }
6174 mRsmpInIndex = mFrameCount;
6175}
6176
6177unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6178{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006179 Mutex::Autolock _l(mLock);
6180 if (initCheck() != NO_ERROR) {
6181 return 0;
6182 }
6183
Dima Zavin799a70e2011-04-18 16:57:27 -07006184 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006185}
6186
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006187uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6188{
6189 Mutex::Autolock _l(mLock);
6190 uint32_t result = 0;
6191 if (getEffectChain_l(sessionId) != 0) {
6192 result = EFFECT_SESSION;
6193 }
6194
6195 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6196 result |= TRACK_SESSION;
6197 }
6198
6199 return result;
6200}
6201
Eric Laurent59bd0da2011-08-01 09:52:20 -07006202AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6203{
6204 Mutex::Autolock _l(mLock);
6205 return mTrack;
6206}
6207
Glenn Kastenaed850d2012-01-26 09:46:34 -08006208AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006209{
6210 Mutex::Autolock _l(mLock);
6211 return mInput;
6212}
6213
6214AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6215{
6216 Mutex::Autolock _l(mLock);
6217 AudioStreamIn *input = mInput;
6218 mInput = NULL;
6219 return input;
6220}
6221
6222// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006223audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006224{
6225 if (mInput == NULL) {
6226 return NULL;
6227 }
6228 return &mInput->stream->common;
6229}
6230
6231
Mathias Agopian65ab4712010-07-14 17:59:35 -07006232// ----------------------------------------------------------------------------
6233
Eric Laurenta4c5a552012-03-29 10:12:40 -07006234audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6235{
6236 if (!settingsAllowed()) {
6237 return 0;
6238 }
6239 Mutex::Autolock _l(mLock);
6240 return loadHwModule_l(name);
6241}
6242
6243// loadHwModule_l() must be called with AudioFlinger::mLock held
6244audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6245{
6246 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6247 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6248 ALOGW("loadHwModule() module %s already loaded", name);
6249 return mAudioHwDevs.keyAt(i);
6250 }
6251 }
6252
Eric Laurenta4c5a552012-03-29 10:12:40 -07006253 audio_hw_device_t *dev;
6254
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006255 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006256 if (rc) {
6257 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6258 return 0;
6259 }
6260
6261 mHardwareStatus = AUDIO_HW_INIT;
6262 rc = dev->init_check(dev);
6263 mHardwareStatus = AUDIO_HW_IDLE;
6264 if (rc) {
6265 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6266 return 0;
6267 }
6268
6269 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6270 (NULL != dev->set_master_volume)) {
6271 AutoMutex lock(mHardwareLock);
6272 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6273 dev->set_master_volume(dev, mMasterVolume);
6274 mHardwareStatus = AUDIO_HW_IDLE;
6275 }
6276
6277 audio_module_handle_t handle = nextUniqueId();
6278 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6279
6280 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006281 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006282
6283 return handle;
6284
6285}
6286
6287audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6288 audio_devices_t *pDevices,
6289 uint32_t *pSamplingRate,
6290 audio_format_t *pFormat,
6291 audio_channel_mask_t *pChannelMask,
6292 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006293 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006294{
6295 status_t status;
6296 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006297 struct audio_config config = {
6298 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6299 channel_mask: pChannelMask ? *pChannelMask : 0,
6300 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6301 };
6302 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006303 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006304
Eric Laurenta4c5a552012-03-29 10:12:40 -07006305 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6306 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006307 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006308 config.sample_rate,
6309 config.format,
6310 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006311 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006312
6313 if (pDevices == NULL || *pDevices == 0) {
6314 return 0;
6315 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006316
Mathias Agopian65ab4712010-07-14 17:59:35 -07006317 Mutex::Autolock _l(mLock);
6318
Eric Laurenta4c5a552012-03-29 10:12:40 -07006319 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006320 if (outHwDev == NULL)
6321 return 0;
6322
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006323 audio_io_handle_t id = nextUniqueId();
6324
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006325 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006326
6327 status = outHwDev->open_output_stream(outHwDev,
6328 id,
6329 *pDevices,
6330 (audio_output_flags_t)flags,
6331 &config,
6332 &outStream);
6333
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006334 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006335 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006336 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006337 config.sample_rate,
6338 config.format,
6339 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006340 status);
6341
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006342 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006343 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006344
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006345 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006346 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6347 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006348 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006349 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006350 } else {
6351 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006352 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006353 }
6354 mPlaybackThreads.add(id, thread);
6355
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006356 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6357 if (pFormat != NULL) *pFormat = config.format;
6358 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006359 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006360
6361 // notify client processes of the new output creation
6362 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006363
6364 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006365 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006366 ALOGI("Using module %d has the primary audio interface", module);
6367 mPrimaryHardwareDev = outHwDev;
6368
6369 AutoMutex lock(mHardwareLock);
6370 mHardwareStatus = AUDIO_HW_SET_MODE;
6371 outHwDev->set_mode(outHwDev, mMode);
6372
6373 // Determine the level of master volume support the primary audio HAL has,
6374 // and set the initial master volume at the same time.
6375 float initialVolume = 1.0;
6376 mMasterVolumeSupportLvl = MVS_NONE;
6377
6378 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6379 if ((NULL != outHwDev->get_master_volume) &&
6380 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6381 mMasterVolumeSupportLvl = MVS_FULL;
6382 } else {
6383 mMasterVolumeSupportLvl = MVS_SETONLY;
6384 initialVolume = 1.0;
6385 }
6386
6387 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6388 if ((NULL == outHwDev->set_master_volume) ||
6389 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6390 mMasterVolumeSupportLvl = MVS_NONE;
6391 }
6392 // now that we have a primary device, initialize master volume on other devices
6393 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6394 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6395
6396 if ((dev != mPrimaryHardwareDev) &&
6397 (NULL != dev->set_master_volume)) {
6398 dev->set_master_volume(dev, initialVolume);
6399 }
6400 }
6401 mHardwareStatus = AUDIO_HW_IDLE;
6402 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6403 ? initialVolume
6404 : 1.0;
6405 mMasterVolume = initialVolume;
6406 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006407 return id;
6408 }
6409
6410 return 0;
6411}
6412
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006413audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6414 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006415{
6416 Mutex::Autolock _l(mLock);
6417 MixerThread *thread1 = checkMixerThread_l(output1);
6418 MixerThread *thread2 = checkMixerThread_l(output2);
6419
6420 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006421 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006422 return 0;
6423 }
6424
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006425 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006426 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6427 thread->addOutputTrack(thread2);
6428 mPlaybackThreads.add(id, thread);
6429 // notify client processes of the new output creation
6430 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6431 return id;
6432}
6433
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006434status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006435{
6436 // keep strong reference on the playback thread so that
6437 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006438 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006439 {
6440 Mutex::Autolock _l(mLock);
6441 thread = checkPlaybackThread_l(output);
6442 if (thread == NULL) {
6443 return BAD_VALUE;
6444 }
6445
Steve Block3856b092011-10-20 11:56:00 +01006446 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006447
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006448 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006449 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006450 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006451 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6452 dupThread->removeOutputTrack((MixerThread *)thread.get());
6453 }
6454 }
6455 }
Glenn Kastena1117922012-01-26 10:53:32 -08006456 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006457 mPlaybackThreads.removeItem(output);
6458 }
6459 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006460 // The thread entity (active unit of execution) is no longer running here,
6461 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006462
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006463 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006464 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006465 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006466 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006467 out->hwDev->close_output_stream(out->hwDev, out->stream);
6468 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006469 }
6470 return NO_ERROR;
6471}
6472
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006473status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006474{
6475 Mutex::Autolock _l(mLock);
6476 PlaybackThread *thread = checkPlaybackThread_l(output);
6477
6478 if (thread == NULL) {
6479 return BAD_VALUE;
6480 }
6481
Steve Block3856b092011-10-20 11:56:00 +01006482 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006483 thread->suspend();
6484
6485 return NO_ERROR;
6486}
6487
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006488status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006489{
6490 Mutex::Autolock _l(mLock);
6491 PlaybackThread *thread = checkPlaybackThread_l(output);
6492
6493 if (thread == NULL) {
6494 return BAD_VALUE;
6495 }
6496
Steve Block3856b092011-10-20 11:56:00 +01006497 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006498
6499 thread->restore();
6500
6501 return NO_ERROR;
6502}
6503
Eric Laurenta4c5a552012-03-29 10:12:40 -07006504audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6505 audio_devices_t *pDevices,
6506 uint32_t *pSamplingRate,
6507 audio_format_t *pFormat,
6508 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006509{
6510 status_t status;
6511 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006512 struct audio_config config = {
6513 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6514 channel_mask: pChannelMask ? *pChannelMask : 0,
6515 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6516 };
6517 uint32_t reqSamplingRate = config.sample_rate;
6518 audio_format_t reqFormat = config.format;
6519 audio_channel_mask_t reqChannels = config.channel_mask;
6520 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006521 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006522
6523 if (pDevices == NULL || *pDevices == 0) {
6524 return 0;
6525 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006526
Mathias Agopian65ab4712010-07-14 17:59:35 -07006527 Mutex::Autolock _l(mLock);
6528
Eric Laurenta4c5a552012-03-29 10:12:40 -07006529 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006530 if (inHwDev == NULL)
6531 return 0;
6532
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006533 audio_io_handle_t id = nextUniqueId();
6534
6535 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006536 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006537 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006538 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006539 config.sample_rate,
6540 config.format,
6541 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006542 status);
6543
6544 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6545 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6546 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006547 if (status == BAD_VALUE &&
6548 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6549 (config.sample_rate <= 2 * reqSamplingRate) &&
6550 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01006551 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006552 inStream = NULL;
6553 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006554 }
6555
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006556 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006557 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6558
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006559 // Start record thread
6560 // RecorThread require both input and output device indication to forward to audio
6561 // pre processing modules
6562 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6563 thread = new RecordThread(this,
6564 input,
6565 reqSamplingRate,
6566 reqChannels,
6567 id,
6568 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006569 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006570 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006571 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006572 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006573 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006574
Dima Zavin799a70e2011-04-18 16:57:27 -07006575 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006576
6577 // notify client processes of the new input creation
6578 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
6579 return id;
6580 }
6581
6582 return 0;
6583}
6584
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006585status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006586{
6587 // keep strong reference on the record thread so that
6588 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006589 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006590 {
6591 Mutex::Autolock _l(mLock);
6592 thread = checkRecordThread_l(input);
6593 if (thread == NULL) {
6594 return BAD_VALUE;
6595 }
6596
Steve Block3856b092011-10-20 11:56:00 +01006597 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08006598 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006599 mRecordThreads.removeItem(input);
6600 }
6601 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006602 // The thread entity (active unit of execution) is no longer running here,
6603 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006604
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006605 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006606 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006607 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006608 in->hwDev->close_input_stream(in->hwDev, in->stream);
6609 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006610
6611 return NO_ERROR;
6612}
6613
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006614status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006615{
6616 Mutex::Autolock _l(mLock);
6617 MixerThread *dstThread = checkMixerThread_l(output);
6618 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006619 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006620 return BAD_VALUE;
6621 }
6622
Steve Block3856b092011-10-20 11:56:00 +01006623 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006624 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
6625
6626 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6627 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08006628 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006629 MixerThread *srcThread = (MixerThread *)thread;
6630 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006631 }
Eric Laurentde070132010-07-13 04:45:46 -07006632 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006633
6634 return NO_ERROR;
6635}
6636
6637
6638int AudioFlinger::newAudioSessionId()
6639{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006640 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006641}
6642
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006643void AudioFlinger::acquireAudioSessionId(int audioSession)
6644{
6645 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006646 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006647 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006648 size_t num = mAudioSessionRefs.size();
6649 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006650 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006651 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6652 ref->mCnt++;
6653 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006654 return;
6655 }
6656 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006657 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
6658 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006659}
6660
6661void AudioFlinger::releaseAudioSessionId(int audioSession)
6662{
6663 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006664 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006665 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006666 size_t num = mAudioSessionRefs.size();
6667 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006668 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006669 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6670 ref->mCnt--;
6671 ALOGV(" decremented refcount to %d", ref->mCnt);
6672 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006673 mAudioSessionRefs.removeAt(i);
6674 delete ref;
6675 purgeStaleEffects_l();
6676 }
6677 return;
6678 }
6679 }
Steve Block5ff1dd52012-01-05 23:22:43 +00006680 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006681}
6682
6683void AudioFlinger::purgeStaleEffects_l() {
6684
Steve Block3856b092011-10-20 11:56:00 +01006685 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006686
6687 Vector< sp<EffectChain> > chains;
6688
6689 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6690 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
6691 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6692 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07006693 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
6694 chains.push(ec);
6695 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006696 }
6697 }
6698 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6699 sp<RecordThread> t = mRecordThreads.valueAt(i);
6700 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6701 sp<EffectChain> ec = t->mEffectChains[j];
6702 chains.push(ec);
6703 }
6704 }
6705
6706 for (size_t i = 0; i < chains.size(); i++) {
6707 sp<EffectChain> ec = chains[i];
6708 int sessionid = ec->sessionId();
6709 sp<ThreadBase> t = ec->mThread.promote();
6710 if (t == 0) {
6711 continue;
6712 }
6713 size_t numsessionrefs = mAudioSessionRefs.size();
6714 bool found = false;
6715 for (size_t k = 0; k < numsessionrefs; k++) {
6716 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006717 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01006718 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006719 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006720 found = true;
6721 break;
6722 }
6723 }
6724 if (!found) {
6725 // remove all effects from the chain
6726 while (ec->mEffects.size()) {
6727 sp<EffectModule> effect = ec->mEffects[0];
6728 effect->unPin();
6729 Mutex::Autolock _l (t->mLock);
6730 t->removeEffect_l(effect);
6731 for (size_t j = 0; j < effect->mHandles.size(); j++) {
6732 sp<EffectHandle> handle = effect->mHandles[j].promote();
6733 if (handle != 0) {
6734 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07006735 if (handle->mHasControl && handle->mEnabled) {
6736 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
6737 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006738 }
6739 }
6740 AudioSystem::unregisterEffect(effect->id());
6741 }
6742 }
6743 }
6744 return;
6745}
6746
Mathias Agopian65ab4712010-07-14 17:59:35 -07006747// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006748AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006749{
Glenn Kastena1117922012-01-26 10:53:32 -08006750 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006751}
6752
6753// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006754AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006755{
6756 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08006757 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006758}
6759
6760// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006761AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006762{
Glenn Kastena1117922012-01-26 10:53:32 -08006763 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006764}
6765
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006766uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07006767{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006768 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006769}
6770
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006771AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006772{
6773 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6774 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006775 AudioStreamOut *output = thread->getOutput();
6776 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006777 return thread;
6778 }
6779 }
6780 return NULL;
6781}
6782
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006783uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006784{
6785 PlaybackThread *thread = primaryPlaybackThread_l();
6786
6787 if (thread == NULL) {
6788 return 0;
6789 }
6790
6791 return thread->device();
6792}
6793
Eric Laurenta011e352012-03-29 15:51:43 -07006794sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
6795 int triggerSession,
6796 int listenerSession,
6797 sync_event_callback_t callBack,
6798 void *cookie)
6799{
6800 Mutex::Autolock _l(mLock);
6801
6802 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
6803 status_t playStatus = NAME_NOT_FOUND;
6804 status_t recStatus = NAME_NOT_FOUND;
6805 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6806 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
6807 if (playStatus == NO_ERROR) {
6808 return event;
6809 }
6810 }
6811 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6812 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
6813 if (recStatus == NO_ERROR) {
6814 return event;
6815 }
6816 }
6817 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
6818 mPendingSyncEvents.add(event);
6819 } else {
6820 ALOGV("createSyncEvent() invalid event %d", event->type());
6821 event.clear();
6822 }
6823 return event;
6824}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006825
Mathias Agopian65ab4712010-07-14 17:59:35 -07006826// ----------------------------------------------------------------------------
6827// Effect management
6828// ----------------------------------------------------------------------------
6829
6830
Glenn Kastenf587ba52012-01-26 16:25:10 -08006831status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006832{
6833 Mutex::Autolock _l(mLock);
6834 return EffectQueryNumberEffects(numEffects);
6835}
6836
Glenn Kastenf587ba52012-01-26 16:25:10 -08006837status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006838{
6839 Mutex::Autolock _l(mLock);
6840 return EffectQueryEffect(index, descriptor);
6841}
6842
Glenn Kasten5e92a782012-01-30 07:40:52 -08006843status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08006844 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006845{
6846 Mutex::Autolock _l(mLock);
6847 return EffectGetDescriptor(pUuid, descriptor);
6848}
6849
6850
Mathias Agopian65ab4712010-07-14 17:59:35 -07006851sp<IEffect> AudioFlinger::createEffect(pid_t pid,
6852 effect_descriptor_t *pDesc,
6853 const sp<IEffectClient>& effectClient,
6854 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006855 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006856 int sessionId,
6857 status_t *status,
6858 int *id,
6859 int *enabled)
6860{
6861 status_t lStatus = NO_ERROR;
6862 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006863 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006864
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006865 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006866 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006867
6868 if (pDesc == NULL) {
6869 lStatus = BAD_VALUE;
6870 goto Exit;
6871 }
6872
Eric Laurent84e9a102010-09-23 16:10:16 -07006873 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006874 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006875 lStatus = PERMISSION_DENIED;
6876 goto Exit;
6877 }
6878
Dima Zavinfce7a472011-04-19 22:30:36 -07006879 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07006880 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08006881 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006882 lStatus = PERMISSION_DENIED;
6883 goto Exit;
6884 }
6885
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006886 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006887 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006888 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07006889 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07006890 lStatus = BAD_VALUE;
6891 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07006892 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006893 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006894 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07006895 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006896 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07006897 }
6898 }
6899
Mathias Agopian65ab4712010-07-14 17:59:35 -07006900 {
6901 Mutex::Autolock _l(mLock);
6902
Mathias Agopian65ab4712010-07-14 17:59:35 -07006903
6904 if (!EffectIsNullUuid(&pDesc->uuid)) {
6905 // if uuid is specified, request effect descriptor
6906 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
6907 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006908 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006909 goto Exit;
6910 }
6911 } else {
6912 // if uuid is not specified, look for an available implementation
6913 // of the required type in effect factory
6914 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006915 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006916 lStatus = BAD_VALUE;
6917 goto Exit;
6918 }
6919 uint32_t numEffects = 0;
6920 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006921 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07006922 bool found = false;
6923
6924 lStatus = EffectQueryNumberEffects(&numEffects);
6925 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006926 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006927 goto Exit;
6928 }
6929 for (uint32_t i = 0; i < numEffects; i++) {
6930 lStatus = EffectQueryEffect(i, &desc);
6931 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006932 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006933 continue;
6934 }
6935 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
6936 // If matching type found save effect descriptor. If the session is
6937 // 0 and the effect is not auxiliary, continue enumeration in case
6938 // an auxiliary version of this effect type is available
6939 found = true;
6940 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07006941 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006942 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6943 break;
6944 }
6945 }
6946 }
6947 if (!found) {
6948 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00006949 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006950 goto Exit;
6951 }
6952 // For same effect type, chose auxiliary version over insert version if
6953 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07006954 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006955 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
6956 memcpy(&desc, &d, sizeof(effect_descriptor_t));
6957 }
6958 }
6959
6960 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07006961 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006962 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6963 lStatus = INVALID_OPERATION;
6964 goto Exit;
6965 }
6966
Eric Laurent59255e42011-07-27 19:49:51 -07006967 // check recording permission for visualizer
6968 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
6969 !recordingAllowed()) {
6970 lStatus = PERMISSION_DENIED;
6971 goto Exit;
6972 }
6973
Mathias Agopian65ab4712010-07-14 17:59:35 -07006974 // return effect descriptor
6975 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
6976
6977 // If output is not specified try to find a matching audio session ID in one of the
6978 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07006979 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
6980 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006981 // Note: io is never 0 when creating an effect on an input
6982 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006983 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07006984 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6985 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006986 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07006987 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07006988 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006989 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006990 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006991 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6992 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6993 io = mRecordThreads.keyAt(i);
6994 break;
6995 }
6996 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006997 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006998 // If no output thread contains the requested session ID, default to
6999 // first output. The effect chain will be moved to the correct output
7000 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007001 if (io == 0 && mPlaybackThreads.size()) {
7002 io = mPlaybackThreads.keyAt(0);
7003 }
Steve Block3856b092011-10-20 11:56:00 +01007004 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007005 }
7006 ThreadBase *thread = checkRecordThread_l(io);
7007 if (thread == NULL) {
7008 thread = checkPlaybackThread_l(io);
7009 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007010 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007011 lStatus = BAD_VALUE;
7012 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007013 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007014 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007015
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007016 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007017
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007018 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007019 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7020 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007021 if (handle != 0 && id != NULL) {
7022 *id = handle->id();
7023 }
7024 }
7025
7026Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007027 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007028 *status = lStatus;
7029 }
7030 return handle;
7031}
7032
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007033status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7034 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007035{
Steve Block3856b092011-10-20 11:56:00 +01007036 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007037 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007038 Mutex::Autolock _l(mLock);
7039 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007040 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007041 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007042 }
Eric Laurentde070132010-07-13 04:45:46 -07007043 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7044 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007045 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007046 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007047 }
Eric Laurentde070132010-07-13 04:45:46 -07007048 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7049 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007050 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007051 return BAD_VALUE;
7052 }
7053
7054 Mutex::Autolock _dl(dstThread->mLock);
7055 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007056 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007057
Mathias Agopian65ab4712010-07-14 17:59:35 -07007058 return NO_ERROR;
7059}
7060
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007061// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007062status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007063 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007064 AudioFlinger::PlaybackThread *dstThread,
7065 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007066{
Steve Block3856b092011-10-20 11:56:00 +01007067 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007068 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007069
Eric Laurent59255e42011-07-27 19:49:51 -07007070 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007071 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007072 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007073 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007074 return INVALID_OPERATION;
7075 }
7076
Eric Laurent39e94f82010-07-28 01:32:47 -07007077 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007078 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007079 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007080 // removed.
7081 srcThread->removeEffectChain_l(chain);
7082
7083 // transfer all effects one by one so that new effect chain is created on new thread with
7084 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007085 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007086 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007087 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007088 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7089 while (effect != 0) {
7090 srcThread->removeEffect_l(effect);
7091 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007092 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7093 if (effect->state() == EffectModule::ACTIVE ||
7094 effect->state() == EffectModule::STOPPING) {
7095 effect->start();
7096 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007097 // if the move request is not received from audio policy manager, the effect must be
7098 // re-registered with the new strategy and output
7099 if (dstChain == 0) {
7100 dstChain = effect->chain().promote();
7101 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007102 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007103 srcThread->addEffect_l(effect);
7104 return NO_INIT;
7105 }
7106 strategy = dstChain->strategy();
7107 }
7108 if (reRegister) {
7109 AudioSystem::unregisterEffect(effect->id());
7110 AudioSystem::registerEffect(&effect->desc(),
7111 dstOutput,
7112 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007113 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007114 effect->id());
7115 }
Eric Laurentde070132010-07-13 04:45:46 -07007116 effect = chain->getEffectFromId_l(0);
7117 }
7118
7119 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007120}
7121
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007122
Mathias Agopian65ab4712010-07-14 17:59:35 -07007123// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007124sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007125 const sp<AudioFlinger::Client>& client,
7126 const sp<IEffectClient>& effectClient,
7127 int32_t priority,
7128 int sessionId,
7129 effect_descriptor_t *desc,
7130 int *enabled,
7131 status_t *status
7132 )
7133{
7134 sp<EffectModule> effect;
7135 sp<EffectHandle> handle;
7136 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007137 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007138 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007139 bool effectCreated = false;
7140 bool effectRegistered = false;
7141
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007142 lStatus = initCheck();
7143 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007144 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007145 goto Exit;
7146 }
7147
7148 // Do not allow effects with session ID 0 on direct output or duplicating threads
7149 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007150 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007151 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007152 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007153 lStatus = BAD_VALUE;
7154 goto Exit;
7155 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007156 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007157 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007158 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007159 desc->name, desc->flags, mType);
7160 lStatus = BAD_VALUE;
7161 goto Exit;
7162 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007163
Steve Block3856b092011-10-20 11:56:00 +01007164 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007165
7166 { // scope for mLock
7167 Mutex::Autolock _l(mLock);
7168
7169 // check for existing effect chain with the requested audio session
7170 chain = getEffectChain_l(sessionId);
7171 if (chain == 0) {
7172 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007173 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007174 chain = new EffectChain(this, sessionId);
7175 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007176 chain->setStrategy(getStrategyForSession_l(sessionId));
7177 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007178 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007179 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007180 }
7181
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007182 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007183
7184 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007185 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007186 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007187 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007188 if (lStatus != NO_ERROR) {
7189 goto Exit;
7190 }
7191 effectRegistered = true;
7192 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007193 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007194 lStatus = effect->status();
7195 if (lStatus != NO_ERROR) {
7196 goto Exit;
7197 }
Eric Laurentcab11242010-07-15 12:50:15 -07007198 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007199 if (lStatus != NO_ERROR) {
7200 goto Exit;
7201 }
7202 effectCreated = true;
7203
7204 effect->setDevice(mDevice);
7205 effect->setMode(mAudioFlinger->getMode());
7206 }
7207 // create effect handle and connect it to effect module
7208 handle = new EffectHandle(effect, client, effectClient, priority);
7209 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08007210 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007211 *enabled = (int)effect->isEnabled();
7212 }
7213 }
7214
7215Exit:
7216 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007217 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007218 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007219 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007220 }
7221 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007222 AudioSystem::unregisterEffect(effect->id());
7223 }
7224 if (chainCreated) {
7225 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007226 }
7227 handle.clear();
7228 }
7229
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007230 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007231 *status = lStatus;
7232 }
7233 return handle;
7234}
7235
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007236sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7237{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007238 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007239 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007240}
7241
Eric Laurentde070132010-07-13 04:45:46 -07007242// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7243// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007244status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007245{
7246 // check for existing effect chain with the requested audio session
7247 int sessionId = effect->sessionId();
7248 sp<EffectChain> chain = getEffectChain_l(sessionId);
7249 bool chainCreated = false;
7250
7251 if (chain == 0) {
7252 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007253 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007254 chain = new EffectChain(this, sessionId);
7255 addEffectChain_l(chain);
7256 chain->setStrategy(getStrategyForSession_l(sessionId));
7257 chainCreated = true;
7258 }
Steve Block3856b092011-10-20 11:56:00 +01007259 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007260
7261 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007262 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007263 this, effect->desc().name, chain.get());
7264 return BAD_VALUE;
7265 }
7266
7267 status_t status = chain->addEffect_l(effect);
7268 if (status != NO_ERROR) {
7269 if (chainCreated) {
7270 removeEffectChain_l(chain);
7271 }
7272 return status;
7273 }
7274
7275 effect->setDevice(mDevice);
7276 effect->setMode(mAudioFlinger->getMode());
7277 return NO_ERROR;
7278}
7279
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007280void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007281
Steve Block3856b092011-10-20 11:56:00 +01007282 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007283 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007284 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7285 detachAuxEffect_l(effect->id());
7286 }
7287
7288 sp<EffectChain> chain = effect->chain().promote();
7289 if (chain != 0) {
7290 // remove effect chain if removing last effect
7291 if (chain->removeEffect_l(effect) == 0) {
7292 removeEffectChain_l(chain);
7293 }
7294 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007295 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007296 }
7297}
7298
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007299void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007300 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007301{
7302 effectChains = mEffectChains;
7303 for (size_t i = 0; i < mEffectChains.size(); i++) {
7304 mEffectChains[i]->lock();
7305 }
7306}
7307
7308void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007309 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007310{
7311 for (size_t i = 0; i < effectChains.size(); i++) {
7312 effectChains[i]->unlock();
7313 }
7314}
7315
7316sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7317{
7318 Mutex::Autolock _l(mLock);
7319 return getEffectChain_l(sessionId);
7320}
7321
7322sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7323{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007324 size_t size = mEffectChains.size();
7325 for (size_t i = 0; i < size; i++) {
7326 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007327 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007328 }
7329 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007330 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007331}
7332
Glenn Kastenf78aee72012-01-04 11:00:47 -08007333void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007334{
7335 Mutex::Autolock _l(mLock);
7336 size_t size = mEffectChains.size();
7337 for (size_t i = 0; i < size; i++) {
7338 mEffectChains[i]->setMode_l(mode);
7339 }
7340}
7341
7342void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007343 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007344 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007345
Mathias Agopian65ab4712010-07-14 17:59:35 -07007346 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007347 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007348 // delete the effect module if removing last handle on it
7349 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007350 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007351 removeEffect_l(effect);
7352 AudioSystem::unregisterEffect(effect->id());
7353 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007354 }
7355}
7356
7357status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7358{
7359 int session = chain->sessionId();
7360 int16_t *buffer = mMixBuffer;
7361 bool ownsBuffer = false;
7362
Steve Block3856b092011-10-20 11:56:00 +01007363 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007364 if (session > 0) {
7365 // Only one effect chain can be present in direct output thread and it uses
7366 // the mix buffer as input
7367 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007368 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007369 buffer = new int16_t[numSamples];
7370 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007371 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007372 ownsBuffer = true;
7373 }
7374
7375 // Attach all tracks with same session ID to this chain.
7376 for (size_t i = 0; i < mTracks.size(); ++i) {
7377 sp<Track> track = mTracks[i];
7378 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007379 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007380 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007381 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007382 }
7383 }
7384
7385 // indicate all active tracks in the chain
7386 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7387 sp<Track> track = mActiveTracks[i].promote();
7388 if (track == 0) continue;
7389 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007390 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007391 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007392 }
7393 }
7394 }
7395
7396 chain->setInBuffer(buffer, ownsBuffer);
7397 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007398 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007399 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007400 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7401 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007402 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007403 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7404 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007405 // Effect chain for other sessions are inserted at beginning of effect
7406 // chains list to be processed before output mix effects. Relative order between other
7407 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007408 size_t size = mEffectChains.size();
7409 size_t i = 0;
7410 for (i = 0; i < size; i++) {
7411 if (mEffectChains[i]->sessionId() < session) break;
7412 }
7413 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007414 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007415
7416 return NO_ERROR;
7417}
7418
7419size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7420{
7421 int session = chain->sessionId();
7422
Steve Block3856b092011-10-20 11:56:00 +01007423 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007424
7425 for (size_t i = 0; i < mEffectChains.size(); i++) {
7426 if (chain == mEffectChains[i]) {
7427 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007428 // detach all active tracks from the chain
7429 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7430 sp<Track> track = mActiveTracks[i].promote();
7431 if (track == 0) continue;
7432 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007433 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007434 chain.get(), session);
7435 chain->decActiveTrackCnt();
7436 }
7437 }
7438
Mathias Agopian65ab4712010-07-14 17:59:35 -07007439 // detach all tracks with same session ID from this chain
7440 for (size_t i = 0; i < mTracks.size(); ++i) {
7441 sp<Track> track = mTracks[i];
7442 if (session == track->sessionId()) {
7443 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007444 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007445 }
7446 }
Eric Laurentde070132010-07-13 04:45:46 -07007447 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007448 }
7449 }
7450 return mEffectChains.size();
7451}
7452
Eric Laurentde070132010-07-13 04:45:46 -07007453status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7454 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007455{
7456 Mutex::Autolock _l(mLock);
7457 return attachAuxEffect_l(track, EffectId);
7458}
7459
Eric Laurentde070132010-07-13 04:45:46 -07007460status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7461 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007462{
7463 status_t status = NO_ERROR;
7464
7465 if (EffectId == 0) {
7466 track->setAuxBuffer(0, NULL);
7467 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007468 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7469 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007470 if (effect != 0) {
7471 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7472 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7473 } else {
7474 status = INVALID_OPERATION;
7475 }
7476 } else {
7477 status = BAD_VALUE;
7478 }
7479 }
7480 return status;
7481}
7482
7483void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7484{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007485 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007486 sp<Track> track = mTracks[i];
7487 if (track->auxEffectId() == effectId) {
7488 attachAuxEffect_l(track, 0);
7489 }
7490 }
7491}
7492
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007493status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7494{
7495 // only one chain per input thread
7496 if (mEffectChains.size() != 0) {
7497 return INVALID_OPERATION;
7498 }
Steve Block3856b092011-10-20 11:56:00 +01007499 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007500
7501 chain->setInBuffer(NULL);
7502 chain->setOutBuffer(NULL);
7503
Eric Laurent59255e42011-07-27 19:49:51 -07007504 checkSuspendOnAddEffectChain_l(chain);
7505
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007506 mEffectChains.add(chain);
7507
7508 return NO_ERROR;
7509}
7510
7511size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7512{
Steve Block3856b092011-10-20 11:56:00 +01007513 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007514 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007515 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7516 chain.get(), mEffectChains.size(), this);
7517 if (mEffectChains.size() == 1) {
7518 mEffectChains.removeAt(0);
7519 }
7520 return 0;
7521}
7522
Mathias Agopian65ab4712010-07-14 17:59:35 -07007523// ----------------------------------------------------------------------------
7524// EffectModule implementation
7525// ----------------------------------------------------------------------------
7526
7527#undef LOG_TAG
7528#define LOG_TAG "AudioFlinger::EffectModule"
7529
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007530AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007531 const wp<AudioFlinger::EffectChain>& chain,
7532 effect_descriptor_t *desc,
7533 int id,
7534 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007535 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007536 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007537{
Steve Block3856b092011-10-20 11:56:00 +01007538 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007539 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007540 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007541 return;
7542 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007543
7544 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7545
7546 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007547 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007548
7549 if (mStatus != NO_ERROR) {
7550 return;
7551 }
7552 lStatus = init();
7553 if (lStatus < 0) {
7554 mStatus = lStatus;
7555 goto Error;
7556 }
7557
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007558 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
7559 mPinned = true;
7560 }
Steve Block3856b092011-10-20 11:56:00 +01007561 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007562 return;
7563Error:
7564 EffectRelease(mEffectInterface);
7565 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007566 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007567}
7568
7569AudioFlinger::EffectModule::~EffectModule()
7570{
Steve Block3856b092011-10-20 11:56:00 +01007571 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007572 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007573 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7574 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7575 sp<ThreadBase> thread = mThread.promote();
7576 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007577 audio_stream_t *stream = thread->stream();
7578 if (stream != NULL) {
7579 stream->remove_audio_effect(stream, mEffectInterface);
7580 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007581 }
7582 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007583 // release effect engine
7584 EffectRelease(mEffectInterface);
7585 }
7586}
7587
Glenn Kasten435dbe62012-01-30 10:15:48 -08007588status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007589{
7590 status_t status;
7591
7592 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007593 int priority = handle->priority();
7594 size_t size = mHandles.size();
7595 sp<EffectHandle> h;
7596 size_t i;
7597 for (i = 0; i < size; i++) {
7598 h = mHandles[i].promote();
7599 if (h == 0) continue;
7600 if (h->priority() <= priority) break;
7601 }
7602 // if inserted in first place, move effect control from previous owner to this handle
7603 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007604 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007605 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007606 enabled = h->enabled();
7607 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007608 }
Eric Laurent59255e42011-07-27 19:49:51 -07007609 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007610 status = NO_ERROR;
7611 } else {
7612 status = ALREADY_EXISTS;
7613 }
Steve Block3856b092011-10-20 11:56:00 +01007614 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007615 mHandles.insertAt(handle, i);
7616 return status;
7617}
7618
7619size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
7620{
7621 Mutex::Autolock _l(mLock);
7622 size_t size = mHandles.size();
7623 size_t i;
7624 for (i = 0; i < size; i++) {
7625 if (mHandles[i] == handle) break;
7626 }
7627 if (i == size) {
7628 return size;
7629 }
Steve Block3856b092011-10-20 11:56:00 +01007630 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07007631
7632 bool enabled = false;
7633 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08007634 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01007635 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07007636 enabled = hdl->enabled();
7637 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007638 mHandles.removeAt(i);
7639 size = mHandles.size();
7640 // if removed from first place, move effect control from this handle to next in line
7641 if (i == 0 && size != 0) {
7642 sp<EffectHandle> h = mHandles[0].promote();
7643 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007644 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007645 }
7646 }
7647
Eric Laurentec437d82011-07-26 20:54:46 -07007648 // Prevent calls to process() and other functions on effect interface from now on.
7649 // The effect engine will be released by the destructor when the last strong reference on
7650 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007651 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07007652 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07007653 }
7654
Mathias Agopian65ab4712010-07-14 17:59:35 -07007655 return size;
7656}
7657
Eric Laurent59255e42011-07-27 19:49:51 -07007658sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
7659{
7660 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08007661 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007662}
7663
Glenn Kasten58123c32012-02-03 10:32:24 -08007664void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007665{
Glenn Kasten90bebef2012-01-27 15:24:38 -08007666 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007667 // keep a strong reference on this EffectModule to avoid calling the
7668 // destructor before we exit
7669 sp<EffectModule> keep(this);
7670 {
7671 sp<ThreadBase> thread = mThread.promote();
7672 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007673 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007674 }
7675 }
7676}
7677
7678void AudioFlinger::EffectModule::updateState() {
7679 Mutex::Autolock _l(mLock);
7680
7681 switch (mState) {
7682 case RESTART:
7683 reset_l();
7684 // FALL THROUGH
7685
7686 case STARTING:
7687 // clear auxiliary effect input buffer for next accumulation
7688 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7689 memset(mConfig.inputCfg.buffer.raw,
7690 0,
7691 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
7692 }
7693 start_l();
7694 mState = ACTIVE;
7695 break;
7696 case STOPPING:
7697 stop_l();
7698 mDisableWaitCnt = mMaxDisableWaitCnt;
7699 mState = STOPPED;
7700 break;
7701 case STOPPED:
7702 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
7703 // turn off sequence.
7704 if (--mDisableWaitCnt == 0) {
7705 reset_l();
7706 mState = IDLE;
7707 }
7708 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007709 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07007710 break;
7711 }
7712}
7713
7714void AudioFlinger::EffectModule::process()
7715{
7716 Mutex::Autolock _l(mLock);
7717
Eric Laurentec437d82011-07-26 20:54:46 -07007718 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007719 mConfig.inputCfg.buffer.raw == NULL ||
7720 mConfig.outputCfg.buffer.raw == NULL) {
7721 return;
7722 }
7723
Eric Laurent8f45bd72010-08-31 13:50:07 -07007724 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007725 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
7726 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08007727 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007728 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07007729 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007730 }
7731
7732 // do the actual processing in the effect engine
7733 int ret = (*mEffectInterface)->process(mEffectInterface,
7734 &mConfig.inputCfg.buffer,
7735 &mConfig.outputCfg.buffer);
7736
7737 // force transition to IDLE state when engine is ready
7738 if (mState == STOPPED && ret == -ENODATA) {
7739 mDisableWaitCnt = 1;
7740 }
7741
7742 // clear auxiliary effect input buffer for next accumulation
7743 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08007744 memset(mConfig.inputCfg.buffer.raw, 0,
7745 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007746 }
7747 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08007748 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7749 // If an insert effect is idle and input buffer is different from output buffer,
7750 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07007751 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07007752 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08007753 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
7754 int16_t *in = mConfig.inputCfg.buffer.s16;
7755 int16_t *out = mConfig.outputCfg.buffer.s16;
7756 for (size_t i = 0; i < frameCnt; i++) {
7757 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007758 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007759 }
7760 }
7761}
7762
7763void AudioFlinger::EffectModule::reset_l()
7764{
7765 if (mEffectInterface == NULL) {
7766 return;
7767 }
7768 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
7769}
7770
7771status_t AudioFlinger::EffectModule::configure()
7772{
7773 uint32_t channels;
7774 if (mEffectInterface == NULL) {
7775 return NO_INIT;
7776 }
7777
7778 sp<ThreadBase> thread = mThread.promote();
7779 if (thread == 0) {
7780 return DEAD_OBJECT;
7781 }
7782
7783 // TODO: handle configuration of effects replacing track process
7784 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007785 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007786 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07007787 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007788 }
7789
7790 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007791 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007792 } else {
7793 mConfig.inputCfg.channels = channels;
7794 }
7795 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07007796 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
7797 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007798 mConfig.inputCfg.samplingRate = thread->sampleRate();
7799 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
7800 mConfig.inputCfg.bufferProvider.cookie = NULL;
7801 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
7802 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
7803 mConfig.outputCfg.bufferProvider.cookie = NULL;
7804 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
7805 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
7806 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
7807 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07007808 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07007809 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07007810 // - in other sessions:
7811 // last effect in the chain accumulates in output buffer: input buffer != output buffer
7812 // other effect: overwrites output buffer: input buffer == output buffer
7813 // Auxiliary effect:
7814 // accumulates in output buffer: input buffer != output buffer
7815 // Therefore: accumulate <=> input buffer != output buffer
7816 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7817 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
7818 } else {
7819 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
7820 }
7821 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
7822 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
7823 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
7824 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
7825
Steve Block3856b092011-10-20 11:56:00 +01007826 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07007827 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
7828
Mathias Agopian65ab4712010-07-14 17:59:35 -07007829 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007830 uint32_t size = sizeof(int);
7831 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08007832 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07007833 sizeof(effect_config_t),
7834 &mConfig,
7835 &size,
7836 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007837 if (status == 0) {
7838 status = cmdStatus;
7839 }
7840
7841 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
7842 (1000 * mConfig.outputCfg.buffer.frameCount);
7843
7844 return status;
7845}
7846
7847status_t AudioFlinger::EffectModule::init()
7848{
7849 Mutex::Autolock _l(mLock);
7850 if (mEffectInterface == NULL) {
7851 return NO_INIT;
7852 }
7853 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007854 uint32_t size = sizeof(status_t);
7855 status_t status = (*mEffectInterface)->command(mEffectInterface,
7856 EFFECT_CMD_INIT,
7857 0,
7858 NULL,
7859 &size,
7860 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007861 if (status == 0) {
7862 status = cmdStatus;
7863 }
7864 return status;
7865}
7866
Eric Laurentec35a142011-10-05 17:42:25 -07007867status_t AudioFlinger::EffectModule::start()
7868{
7869 Mutex::Autolock _l(mLock);
7870 return start_l();
7871}
7872
Mathias Agopian65ab4712010-07-14 17:59:35 -07007873status_t AudioFlinger::EffectModule::start_l()
7874{
7875 if (mEffectInterface == NULL) {
7876 return NO_INIT;
7877 }
7878 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007879 uint32_t size = sizeof(status_t);
7880 status_t status = (*mEffectInterface)->command(mEffectInterface,
7881 EFFECT_CMD_ENABLE,
7882 0,
7883 NULL,
7884 &size,
7885 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007886 if (status == 0) {
7887 status = cmdStatus;
7888 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007889 if (status == 0 &&
7890 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7891 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7892 sp<ThreadBase> thread = mThread.promote();
7893 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007894 audio_stream_t *stream = thread->stream();
7895 if (stream != NULL) {
7896 stream->add_audio_effect(stream, mEffectInterface);
7897 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007898 }
7899 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007900 return status;
7901}
7902
Eric Laurentec437d82011-07-26 20:54:46 -07007903status_t AudioFlinger::EffectModule::stop()
7904{
7905 Mutex::Autolock _l(mLock);
7906 return stop_l();
7907}
7908
Mathias Agopian65ab4712010-07-14 17:59:35 -07007909status_t AudioFlinger::EffectModule::stop_l()
7910{
7911 if (mEffectInterface == NULL) {
7912 return NO_INIT;
7913 }
7914 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007915 uint32_t size = sizeof(status_t);
7916 status_t status = (*mEffectInterface)->command(mEffectInterface,
7917 EFFECT_CMD_DISABLE,
7918 0,
7919 NULL,
7920 &size,
7921 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007922 if (status == 0) {
7923 status = cmdStatus;
7924 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007925 if (status == 0 &&
7926 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7927 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7928 sp<ThreadBase> thread = mThread.promote();
7929 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007930 audio_stream_t *stream = thread->stream();
7931 if (stream != NULL) {
7932 stream->remove_audio_effect(stream, mEffectInterface);
7933 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007934 }
7935 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007936 return status;
7937}
7938
Eric Laurent25f43952010-07-28 05:40:18 -07007939status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
7940 uint32_t cmdSize,
7941 void *pCmdData,
7942 uint32_t *replySize,
7943 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007944{
7945 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007946// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007947
Eric Laurentec437d82011-07-26 20:54:46 -07007948 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007949 return NO_INIT;
7950 }
Eric Laurent25f43952010-07-28 05:40:18 -07007951 status_t status = (*mEffectInterface)->command(mEffectInterface,
7952 cmdCode,
7953 cmdSize,
7954 pCmdData,
7955 replySize,
7956 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007957 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07007958 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007959 for (size_t i = 1; i < mHandles.size(); i++) {
7960 sp<EffectHandle> h = mHandles[i].promote();
7961 if (h != 0) {
7962 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
7963 }
7964 }
7965 }
7966 return status;
7967}
7968
7969status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
7970{
Eric Laurentdb7c0792011-08-10 10:37:50 -07007971
Mathias Agopian65ab4712010-07-14 17:59:35 -07007972 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007973 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007974
7975 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007976 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
7977 if (enabled && status != NO_ERROR) {
7978 return status;
7979 }
7980
Mathias Agopian65ab4712010-07-14 17:59:35 -07007981 switch (mState) {
7982 // going from disabled to enabled
7983 case IDLE:
7984 mState = STARTING;
7985 break;
7986 case STOPPED:
7987 mState = RESTART;
7988 break;
7989 case STOPPING:
7990 mState = ACTIVE;
7991 break;
7992
7993 // going from enabled to disabled
7994 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007995 mState = STOPPED;
7996 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007997 case STARTING:
7998 mState = IDLE;
7999 break;
8000 case ACTIVE:
8001 mState = STOPPING;
8002 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008003 case DESTROYED:
8004 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008005 }
8006 for (size_t i = 1; i < mHandles.size(); i++) {
8007 sp<EffectHandle> h = mHandles[i].promote();
8008 if (h != 0) {
8009 h->setEnabled(enabled);
8010 }
8011 }
8012 }
8013 return NO_ERROR;
8014}
8015
Glenn Kastenc59c0042012-02-02 14:06:11 -08008016bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008017{
8018 switch (mState) {
8019 case RESTART:
8020 case STARTING:
8021 case ACTIVE:
8022 return true;
8023 case IDLE:
8024 case STOPPING:
8025 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008026 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008027 default:
8028 return false;
8029 }
8030}
8031
Glenn Kastenc59c0042012-02-02 14:06:11 -08008032bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008033{
8034 switch (mState) {
8035 case RESTART:
8036 case ACTIVE:
8037 case STOPPING:
8038 case STOPPED:
8039 return true;
8040 case IDLE:
8041 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008042 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008043 default:
8044 return false;
8045 }
8046}
8047
Mathias Agopian65ab4712010-07-14 17:59:35 -07008048status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8049{
8050 Mutex::Autolock _l(mLock);
8051 status_t status = NO_ERROR;
8052
8053 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8054 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008055 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008056 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8057 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008058 status_t cmdStatus;
8059 uint32_t volume[2];
8060 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008061 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008062 volume[0] = *left;
8063 volume[1] = *right;
8064 if (controller) {
8065 pVolume = volume;
8066 }
Eric Laurent25f43952010-07-28 05:40:18 -07008067 status = (*mEffectInterface)->command(mEffectInterface,
8068 EFFECT_CMD_SET_VOLUME,
8069 size,
8070 volume,
8071 &size,
8072 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008073 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8074 *left = volume[0];
8075 *right = volume[1];
8076 }
8077 }
8078 return status;
8079}
8080
8081status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8082{
8083 Mutex::Autolock _l(mLock);
8084 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008085 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8086 // audio pre processing modules on RecordThread can receive both output and
8087 // input device indication in the same call
8088 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8089 if (dev) {
8090 status_t cmdStatus;
8091 uint32_t size = sizeof(status_t);
8092
8093 status = (*mEffectInterface)->command(mEffectInterface,
8094 EFFECT_CMD_SET_DEVICE,
8095 sizeof(uint32_t),
8096 &dev,
8097 &size,
8098 &cmdStatus);
8099 if (status == NO_ERROR) {
8100 status = cmdStatus;
8101 }
8102 }
8103 dev = device & AUDIO_DEVICE_IN_ALL;
8104 if (dev) {
8105 status_t cmdStatus;
8106 uint32_t size = sizeof(status_t);
8107
8108 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8109 EFFECT_CMD_SET_INPUT_DEVICE,
8110 sizeof(uint32_t),
8111 &dev,
8112 &size,
8113 &cmdStatus);
8114 if (status2 == NO_ERROR) {
8115 status2 = cmdStatus;
8116 }
8117 if (status == NO_ERROR) {
8118 status = status2;
8119 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008120 }
8121 }
8122 return status;
8123}
8124
Glenn Kastenf78aee72012-01-04 11:00:47 -08008125status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008126{
8127 Mutex::Autolock _l(mLock);
8128 status_t status = NO_ERROR;
8129 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008130 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008131 uint32_t size = sizeof(status_t);
8132 status = (*mEffectInterface)->command(mEffectInterface,
8133 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008134 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008135 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008136 &size,
8137 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008138 if (status == NO_ERROR) {
8139 status = cmdStatus;
8140 }
8141 }
8142 return status;
8143}
8144
Eric Laurent59255e42011-07-27 19:49:51 -07008145void AudioFlinger::EffectModule::setSuspended(bool suspended)
8146{
8147 Mutex::Autolock _l(mLock);
8148 mSuspended = suspended;
8149}
Glenn Kastena3a85482012-01-04 11:01:11 -08008150
8151bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008152{
8153 Mutex::Autolock _l(mLock);
8154 return mSuspended;
8155}
8156
Mathias Agopian65ab4712010-07-14 17:59:35 -07008157status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8158{
8159 const size_t SIZE = 256;
8160 char buffer[SIZE];
8161 String8 result;
8162
8163 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8164 result.append(buffer);
8165
8166 bool locked = tryLock(mLock);
8167 // failed to lock - AudioFlinger is probably deadlocked
8168 if (!locked) {
8169 result.append("\t\tCould not lock Fx mutex:\n");
8170 }
8171
8172 result.append("\t\tSession Status State Engine:\n");
8173 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8174 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8175 result.append(buffer);
8176
8177 result.append("\t\tDescriptor:\n");
8178 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8179 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8180 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8181 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8182 result.append(buffer);
8183 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8184 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8185 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8186 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8187 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008188 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008189 mDescriptor.apiVersion,
8190 mDescriptor.flags);
8191 result.append(buffer);
8192 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8193 mDescriptor.name);
8194 result.append(buffer);
8195 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8196 mDescriptor.implementor);
8197 result.append(buffer);
8198
8199 result.append("\t\t- Input configuration:\n");
8200 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8201 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8202 (uint32_t)mConfig.inputCfg.buffer.raw,
8203 mConfig.inputCfg.buffer.frameCount,
8204 mConfig.inputCfg.samplingRate,
8205 mConfig.inputCfg.channels,
8206 mConfig.inputCfg.format);
8207 result.append(buffer);
8208
8209 result.append("\t\t- Output configuration:\n");
8210 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8211 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8212 (uint32_t)mConfig.outputCfg.buffer.raw,
8213 mConfig.outputCfg.buffer.frameCount,
8214 mConfig.outputCfg.samplingRate,
8215 mConfig.outputCfg.channels,
8216 mConfig.outputCfg.format);
8217 result.append(buffer);
8218
8219 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8220 result.append(buffer);
8221 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8222 for (size_t i = 0; i < mHandles.size(); ++i) {
8223 sp<EffectHandle> handle = mHandles[i].promote();
8224 if (handle != 0) {
8225 handle->dump(buffer, SIZE);
8226 result.append(buffer);
8227 }
8228 }
8229
8230 result.append("\n");
8231
8232 write(fd, result.string(), result.length());
8233
8234 if (locked) {
8235 mLock.unlock();
8236 }
8237
8238 return NO_ERROR;
8239}
8240
8241// ----------------------------------------------------------------------------
8242// EffectHandle implementation
8243// ----------------------------------------------------------------------------
8244
8245#undef LOG_TAG
8246#define LOG_TAG "AudioFlinger::EffectHandle"
8247
8248AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8249 const sp<AudioFlinger::Client>& client,
8250 const sp<IEffectClient>& effectClient,
8251 int32_t priority)
8252 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008253 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07008254 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008255{
Steve Block3856b092011-10-20 11:56:00 +01008256 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008257
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008258 if (client == 0) {
8259 return;
8260 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008261 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8262 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8263 if (mCblkMemory != 0) {
8264 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8265
Glenn Kastena0d68332012-01-27 16:47:15 -08008266 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008267 new(mCblk) effect_param_cblk_t();
8268 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008269 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008270 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008271 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008272 return;
8273 }
8274}
8275
8276AudioFlinger::EffectHandle::~EffectHandle()
8277{
Steve Block3856b092011-10-20 11:56:00 +01008278 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008279 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01008280 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008281}
8282
8283status_t AudioFlinger::EffectHandle::enable()
8284{
Steve Block3856b092011-10-20 11:56:00 +01008285 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008286 if (!mHasControl) return INVALID_OPERATION;
8287 if (mEffect == 0) return DEAD_OBJECT;
8288
Eric Laurentdb7c0792011-08-10 10:37:50 -07008289 if (mEnabled) {
8290 return NO_ERROR;
8291 }
8292
Eric Laurent59255e42011-07-27 19:49:51 -07008293 mEnabled = true;
8294
8295 sp<ThreadBase> thread = mEffect->thread().promote();
8296 if (thread != 0) {
8297 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8298 }
8299
8300 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8301 if (mEffect->suspended()) {
8302 return NO_ERROR;
8303 }
8304
Eric Laurentdb7c0792011-08-10 10:37:50 -07008305 status_t status = mEffect->setEnabled(true);
8306 if (status != NO_ERROR) {
8307 if (thread != 0) {
8308 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8309 }
8310 mEnabled = false;
8311 }
8312 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008313}
8314
8315status_t AudioFlinger::EffectHandle::disable()
8316{
Steve Block3856b092011-10-20 11:56:00 +01008317 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008318 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008319 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008320
Eric Laurentdb7c0792011-08-10 10:37:50 -07008321 if (!mEnabled) {
8322 return NO_ERROR;
8323 }
Eric Laurent59255e42011-07-27 19:49:51 -07008324 mEnabled = false;
8325
8326 if (mEffect->suspended()) {
8327 return NO_ERROR;
8328 }
8329
8330 status_t status = mEffect->setEnabled(false);
8331
8332 sp<ThreadBase> thread = mEffect->thread().promote();
8333 if (thread != 0) {
8334 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8335 }
8336
8337 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008338}
8339
8340void AudioFlinger::EffectHandle::disconnect()
8341{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008342 disconnect(true);
8343}
8344
Glenn Kasten58123c32012-02-03 10:32:24 -08008345void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008346{
Glenn Kasten58123c32012-02-03 10:32:24 -08008347 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008348 if (mEffect == 0) {
8349 return;
8350 }
Glenn Kasten58123c32012-02-03 10:32:24 -08008351 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07008352
Eric Laurenta85a74a2011-10-19 11:44:54 -07008353 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008354 sp<ThreadBase> thread = mEffect->thread().promote();
8355 if (thread != 0) {
8356 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8357 }
Eric Laurent59255e42011-07-27 19:49:51 -07008358 }
8359
Mathias Agopian65ab4712010-07-14 17:59:35 -07008360 // release sp on module => module destructor can be called now
8361 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008362 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008363 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008364 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008365 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8366 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008367 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008368 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008369 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8370 mClient.clear();
8371 }
8372}
8373
Eric Laurent25f43952010-07-28 05:40:18 -07008374status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8375 uint32_t cmdSize,
8376 void *pCmdData,
8377 uint32_t *replySize,
8378 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008379{
Steve Block3856b092011-10-20 11:56:00 +01008380// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008381// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008382
8383 // only get parameter command is permitted for applications not controlling the effect
8384 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8385 return INVALID_OPERATION;
8386 }
8387 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008388 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008389
8390 // handle commands that are not forwarded transparently to effect engine
8391 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8392 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8393 // no risk to block the whole media server process or mixer threads is we are stuck here
8394 Mutex::Autolock _l(mCblk->lock);
8395 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8396 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8397 mCblk->serverIndex = 0;
8398 mCblk->clientIndex = 0;
8399 return BAD_VALUE;
8400 }
8401 status_t status = NO_ERROR;
8402 while (mCblk->serverIndex < mCblk->clientIndex) {
8403 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008404 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008405 int *p = (int *)(mBuffer + mCblk->serverIndex);
8406 int size = *p++;
8407 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008408 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008409 break;
8410 }
8411 effect_param_t *param = (effect_param_t *)p;
8412 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008413 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008414 mCblk->serverIndex += size;
8415 continue;
8416 }
Eric Laurent25f43952010-07-28 05:40:18 -07008417 uint32_t psize = sizeof(effect_param_t) +
8418 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8419 param->vsize;
8420 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8421 psize,
8422 p,
8423 &rsize,
8424 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008425 // stop at first error encountered
8426 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008427 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008428 *(int *)pReplyData = reply;
8429 break;
8430 } else if (reply != NO_ERROR) {
8431 *(int *)pReplyData = reply;
8432 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008433 }
8434 mCblk->serverIndex += size;
8435 }
8436 mCblk->serverIndex = 0;
8437 mCblk->clientIndex = 0;
8438 return status;
8439 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008440 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008441 return enable();
8442 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008443 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008444 return disable();
8445 }
8446
8447 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8448}
8449
Eric Laurent59255e42011-07-27 19:49:51 -07008450void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008451{
Steve Block3856b092011-10-20 11:56:00 +01008452 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008453
8454 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008455 mEnabled = enabled;
8456
Mathias Agopian65ab4712010-07-14 17:59:35 -07008457 if (signal && mEffectClient != 0) {
8458 mEffectClient->controlStatusChanged(hasControl);
8459 }
8460}
8461
Eric Laurent25f43952010-07-28 05:40:18 -07008462void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8463 uint32_t cmdSize,
8464 void *pCmdData,
8465 uint32_t replySize,
8466 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008467{
8468 if (mEffectClient != 0) {
8469 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8470 }
8471}
8472
8473
8474
8475void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8476{
8477 if (mEffectClient != 0) {
8478 mEffectClient->enableStatusChanged(enabled);
8479 }
8480}
8481
8482status_t AudioFlinger::EffectHandle::onTransact(
8483 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8484{
8485 return BnEffect::onTransact(code, data, reply, flags);
8486}
8487
8488
8489void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8490{
Glenn Kastena0d68332012-01-27 16:47:15 -08008491 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008492
8493 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008494 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008495 mPriority,
8496 mHasControl,
8497 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008498 mCblk ? mCblk->clientIndex : 0,
8499 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008500 );
8501
8502 if (locked) {
8503 mCblk->lock.unlock();
8504 }
8505}
8506
8507#undef LOG_TAG
8508#define LOG_TAG "AudioFlinger::EffectChain"
8509
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008510AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008511 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008512 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008513 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8514 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008515{
Dima Zavinfce7a472011-04-19 22:30:36 -07008516 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008517 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008518 return;
8519 }
8520 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8521 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008522}
8523
8524AudioFlinger::EffectChain::~EffectChain()
8525{
8526 if (mOwnInBuffer) {
8527 delete mInBuffer;
8528 }
8529
8530}
8531
Eric Laurent59255e42011-07-27 19:49:51 -07008532// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008533sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008534{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008535 size_t size = mEffects.size();
8536
8537 for (size_t i = 0; i < size; i++) {
8538 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008539 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008540 }
8541 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008542 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008543}
8544
Eric Laurent59255e42011-07-27 19:49:51 -07008545// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008546sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008547{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008548 size_t size = mEffects.size();
8549
8550 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07008551 // by convention, return first effect if id provided is 0 (0 is never a valid id)
8552 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008553 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008554 }
8555 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008556 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008557}
8558
Eric Laurent59255e42011-07-27 19:49:51 -07008559// getEffectFromType_l() must be called with ThreadBase::mLock held
8560sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
8561 const effect_uuid_t *type)
8562{
Eric Laurent59255e42011-07-27 19:49:51 -07008563 size_t size = mEffects.size();
8564
8565 for (size_t i = 0; i < size; i++) {
8566 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008567 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07008568 }
8569 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008570 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008571}
8572
Mathias Agopian65ab4712010-07-14 17:59:35 -07008573// Must be called with EffectChain::mLock locked
8574void AudioFlinger::EffectChain::process_l()
8575{
Eric Laurentdac69112010-09-28 14:09:57 -07008576 sp<ThreadBase> thread = mThread.promote();
8577 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008578 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07008579 return;
8580 }
Dima Zavinfce7a472011-04-19 22:30:36 -07008581 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
8582 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08008583 // always process effects unless no more tracks are on the session and the effect tail
8584 // has been rendered
8585 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07008586 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008587 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07008588
Eric Laurent544fe9b2011-11-11 15:42:52 -08008589 if (!tracksOnSession && mTailBufferCount == 0) {
8590 doProcess = false;
8591 }
8592
8593 if (activeTrackCnt() == 0) {
8594 // if no track is active and the effect tail has not been rendered,
8595 // the input buffer must be cleared here as the mixer process will not do it
8596 if (tracksOnSession || mTailBufferCount > 0) {
8597 size_t numSamples = thread->frameCount() * thread->channelCount();
8598 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
8599 if (mTailBufferCount > 0) {
8600 mTailBufferCount--;
8601 }
8602 }
8603 }
Eric Laurentdac69112010-09-28 14:09:57 -07008604 }
8605
Mathias Agopian65ab4712010-07-14 17:59:35 -07008606 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08008607 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07008608 for (size_t i = 0; i < size; i++) {
8609 mEffects[i]->process();
8610 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008611 }
8612 for (size_t i = 0; i < size; i++) {
8613 mEffects[i]->updateState();
8614 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008615}
8616
Eric Laurentcab11242010-07-15 12:50:15 -07008617// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07008618status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008619{
8620 effect_descriptor_t desc = effect->desc();
8621 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
8622
8623 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07008624 effect->setChain(this);
8625 sp<ThreadBase> thread = mThread.promote();
8626 if (thread == 0) {
8627 return NO_INIT;
8628 }
8629 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008630
8631 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8632 // Auxiliary effects are inserted at the beginning of mEffects vector as
8633 // they are processed first and accumulated in chain input buffer
8634 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07008635
Mathias Agopian65ab4712010-07-14 17:59:35 -07008636 // the input buffer for auxiliary effect contains mono samples in
8637 // 32 bit format. This is to avoid saturation in AudoMixer
8638 // accumulation stage. Saturation is done in EffectModule::process() before
8639 // calling the process in effect engine
8640 size_t numSamples = thread->frameCount();
8641 int32_t *buffer = new int32_t[numSamples];
8642 memset(buffer, 0, numSamples * sizeof(int32_t));
8643 effect->setInBuffer((int16_t *)buffer);
8644 // auxiliary effects output samples to chain input buffer for further processing
8645 // by insert effects
8646 effect->setOutBuffer(mInBuffer);
8647 } else {
8648 // Insert effects are inserted at the end of mEffects vector as they are processed
8649 // after track and auxiliary effects.
8650 // Insert effect order as a function of indicated preference:
8651 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
8652 // another effect is present
8653 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
8654 // last effect claiming first position
8655 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
8656 // first effect claiming last position
8657 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
8658 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
8659 // already present
8660
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008661 size_t size = mEffects.size();
8662 size_t idx_insert = size;
8663 ssize_t idx_insert_first = -1;
8664 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008665
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008666 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008667 effect_descriptor_t d = mEffects[i]->desc();
8668 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
8669 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
8670 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
8671 // check invalid effect chaining combinations
8672 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
8673 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008674 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008675 return INVALID_OPERATION;
8676 }
8677 // remember position of first insert effect and by default
8678 // select this as insert position for new effect
8679 if (idx_insert == size) {
8680 idx_insert = i;
8681 }
8682 // remember position of last insert effect claiming
8683 // first position
8684 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
8685 idx_insert_first = i;
8686 }
8687 // remember position of first insert effect claiming
8688 // last position
8689 if (iPref == EFFECT_FLAG_INSERT_LAST &&
8690 idx_insert_last == -1) {
8691 idx_insert_last = i;
8692 }
8693 }
8694 }
8695
8696 // modify idx_insert from first position if needed
8697 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
8698 if (idx_insert_last != -1) {
8699 idx_insert = idx_insert_last;
8700 } else {
8701 idx_insert = size;
8702 }
8703 } else {
8704 if (idx_insert_first != -1) {
8705 idx_insert = idx_insert_first + 1;
8706 }
8707 }
8708
8709 // always read samples from chain input buffer
8710 effect->setInBuffer(mInBuffer);
8711
8712 // if last effect in the chain, output samples to chain
8713 // output buffer, otherwise to chain input buffer
8714 if (idx_insert == size) {
8715 if (idx_insert != 0) {
8716 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
8717 mEffects[idx_insert-1]->configure();
8718 }
8719 effect->setOutBuffer(mOutBuffer);
8720 } else {
8721 effect->setOutBuffer(mInBuffer);
8722 }
8723 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008724
Steve Block3856b092011-10-20 11:56:00 +01008725 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008726 }
8727 effect->configure();
8728 return NO_ERROR;
8729}
8730
Eric Laurentcab11242010-07-15 12:50:15 -07008731// removeEffect_l() must be called with PlaybackThread::mLock held
8732size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008733{
8734 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008735 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008736 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
8737
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008738 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008739 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07008740 // calling stop here will remove pre-processing effect from the audio HAL.
8741 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
8742 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07008743 if (mEffects[i]->state() == EffectModule::ACTIVE ||
8744 mEffects[i]->state() == EffectModule::STOPPING) {
8745 mEffects[i]->stop();
8746 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008747 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
8748 delete[] effect->inBuffer();
8749 } else {
8750 if (i == size - 1 && i != 0) {
8751 mEffects[i - 1]->setOutBuffer(mOutBuffer);
8752 mEffects[i - 1]->configure();
8753 }
8754 }
8755 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01008756 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008757 break;
8758 }
8759 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008760
8761 return mEffects.size();
8762}
8763
Eric Laurentcab11242010-07-15 12:50:15 -07008764// setDevice_l() must be called with PlaybackThread::mLock held
8765void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008766{
8767 size_t size = mEffects.size();
8768 for (size_t i = 0; i < size; i++) {
8769 mEffects[i]->setDevice(device);
8770 }
8771}
8772
Eric Laurentcab11242010-07-15 12:50:15 -07008773// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08008774void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008775{
8776 size_t size = mEffects.size();
8777 for (size_t i = 0; i < size; i++) {
8778 mEffects[i]->setMode(mode);
8779 }
8780}
8781
Eric Laurentcab11242010-07-15 12:50:15 -07008782// setVolume_l() must be called with PlaybackThread::mLock held
8783bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008784{
8785 uint32_t newLeft = *left;
8786 uint32_t newRight = *right;
8787 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07008788 int ctrlIdx = -1;
8789 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008790
Eric Laurentcab11242010-07-15 12:50:15 -07008791 // first update volume controller
8792 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07008793 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07008794 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
8795 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07008796 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07008797 break;
8798 }
8799 }
8800
8801 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07008802 if (hasControl) {
8803 *left = mNewLeftVolume;
8804 *right = mNewRightVolume;
8805 }
8806 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07008807 }
8808
8809 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07008810 mLeftVolume = newLeft;
8811 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008812
8813 // second get volume update from volume controller
8814 if (ctrlIdx >= 0) {
8815 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07008816 mNewLeftVolume = newLeft;
8817 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008818 }
8819 // then indicate volume to all other effects in chain.
8820 // Pass altered volume to effects before volume controller
8821 // and requested volume to effects after controller
8822 uint32_t lVol = newLeft;
8823 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008824
Mathias Agopian65ab4712010-07-14 17:59:35 -07008825 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07008826 if ((int)i == ctrlIdx) continue;
8827 // this also works for ctrlIdx == -1 when there is no volume controller
8828 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008829 lVol = *left;
8830 rVol = *right;
8831 }
8832 mEffects[i]->setVolume(&lVol, &rVol, false);
8833 }
8834 *left = newLeft;
8835 *right = newRight;
8836
8837 return hasControl;
8838}
8839
Mathias Agopian65ab4712010-07-14 17:59:35 -07008840status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
8841{
8842 const size_t SIZE = 256;
8843 char buffer[SIZE];
8844 String8 result;
8845
8846 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
8847 result.append(buffer);
8848
8849 bool locked = tryLock(mLock);
8850 // failed to lock - AudioFlinger is probably deadlocked
8851 if (!locked) {
8852 result.append("\tCould not lock mutex:\n");
8853 }
8854
Eric Laurentcab11242010-07-15 12:50:15 -07008855 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
8856 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008857 mEffects.size(),
8858 (uint32_t)mInBuffer,
8859 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008860 mActiveTrackCnt);
8861 result.append(buffer);
8862 write(fd, result.string(), result.size());
8863
8864 for (size_t i = 0; i < mEffects.size(); ++i) {
8865 sp<EffectModule> effect = mEffects[i];
8866 if (effect != 0) {
8867 effect->dump(fd, args);
8868 }
8869 }
8870
8871 if (locked) {
8872 mLock.unlock();
8873 }
8874
8875 return NO_ERROR;
8876}
8877
Eric Laurent59255e42011-07-27 19:49:51 -07008878// must be called with ThreadBase::mLock held
8879void AudioFlinger::EffectChain::setEffectSuspended_l(
8880 const effect_uuid_t *type, bool suspend)
8881{
8882 sp<SuspendedEffectDesc> desc;
8883 // use effect type UUID timelow as key as there is no real risk of identical
8884 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008885 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008886 if (suspend) {
8887 if (index >= 0) {
8888 desc = mSuspendedEffects.valueAt(index);
8889 } else {
8890 desc = new SuspendedEffectDesc();
8891 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
8892 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01008893 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008894 }
8895 if (desc->mRefCount++ == 0) {
8896 sp<EffectModule> effect = getEffectIfEnabled(type);
8897 if (effect != 0) {
8898 desc->mEffect = effect;
8899 effect->setSuspended(true);
8900 effect->setEnabled(false);
8901 }
8902 }
8903 } else {
8904 if (index < 0) {
8905 return;
8906 }
8907 desc = mSuspendedEffects.valueAt(index);
8908 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008909 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008910 desc->mRefCount = 1;
8911 }
8912 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01008913 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008914 if (desc->mEffect != 0) {
8915 sp<EffectModule> effect = desc->mEffect.promote();
8916 if (effect != 0) {
8917 effect->setSuspended(false);
8918 sp<EffectHandle> handle = effect->controlHandle();
8919 if (handle != 0) {
8920 effect->setEnabled(handle->enabled());
8921 }
8922 }
8923 desc->mEffect.clear();
8924 }
8925 mSuspendedEffects.removeItemsAt(index);
8926 }
8927 }
8928}
8929
8930// must be called with ThreadBase::mLock held
8931void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
8932{
8933 sp<SuspendedEffectDesc> desc;
8934
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008935 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07008936 if (suspend) {
8937 if (index >= 0) {
8938 desc = mSuspendedEffects.valueAt(index);
8939 } else {
8940 desc = new SuspendedEffectDesc();
8941 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01008942 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07008943 }
8944 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08008945 Vector< sp<EffectModule> > effects;
8946 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07008947 for (size_t i = 0; i < effects.size(); i++) {
8948 setEffectSuspended_l(&effects[i]->desc().type, true);
8949 }
8950 }
8951 } else {
8952 if (index < 0) {
8953 return;
8954 }
8955 desc = mSuspendedEffects.valueAt(index);
8956 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008957 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008958 desc->mRefCount = 1;
8959 }
8960 if (--desc->mRefCount == 0) {
8961 Vector<const effect_uuid_t *> types;
8962 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
8963 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
8964 continue;
8965 }
8966 types.add(&mSuspendedEffects.valueAt(i)->mType);
8967 }
8968 for (size_t i = 0; i < types.size(); i++) {
8969 setEffectSuspended_l(types[i], false);
8970 }
Steve Block3856b092011-10-20 11:56:00 +01008971 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008972 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
8973 }
8974 }
8975}
8976
Eric Laurent6bffdb82011-09-23 08:40:41 -07008977
8978// The volume effect is used for automated tests only
8979#ifndef OPENSL_ES_H_
8980static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
8981 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
8982const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
8983#endif //OPENSL_ES_H_
8984
Eric Laurentdb7c0792011-08-10 10:37:50 -07008985bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
8986{
8987 // auxiliary effects and visualizer are never suspended on output mix
8988 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8989 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07008990 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8991 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008992 return false;
8993 }
8994 return true;
8995}
8996
Glenn Kastend0539712012-01-30 12:56:03 -08008997void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07008998{
Glenn Kastend0539712012-01-30 12:56:03 -08008999 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009000 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009001 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9002 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009003 }
Eric Laurent59255e42011-07-27 19:49:51 -07009004 }
Eric Laurent59255e42011-07-27 19:49:51 -07009005}
9006
9007sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9008 const effect_uuid_t *type)
9009{
Glenn Kasten090f0192012-01-30 13:00:02 -08009010 sp<EffectModule> effect = getEffectFromType_l(type);
9011 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009012}
9013
9014void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9015 bool enabled)
9016{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009017 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009018 if (enabled) {
9019 if (index < 0) {
9020 // if the effect is not suspend check if all effects are suspended
9021 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9022 if (index < 0) {
9023 return;
9024 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009025 if (!isEffectEligibleForSuspend(effect->desc())) {
9026 return;
9027 }
Eric Laurent59255e42011-07-27 19:49:51 -07009028 setEffectSuspended_l(&effect->desc().type, enabled);
9029 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009030 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009031 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009032 return;
9033 }
Eric Laurent59255e42011-07-27 19:49:51 -07009034 }
Steve Block3856b092011-10-20 11:56:00 +01009035 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009036 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009037 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9038 // if effect is requested to suspended but was not yet enabled, supend it now.
9039 if (desc->mEffect == 0) {
9040 desc->mEffect = effect;
9041 effect->setEnabled(false);
9042 effect->setSuspended(true);
9043 }
9044 } else {
9045 if (index < 0) {
9046 return;
9047 }
Steve Block3856b092011-10-20 11:56:00 +01009048 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009049 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009050 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9051 desc->mEffect.clear();
9052 effect->setSuspended(false);
9053 }
9054}
9055
Mathias Agopian65ab4712010-07-14 17:59:35 -07009056#undef LOG_TAG
9057#define LOG_TAG "AudioFlinger"
9058
9059// ----------------------------------------------------------------------------
9060
9061status_t AudioFlinger::onTransact(
9062 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9063{
9064 return BnAudioFlinger::onTransact(code, data, reply, flags);
9065}
9066
Mathias Agopian65ab4712010-07-14 17:59:35 -07009067}; // namespace android