blob: f94ab84cd6bcdfaf62b16bc9b9b0d990ad854b19 [file] [log] [blame]
Glenn Kastenb3db2132012-01-19 08:59:58 -08001/*
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -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"
Eric Laurent7d850f22010-07-09 13:34:17 -070020//#define LOG_NDEBUG 0
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070021
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9b3f1522011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian07952722009-05-19 19:08:10 -070028#include <binder/IServiceManager.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070029#include <utils/Log.h>
Mathias Agopian07952722009-05-19 19:08:10 -070030#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070032#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurentae29b762011-03-28 18:37:07 -070034#include <utils/Atomic.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070035
Dima Zavin24fc2fb2011-04-19 22:30:36 -070036#include <cutils/bitops.h>
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080037#include <cutils/properties.h>
Glenn Kastene80a4cc2011-12-15 09:51:17 -080038#include <cutils/compiler.h>
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080039
Gloria Wang9b3f1522011-02-24 14:51:45 -080040#include <media/IMediaPlayerService.h>
Glenn Kasten26f260a2012-01-03 15:28:29 -080041#include <media/IMediaDeathNotifier.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042
43#include <private/media/AudioTrackShared.h>
Eric Laurent65b65452010-06-01 23:49:17 -070044#include <private/media/AudioEffectShared.h>
Dima Zavin24fc2fb2011-04-19 22:30:36 -070045
Dima Zavin34bb4192011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin290029d2011-06-13 18:16:26 -070047#include <hardware/audio.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
Glenn Kasten81211142012-02-05 18:09:08 -080051#include "ServiceUtilities.h"
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070052
Eric Laurent53334cd2010-06-23 17:38:20 -070053#include <media/EffectsFactoryApi.h>
Eric Laurent5cc05262011-06-24 07:01:31 -070054#include <audio_effects/effect_visualizer.h>
Eric Laurent6639b552011-08-01 09:52:20 -070055#include <audio_effects/effect_ns.h>
56#include <audio_effects/effect_aec.h>
Eric Laurent65b65452010-06-01 23:49:17 -070057
Glenn Kasten490909d2011-12-15 09:52:39 -080058#include <audio_utils/primitives.h>
59
Glenn Kastenda494f92011-07-08 15:26:12 -070060#include <cpustats/ThreadCpuUsage.h>
Eric Laurent6dbdc402011-07-22 09:04:31 -070061#include <powermanager/PowerManager.h>
Glenn Kastenda494f92011-07-08 15:26:12 -070062// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
63
John Grossmand8cf2962012-02-08 16:37:41 -080064#include <common_time/cc_helper.h>
65#include <common_time/local_clock.h>
66
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067// ----------------------------------------------------------------------------
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068
Eric Laurent8ed6ed02010-07-13 04:45:46 -070069
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070070namespace android {
71
Glenn Kasten62de3db2011-12-12 09:04:45 -080072static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
73static const char kHardwareLockedString[] = "Hardware lock is taken\n";
The Android Open Source Project10592532009-03-18 17:39:46 -070074
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070075static const float MAX_GAIN = 4096.0f;
Glenn Kasten0632bad2012-01-17 12:20:54 -080076static const uint32_t MAX_GAIN_INT = 0x1000;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070077
78// retry counts for buffer fill timeout
79// 50 * ~20msecs = 1 second
80static const int8_t kMaxTrackRetries = 50;
81static const int8_t kMaxTrackStartupRetries = 50;
Eric Laurentef9500f2010-03-11 14:47:00 -080082// allow less retry attempts on direct output thread.
83// direct outputs can be a scarce resource in audio hardware and should
84// be released as quickly as possible.
85static const int8_t kMaxTrackRetriesDirect = 2;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070086
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070087static const int kDumpLockRetries = 50;
Glenn Kastencbfe2e12011-12-13 11:04:14 -080088static const int kDumpLockSleepUs = 20000;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070089
Glenn Kastencbfe2e12011-12-13 11:04:14 -080090// don't warn about blocked writes or record buffer overflows more often than this
91static const nsecs_t kWarningThrottleNs = seconds(5);
Dave Sparksd0ac8c02009-09-30 03:09:03 -070092
Eric Laurent464d5b32011-06-17 21:29:58 -070093// RecordThread loop sleep time upon application overrun or audio HAL read error
94static const int kRecordThreadSleepUs = 5000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095
Glenn Kastencbfe2e12011-12-13 11:04:14 -080096// maximum time to wait for setParameters to complete
97static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent5f37be32011-09-13 11:40:21 -070098
Eric Laurentf1f5fc82011-11-22 18:50:29 -080099// minimum sleep time for the mixer thread loop when tracks are active but in underrun
100static const uint32_t kMinThreadSleepTimeUs = 5000;
101// maximum divider applied to the active sleep time in the mixer thread loop
102static const uint32_t kMaxThreadSleepTimeShift = 2;
103
John Grossmand8cf2962012-02-08 16:37:41 -0800104nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurentf1f5fc82011-11-22 18:50:29 -0800105
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700106// ----------------------------------------------------------------------------
107
Gloria Wang9b3f1522011-02-24 14:51:45 -0800108// To collect the amplifier usage
109static void addBatteryData(uint32_t params) {
Glenn Kasten26f260a2012-01-03 15:28:29 -0800110 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
111 if (service == NULL) {
112 // it already logged
Gloria Wang9b3f1522011-02-24 14:51:45 -0800113 return;
114 }
115
116 service->addBatteryData(params);
117}
118
Dima Zavin31f18882011-04-18 16:57:27 -0700119static int load_audio_interface(const char *if_name, const hw_module_t **mod,
120 audio_hw_device_t **dev)
121{
122 int rc;
123
124 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
125 if (rc)
126 goto out;
127
128 rc = audio_hw_device_open(*mod, dev);
Steve Block3762c312012-01-06 19:20:56 +0000129 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin31f18882011-04-18 16:57:27 -0700130 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
131 if (rc)
132 goto out;
133
134 return 0;
135
136out:
137 *mod = NULL;
138 *dev = NULL;
139 return rc;
140}
141
Glenn Kasten62de3db2011-12-12 09:04:45 -0800142static const char * const audio_interfaces[] = {
Dima Zavin31f18882011-04-18 16:57:27 -0700143 "primary",
144 "a2dp",
145 "usb",
146};
147#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
148
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700149// ----------------------------------------------------------------------------
150
151AudioFlinger::AudioFlinger()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 : BnAudioFlinger(),
John Grossmand8cf2962012-02-08 16:37:41 -0800153 mPrimaryHardwareDev(NULL),
154 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
155 mMasterVolume(1.0f),
156 mMasterVolumeSupportLvl(MVS_NONE),
157 mMasterMute(false),
158 mNextUniqueId(1),
159 mMode(AUDIO_MODE_INVALID),
160 mBtNrecIsOff(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700161{
Dima Zavin2986f5b2011-04-19 19:04:32 -0700162}
163
164void AudioFlinger::onFirstRef()
165{
Dima Zavin31f18882011-04-18 16:57:27 -0700166 int rc = 0;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700167
Eric Laurent01635942011-01-18 18:39:02 -0800168 Mutex::Autolock _l(mLock);
169
Dima Zavin31f18882011-04-18 16:57:27 -0700170 /* TODO: move all this work into an Init() function */
John Grossmand8cf2962012-02-08 16:37:41 -0800171 char val_str[PROPERTY_VALUE_MAX] = { 0 };
172 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
173 uint32_t int_val;
174 if (1 == sscanf(val_str, "%u", &int_val)) {
175 mStandbyTimeInNsecs = milliseconds(int_val);
176 ALOGI("Using %u mSec as standby time.", int_val);
177 } else {
178 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
179 ALOGI("Using default %u mSec as standby time.",
180 (uint32_t)(mStandbyTimeInNsecs / 1000000));
181 }
182 }
Eric Laurenta553c252009-07-17 12:17:14 -0700183
Dima Zavin31f18882011-04-18 16:57:27 -0700184 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
185 const hw_module_t *mod;
186 audio_hw_device_t *dev;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700187
Dima Zavin31f18882011-04-18 16:57:27 -0700188 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
189 if (rc)
190 continue;
191
Steve Block6215d3f2012-01-04 20:05:49 +0000192 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Dima Zavin31f18882011-04-18 16:57:27 -0700193 mod->name, mod->id);
194 mAudioHwDevs.push(dev);
195
Glenn Kastenad8d1752012-02-02 14:05:20 -0800196 if (mPrimaryHardwareDev == NULL) {
Dima Zavin31f18882011-04-18 16:57:27 -0700197 mPrimaryHardwareDev = dev;
Steve Block6215d3f2012-01-04 20:05:49 +0000198 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin2986f5b2011-04-19 19:04:32 -0700199 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin31f18882011-04-18 16:57:27 -0700200 }
201 }
Eric Laurenta553c252009-07-17 12:17:14 -0700202
Glenn Kastenad8d1752012-02-02 14:05:20 -0800203 if (mPrimaryHardwareDev == NULL) {
Steve Block3762c312012-01-06 19:20:56 +0000204 ALOGE("Primary audio interface not found");
Glenn Kastenad8d1752012-02-02 14:05:20 -0800205 // proceed, all later accesses to mPrimaryHardwareDev verify it's safe with initCheck()
Dima Zavin31f18882011-04-18 16:57:27 -0700206 }
207
Glenn Kastenad8d1752012-02-02 14:05:20 -0800208 // Currently (mPrimaryHardwareDev == NULL) == (mAudioHwDevs.size() == 0), but the way the
209 // primary HW dev is selected can change so these conditions might not always be equivalent.
210 // When that happens, re-visit all the code that assumes this.
211
212 AutoMutex lock(mHardwareLock);
213
John Grossmand8cf2962012-02-08 16:37:41 -0800214 // Determine the level of master volume support the primary audio HAL has,
215 // and set the initial master volume at the same time.
216 float initialVolume = 1.0;
217 mMasterVolumeSupportLvl = MVS_NONE;
218 if (0 == mPrimaryHardwareDev->init_check(mPrimaryHardwareDev)) {
219 audio_hw_device_t *dev = mPrimaryHardwareDev;
220
221 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
222 if ((NULL != dev->get_master_volume) &&
223 (NO_ERROR == dev->get_master_volume(dev, &initialVolume))) {
224 mMasterVolumeSupportLvl = MVS_FULL;
225 } else {
226 mMasterVolumeSupportLvl = MVS_SETONLY;
227 initialVolume = 1.0;
228 }
229
230 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
231 if ((NULL == dev->set_master_volume) ||
232 (NO_ERROR != dev->set_master_volume(dev, initialVolume))) {
233 mMasterVolumeSupportLvl = MVS_NONE;
234 }
Glenn Kasten23c9c742012-02-02 14:16:03 -0800235 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8cf2962012-02-08 16:37:41 -0800236 }
237
238 // Set the mode for each audio HAL, and try to set the initial volume (if
239 // supported) for all of the non-primary audio HALs.
Dima Zavin31f18882011-04-18 16:57:27 -0700240 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
241 audio_hw_device_t *dev = mAudioHwDevs[i];
242
243 mHardwareStatus = AUDIO_HW_INIT;
244 rc = dev->init_check(dev);
Glenn Kastenad8d1752012-02-02 14:05:20 -0800245 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin31f18882011-04-18 16:57:27 -0700246 if (rc == 0) {
Glenn Kastenad8d1752012-02-02 14:05:20 -0800247 mMode = AUDIO_MODE_NORMAL; // assigned multiple times with same value
Dima Zavin31f18882011-04-18 16:57:27 -0700248 mHardwareStatus = AUDIO_HW_SET_MODE;
249 dev->set_mode(dev, mMode);
John Grossmand8cf2962012-02-08 16:37:41 -0800250
251 if ((dev != mPrimaryHardwareDev) &&
252 (NULL != dev->set_master_volume)) {
253 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
254 dev->set_master_volume(dev, initialVolume);
255 }
256
Glenn Kasten23c9c742012-02-02 14:16:03 -0800257 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin31f18882011-04-18 16:57:27 -0700258 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700259 }
John Grossmand8cf2962012-02-08 16:37:41 -0800260
261 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
262 ? initialVolume
263 : 1.0;
264 mMasterVolume = initialVolume;
265 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700266}
267
268AudioFlinger::~AudioFlinger()
269{
Dima Zavin31f18882011-04-18 16:57:27 -0700270
Eric Laurent7954c462009-08-28 10:39:03 -0700271 while (!mRecordThreads.isEmpty()) {
272 // closeInput() will remove first entry from mRecordThreads
273 closeInput(mRecordThreads.keyAt(0));
274 }
275 while (!mPlaybackThreads.isEmpty()) {
276 // closeOutput() will remove first entry from mPlaybackThreads
277 closeOutput(mPlaybackThreads.keyAt(0));
278 }
Dima Zavin31f18882011-04-18 16:57:27 -0700279
Glenn Kastenad8d1752012-02-02 14:05:20 -0800280 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
281 // no mHardwareLock needed, as there are no other references to this
282 audio_hw_device_close(mAudioHwDevs[i]);
Eric Laurent7954c462009-08-28 10:39:03 -0700283 }
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800284}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800285
Dima Zavin31f18882011-04-18 16:57:27 -0700286audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
287{
288 /* first matching HW device is returned */
289 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
290 audio_hw_device_t *dev = mAudioHwDevs[i];
291 if ((dev->get_supported_devices(dev) & devices) == devices)
292 return dev;
293 }
294 return NULL;
295}
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700296
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700297status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
298{
299 const size_t SIZE = 256;
300 char buffer[SIZE];
301 String8 result;
302
303 result.append("Clients:\n");
304 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kastene4787422012-01-25 14:27:41 -0800305 sp<Client> client = mClients.valueAt(i).promote();
306 if (client != 0) {
307 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
308 result.append(buffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700309 }
310 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700311
312 result.append("Global session refs:\n");
Glenn Kasten9a42ac92012-03-06 11:22:01 -0800313 result.append(" session pid count\n");
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700314 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
315 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten9a42ac92012-03-06 11:22:01 -0800316 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700317 result.append(buffer);
318 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700319 write(fd, result.string(), result.size());
320 return NO_ERROR;
321}
322
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700323
324status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
325{
326 const size_t SIZE = 256;
327 char buffer[SIZE];
328 String8 result;
Glenn Kastena934c2c2012-01-04 11:02:33 -0800329 hardware_call_state hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700330
John Grossmand8cf2962012-02-08 16:37:41 -0800331 snprintf(buffer, SIZE, "Hardware status: %d\n"
332 "Standby Time mSec: %u\n",
333 hardwareStatus,
334 (uint32_t)(mStandbyTimeInNsecs / 1000000));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700335 result.append(buffer);
336 write(fd, result.string(), result.size());
337 return NO_ERROR;
338}
339
340status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
341{
342 const size_t SIZE = 256;
343 char buffer[SIZE];
344 String8 result;
345 snprintf(buffer, SIZE, "Permission Denial: "
346 "can't dump AudioFlinger from pid=%d, uid=%d\n",
347 IPCThreadState::self()->getCallingPid(),
348 IPCThreadState::self()->getCallingUid());
349 result.append(buffer);
350 write(fd, result.string(), result.size());
351 return NO_ERROR;
352}
353
The Android Open Source Project10592532009-03-18 17:39:46 -0700354static bool tryLock(Mutex& mutex)
355{
356 bool locked = false;
357 for (int i = 0; i < kDumpLockRetries; ++i) {
358 if (mutex.tryLock() == NO_ERROR) {
359 locked = true;
360 break;
361 }
Glenn Kastencbfe2e12011-12-13 11:04:14 -0800362 usleep(kDumpLockSleepUs);
The Android Open Source Project10592532009-03-18 17:39:46 -0700363 }
364 return locked;
365}
366
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700367status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
368{
Glenn Kasten81211142012-02-05 18:09:08 -0800369 if (!dumpAllowed()) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700370 dumpPermissionDenial(fd, args);
371 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700372 // get state of hardware lock
373 bool hardwareLocked = tryLock(mHardwareLock);
374 if (!hardwareLocked) {
375 String8 result(kHardwareLockedString);
376 write(fd, result.string(), result.size());
377 } else {
378 mHardwareLock.unlock();
379 }
380
381 bool locked = tryLock(mLock);
382
383 // failed to lock - AudioFlinger is probably deadlocked
384 if (!locked) {
385 String8 result(kDeadlockedString);
386 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700387 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700388
389 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700390 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800391
Eric Laurenta553c252009-07-17 12:17:14 -0700392 // dump playback threads
393 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700394 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700395 }
396
397 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700398 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700399 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401
Dima Zavin31f18882011-04-18 16:57:27 -0700402 // dump all hardware devs
403 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
404 audio_hw_device_t *dev = mAudioHwDevs[i];
405 dev->dump(dev, fd);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700406 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700407 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700408 }
409 return NO_ERROR;
410}
411
Glenn Kasten803a86a2012-01-25 14:28:29 -0800412sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
413{
414 // If pid is already in the mClients wp<> map, then use that entry
415 // (for which promote() is always != 0), otherwise create a new entry and Client.
416 sp<Client> client = mClients.valueFor(pid).promote();
417 if (client == 0) {
418 client = new Client(this, pid);
419 mClients.add(pid, client);
420 }
421
422 return client;
423}
Eric Laurenta553c252009-07-17 12:17:14 -0700424
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700425// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426
427
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700428sp<IAudioTrack> AudioFlinger::createTrack(
429 pid_t pid,
Glenn Kastenbc1d77b2012-01-12 16:38:12 -0800430 audio_stream_type_t streamType,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700431 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -0800432 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700433 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800434 int frameCount,
Glenn Kasten35269822012-02-21 10:35:56 -0800435 // FIXME dead, remove from IAudioFlinger
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800436 uint32_t flags,
437 const sp<IMemory>& sharedBuffer,
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800438 audio_io_handle_t output,
John Grossmand8cf2962012-02-08 16:37:41 -0800439 bool isTimed,
Eric Laurent65b65452010-06-01 23:49:17 -0700440 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800441 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700442{
Eric Laurenta553c252009-07-17 12:17:14 -0700443 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700444 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700445 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800446 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700447 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700448
Glenn Kasten6e987a42012-01-06 08:40:01 -0800449 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
450 // but if someone uses binder directly they could bypass that and cause us to crash
451 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block3762c312012-01-06 19:20:56 +0000452 ALOGE("createTrack() invalid stream type %d", streamType);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800453 lStatus = BAD_VALUE;
454 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700455 }
456
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800457 {
458 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700459 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent493941b2010-07-28 01:32:47 -0700460 PlaybackThread *effectThread = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -0700461 if (thread == NULL) {
Steve Block3762c312012-01-06 19:20:56 +0000462 ALOGE("unknown output thread");
Eric Laurenta553c252009-07-17 12:17:14 -0700463 lStatus = BAD_VALUE;
464 goto Exit;
465 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800466
Glenn Kasten803a86a2012-01-25 14:28:29 -0800467 client = registerPid_l(pid);
Eric Laurent65b65452010-06-01 23:49:17 -0700468
Steve Block71f2cf12011-10-20 11:56:00 +0100469 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700470 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700471 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent493941b2010-07-28 01:32:47 -0700472 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
473 if (mPlaybackThreads.keyAt(i) != output) {
474 // prevent same audio session on different output threads
475 uint32_t sessions = t->hasAudioSession(*sessionId);
476 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block3762c312012-01-06 19:20:56 +0000477 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent493941b2010-07-28 01:32:47 -0700478 lStatus = BAD_VALUE;
479 goto Exit;
480 }
481 // check if an effect with same session ID is waiting for a track to be created
482 if (sessions & PlaybackThread::EFFECT_SESSION) {
483 effectThread = t.get();
484 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700485 }
486 }
Eric Laurent65b65452010-06-01 23:49:17 -0700487 lSessionId = *sessionId;
488 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700489 // if no audio session id is provided, create one here
Eric Laurent464d5b32011-06-17 21:29:58 -0700490 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -0700491 if (sessionId != NULL) {
492 *sessionId = lSessionId;
493 }
494 }
Steve Block71f2cf12011-10-20 11:56:00 +0100495 ALOGV("createTrack() lSessionId: %d", lSessionId);
Eric Laurent65b65452010-06-01 23:49:17 -0700496
Eric Laurenta553c252009-07-17 12:17:14 -0700497 track = thread->createTrack_l(client, streamType, sampleRate, format,
John Grossmand8cf2962012-02-08 16:37:41 -0800498 channelMask, frameCount, sharedBuffer, lSessionId, isTimed, &lStatus);
Eric Laurent493941b2010-07-28 01:32:47 -0700499
500 // move effect chain to this output thread if an effect on same session was waiting
501 // for a track to be created
502 if (lStatus == NO_ERROR && effectThread != NULL) {
503 Mutex::Autolock _dl(thread->mLock);
504 Mutex::Autolock _sl(effectThread->mLock);
505 moveEffectChain_l(lSessionId, effectThread, thread, true);
506 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700507 }
508 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800509 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700510 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700511 // remove local strong reference to Client before deleting the Track so that the Client
512 // destructor is called by the TrackBase destructor with mLock held
513 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700514 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800515 }
516
517Exit:
518 if(status) {
519 *status = lStatus;
520 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700521 return trackHandle;
522}
523
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800524uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700525{
Eric Laurenta553c252009-07-17 12:17:14 -0700526 Mutex::Autolock _l(mLock);
527 PlaybackThread *thread = checkPlaybackThread_l(output);
528 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000529 ALOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700530 return 0;
531 }
532 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700533}
534
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800535int AudioFlinger::channelCount(audio_io_handle_t output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700536{
Eric Laurenta553c252009-07-17 12:17:14 -0700537 Mutex::Autolock _l(mLock);
538 PlaybackThread *thread = checkPlaybackThread_l(output);
539 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000540 ALOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700541 return 0;
542 }
543 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700544}
545
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800546audio_format_t AudioFlinger::format(audio_io_handle_t output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700547{
Eric Laurenta553c252009-07-17 12:17:14 -0700548 Mutex::Autolock _l(mLock);
549 PlaybackThread *thread = checkPlaybackThread_l(output);
550 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000551 ALOGW("format() unknown thread %d", output);
Glenn Kasten0a204ed2012-01-12 12:27:51 -0800552 return AUDIO_FORMAT_INVALID;
Eric Laurenta553c252009-07-17 12:17:14 -0700553 }
554 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700555}
556
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800557size_t AudioFlinger::frameCount(audio_io_handle_t output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700558{
Eric Laurenta553c252009-07-17 12:17:14 -0700559 Mutex::Autolock _l(mLock);
560 PlaybackThread *thread = checkPlaybackThread_l(output);
561 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000562 ALOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700563 return 0;
564 }
565 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700566}
567
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800568uint32_t AudioFlinger::latency(audio_io_handle_t output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800569{
Eric Laurenta553c252009-07-17 12:17:14 -0700570 Mutex::Autolock _l(mLock);
571 PlaybackThread *thread = checkPlaybackThread_l(output);
572 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000573 ALOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700574 return 0;
575 }
576 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800577}
578
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700579status_t AudioFlinger::setMasterVolume(float value)
580{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700581 status_t ret = initCheck();
582 if (ret != NO_ERROR) {
583 return ret;
584 }
585
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700586 // check calling permissions
587 if (!settingsAllowed()) {
588 return PERMISSION_DENIED;
589 }
590
John Grossmand8cf2962012-02-08 16:37:41 -0800591 float swmv = value;
592
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700593 // when hw supports master volume, don't scale in sw mixer
John Grossmand8cf2962012-02-08 16:37:41 -0800594 if (MVS_NONE != mMasterVolumeSupportLvl) {
595 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
596 AutoMutex lock(mHardwareLock);
597 audio_hw_device_t *dev = mAudioHwDevs[i];
598
599 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
600 if (NULL != dev->set_master_volume) {
601 dev->set_master_volume(dev, value);
602 }
603 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent01635942011-01-18 18:39:02 -0800604 }
John Grossmand8cf2962012-02-08 16:37:41 -0800605
606 swmv = 1.0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700607 }
Eric Laurenta553c252009-07-17 12:17:14 -0700608
Eric Laurent01635942011-01-18 18:39:02 -0800609 Mutex::Autolock _l(mLock);
John Grossmand8cf2962012-02-08 16:37:41 -0800610 mMasterVolume = value;
611 mMasterVolumeSW = swmv;
Glenn Kasten150d2382012-02-08 14:04:28 -0800612 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmand8cf2962012-02-08 16:37:41 -0800613 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700614
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700615 return NO_ERROR;
616}
617
Glenn Kastenaccb1142012-01-04 11:00:47 -0800618status_t AudioFlinger::setMode(audio_mode_t mode)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700619{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700620 status_t ret = initCheck();
621 if (ret != NO_ERROR) {
622 return ret;
623 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700624
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700625 // check calling permissions
626 if (!settingsAllowed()) {
627 return PERMISSION_DENIED;
628 }
Glenn Kasten01aaf2c2012-01-06 16:47:31 -0800629 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block8564c8d2012-01-05 23:22:43 +0000630 ALOGW("Illegal value: setMode(%d)", mode);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700631 return BAD_VALUE;
632 }
633
Eric Laurent53334cd2010-06-23 17:38:20 -0700634 { // scope for the lock
635 AutoMutex lock(mHardwareLock);
636 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin31f18882011-04-18 16:57:27 -0700637 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700638 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800639 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700640
641 if (NO_ERROR == ret) {
642 Mutex::Autolock _l(mLock);
643 mMode = mode;
Glenn Kasten150d2382012-02-08 14:04:28 -0800644 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurent53334cd2010-06-23 17:38:20 -0700645 mPlaybackThreads.valueAt(i)->setMode(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700646 }
647
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700648 return ret;
649}
650
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700651status_t AudioFlinger::setMicMute(bool state)
652{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700653 status_t ret = initCheck();
654 if (ret != NO_ERROR) {
655 return ret;
656 }
657
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700658 // check calling permissions
659 if (!settingsAllowed()) {
660 return PERMISSION_DENIED;
661 }
662
663 AutoMutex lock(mHardwareLock);
664 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700665 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700666 mHardwareStatus = AUDIO_HW_IDLE;
667 return ret;
668}
669
670bool AudioFlinger::getMicMute() const
671{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700672 status_t ret = initCheck();
673 if (ret != NO_ERROR) {
674 return false;
675 }
676
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700677 bool state = AUDIO_MODE_INVALID;
Glenn Kastenad8d1752012-02-02 14:05:20 -0800678 AutoMutex lock(mHardwareLock);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700679 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin31f18882011-04-18 16:57:27 -0700680 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700681 mHardwareStatus = AUDIO_HW_IDLE;
682 return state;
683}
684
685status_t AudioFlinger::setMasterMute(bool muted)
686{
687 // check calling permissions
688 if (!settingsAllowed()) {
689 return PERMISSION_DENIED;
690 }
Eric Laurenta553c252009-07-17 12:17:14 -0700691
Eric Laurent01635942011-01-18 18:39:02 -0800692 Mutex::Autolock _l(mLock);
Glenn Kastenb3db2132012-01-19 08:59:58 -0800693 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Eric Laurenta553c252009-07-17 12:17:14 -0700694 mMasterMute = muted;
Glenn Kasten150d2382012-02-08 14:04:28 -0800695 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700696 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700697
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700698 return NO_ERROR;
699}
700
701float AudioFlinger::masterVolume() const
702{
Glenn Kastene6f8a422011-12-13 11:47:54 -0800703 Mutex::Autolock _l(mLock);
704 return masterVolume_l();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700705}
706
John Grossmand8cf2962012-02-08 16:37:41 -0800707float AudioFlinger::masterVolumeSW() const
708{
709 Mutex::Autolock _l(mLock);
710 return masterVolumeSW_l();
711}
712
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700713bool AudioFlinger::masterMute() const
714{
Glenn Kastene6f8a422011-12-13 11:47:54 -0800715 Mutex::Autolock _l(mLock);
716 return masterMute_l();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700717}
718
John Grossmand8cf2962012-02-08 16:37:41 -0800719float AudioFlinger::masterVolume_l() const
720{
721 if (MVS_FULL == mMasterVolumeSupportLvl) {
722 float ret_val;
723 AutoMutex lock(mHardwareLock);
724
725 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
726 assert(NULL != mPrimaryHardwareDev);
727 assert(NULL != mPrimaryHardwareDev->get_master_volume);
728
729 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
730 mHardwareStatus = AUDIO_HW_IDLE;
731 return ret_val;
732 }
733
734 return mMasterVolume;
735}
736
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800737status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
738 audio_io_handle_t output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700739{
740 // check calling permissions
741 if (!settingsAllowed()) {
742 return PERMISSION_DENIED;
743 }
744
Glenn Kasten6e987a42012-01-06 08:40:01 -0800745 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block3762c312012-01-06 19:20:56 +0000746 ALOGE("setStreamVolume() invalid stream %d", stream);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700747 return BAD_VALUE;
748 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800749
Eric Laurenta553c252009-07-17 12:17:14 -0700750 AutoMutex lock(mLock);
751 PlaybackThread *thread = NULL;
752 if (output) {
753 thread = checkPlaybackThread_l(output);
754 if (thread == NULL) {
755 return BAD_VALUE;
756 }
757 }
758
Eric Laurenta553c252009-07-17 12:17:14 -0700759 mStreamTypes[stream].volume = value;
760
761 if (thread == NULL) {
Glenn Kasten150d2382012-02-08 14:04:28 -0800762 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700763 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700764 }
Eric Laurenta553c252009-07-17 12:17:14 -0700765 } else {
766 thread->setStreamVolume(stream, value);
767 }
Eric Laurentef028272009-04-21 07:56:33 -0700768
Eric Laurent415f3e22009-10-21 08:14:22 -0700769 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700770}
771
Glenn Kastenbc1d77b2012-01-12 16:38:12 -0800772status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700773{
774 // check calling permissions
775 if (!settingsAllowed()) {
776 return PERMISSION_DENIED;
777 }
778
Glenn Kasten6e987a42012-01-06 08:40:01 -0800779 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700780 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block3762c312012-01-06 19:20:56 +0000781 ALOGE("setStreamMute() invalid stream %d", stream);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700782 return BAD_VALUE;
783 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700784
Eric Laurent01635942011-01-18 18:39:02 -0800785 AutoMutex lock(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700786 mStreamTypes[stream].mute = muted;
787 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700788 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700790 return NO_ERROR;
791}
792
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800793float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700794{
Glenn Kasten6e987a42012-01-06 08:40:01 -0800795 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700796 return 0.0f;
797 }
Eric Laurenta553c252009-07-17 12:17:14 -0700798
799 AutoMutex lock(mLock);
800 float volume;
801 if (output) {
802 PlaybackThread *thread = checkPlaybackThread_l(output);
803 if (thread == NULL) {
804 return 0.0f;
805 }
806 volume = thread->streamVolume(stream);
807 } else {
Glenn Kasten8b02b992012-01-09 09:40:36 -0800808 volume = streamVolume_l(stream);
Eric Laurenta553c252009-07-17 12:17:14 -0700809 }
810
Eric Laurentef028272009-04-21 07:56:33 -0700811 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700812}
813
Glenn Kastenbc1d77b2012-01-12 16:38:12 -0800814bool AudioFlinger::streamMute(audio_stream_type_t stream) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700815{
Glenn Kasten6e987a42012-01-06 08:40:01 -0800816 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700817 return true;
818 }
Eric Laurenta553c252009-07-17 12:17:14 -0700819
Glenn Kasten8b02b992012-01-09 09:40:36 -0800820 AutoMutex lock(mLock);
821 return streamMute_l(stream);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700822}
823
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800824status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700825{
Glenn Kasten7ed4f0c2012-02-03 11:10:00 -0800826 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700827 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
828 // check calling permissions
829 if (!settingsAllowed()) {
830 return PERMISSION_DENIED;
The Android Open Source Project9266c552009-01-15 16:12:10 -0800831 }
Eric Laurenta553c252009-07-17 12:17:14 -0700832
833 // ioHandle == 0 means the parameters are global to the audio hardware interface
834 if (ioHandle == 0) {
Dima Zavin31f18882011-04-18 16:57:27 -0700835 status_t final_result = NO_ERROR;
Glenn Kasten23c9c742012-02-02 14:16:03 -0800836 {
837 AutoMutex lock(mHardwareLock);
838 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
Dima Zavin31f18882011-04-18 16:57:27 -0700839 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
840 audio_hw_device_t *dev = mAudioHwDevs[i];
Glenn Kasten23c9c742012-02-02 14:16:03 -0800841 status_t result = dev->set_parameters(dev, keyValuePairs.string());
Dima Zavin31f18882011-04-18 16:57:27 -0700842 final_result = result ?: final_result;
843 }
Eric Laurenta553c252009-07-17 12:17:14 -0700844 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten23c9c742012-02-02 14:16:03 -0800845 }
Eric Laurent6639b552011-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) {
850 Mutex::Autolock _l(mLock);
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700851 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
852 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent6639b552011-08-01 09:52:20 -0700853 for (size_t i = 0; i < mRecordThreads.size(); i++) {
854 sp<RecordThread> thread = mRecordThreads.valueAt(i);
855 RecordThread::RecordTrack *track = thread->track();
856 if (track != NULL) {
857 audio_devices_t device = (audio_devices_t)(
858 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700859 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent6639b552011-08-01 09:52:20 -0700860 thread->setEffectSuspended(FX_IID_AEC,
861 suspend,
862 track->sessionId());
863 thread->setEffectSuspended(FX_IID_NS,
864 suspend,
865 track->sessionId());
866 }
867 }
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700868 mBtNrecIsOff = btNrecIsOff;
Eric Laurent6639b552011-08-01 09:52:20 -0700869 }
870 }
Dima Zavin31f18882011-04-18 16:57:27 -0700871 return final_result;
Eric Laurenta553c252009-07-17 12:17:14 -0700872 }
873
Eric Laurentb7d94602009-09-29 11:12:57 -0700874 // hold a strong ref on thread in case closeOutput() or closeInput() is called
875 // and the thread is exited once the lock is released
876 sp<ThreadBase> thread;
877 {
878 Mutex::Autolock _l(mLock);
879 thread = checkPlaybackThread_l(ioHandle);
880 if (thread == NULL) {
881 thread = checkRecordThread_l(ioHandle);
Glenn Kasten70ed6b72012-01-10 10:46:34 -0800882 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent464d5b32011-06-17 21:29:58 -0700883 // indicate output device change to all input threads for pre processing
884 AudioParameter param = AudioParameter(keyValuePairs);
885 int value;
886 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
887 for (size_t i = 0; i < mRecordThreads.size(); i++) {
888 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
889 }
890 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700891 }
Eric Laurenta553c252009-07-17 12:17:14 -0700892 }
Glenn Kasten706b6182012-01-20 13:44:40 -0800893 if (thread != 0) {
894 return thread->setParameters(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -0700895 }
Eric Laurenta553c252009-07-17 12:17:14 -0700896 return BAD_VALUE;
897}
898
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800899String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Eric Laurenta553c252009-07-17 12:17:14 -0700900{
Glenn Kasten7ed4f0c2012-02-03 11:10:00 -0800901// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700902// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
903
904 if (ioHandle == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700905 String8 out_s8;
906
Dima Zavin31f18882011-04-18 16:57:27 -0700907 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten23c9c742012-02-02 14:16:03 -0800908 char *s;
909 {
910 AutoMutex lock(mHardwareLock);
911 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Dima Zavin31f18882011-04-18 16:57:27 -0700912 audio_hw_device_t *dev = mAudioHwDevs[i];
Glenn Kasten23c9c742012-02-02 14:16:03 -0800913 s = dev->get_parameters(dev, keys.string());
914 mHardwareStatus = AUDIO_HW_IDLE;
915 }
John Grossman4fbe95e2012-02-09 11:28:36 -0800916 out_s8 += String8(s ? s : "");
Dima Zavin31f18882011-04-18 16:57:27 -0700917 free(s);
918 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700919 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -0700920 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700921
922 Mutex::Autolock _l(mLock);
923
Eric Laurenta553c252009-07-17 12:17:14 -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("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700933}
934
Glenn Kasten3f6d83a2012-01-26 16:25:10 -0800935size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700937 status_t ret = initCheck();
938 if (ret != NO_ERROR) {
939 return 0;
940 }
941
Glenn Kastenad8d1752012-02-02 14:05:20 -0800942 AutoMutex lock(mHardwareLock);
943 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
944 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
945 mHardwareStatus = AUDIO_HW_IDLE;
946 return size;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947}
948
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800949unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Eric Laurent47d0a922010-02-26 02:47:27 -0800950{
951 if (ioHandle == 0) {
952 return 0;
953 }
954
955 Mutex::Autolock _l(mLock);
956
957 RecordThread *recordThread = checkRecordThread_l(ioHandle);
958 if (recordThread != NULL) {
959 return recordThread->getInputFramesLost();
960 }
961 return 0;
962}
963
Eric Laurent415f3e22009-10-21 08:14:22 -0700964status_t AudioFlinger::setVoiceVolume(float value)
965{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700966 status_t ret = initCheck();
967 if (ret != NO_ERROR) {
968 return ret;
969 }
970
Eric Laurent415f3e22009-10-21 08:14:22 -0700971 // check calling permissions
972 if (!settingsAllowed()) {
973 return PERMISSION_DENIED;
974 }
975
976 AutoMutex lock(mHardwareLock);
Glenn Kasten23c9c742012-02-02 14:16:03 -0800977 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700978 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700979 mHardwareStatus = AUDIO_HW_IDLE;
980
981 return ret;
982}
983
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800984status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
985 audio_io_handle_t output) const
Eric Laurent0986e792010-01-19 17:37:09 -0800986{
987 status_t status;
988
989 Mutex::Autolock _l(mLock);
990
991 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
992 if (playbackThread != NULL) {
993 return playbackThread->getRenderPosition(halFrames, dspFrames);
994 }
995
996 return BAD_VALUE;
997}
998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1000{
Eric Laurenta553c252009-07-17 12:17:14 -07001001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 Mutex::Autolock _l(mLock);
1003
Glenn Kastend153b1f2012-02-03 11:10:26 -08001004 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent4f0f17d2010-05-12 02:05:53 -07001005 if (mNotificationClients.indexOfKey(pid) < 0) {
1006 sp<NotificationClient> notificationClient = new NotificationClient(this,
1007 client,
1008 pid);
Steve Block71f2cf12011-10-20 11:56:00 +01001009 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -07001010
Eric Laurent4f0f17d2010-05-12 02:05:53 -07001011 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -07001012
Eric Laurent4f0f17d2010-05-12 02:05:53 -07001013 sp<IBinder> binder = client->asBinder();
1014 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015
Eric Laurent4f0f17d2010-05-12 02:05:53 -07001016 // the config change is always sent from playback or record threads to avoid deadlock
1017 // with AudioSystem::gLock
1018 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1019 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1020 }
Eric Laurenta553c252009-07-17 12:17:14 -07001021
Eric Laurent4f0f17d2010-05-12 02:05:53 -07001022 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1023 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 }
1025 }
1026}
1027
Eric Laurent4f0f17d2010-05-12 02:05:53 -07001028void AudioFlinger::removeNotificationClient(pid_t pid)
1029{
1030 Mutex::Autolock _l(mLock);
1031
Glenn Kasten538529b2012-01-20 09:19:01 -08001032 mNotificationClients.removeItem(pid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07001033
Steve Block71f2cf12011-10-20 11:56:00 +01001034 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten150d2382012-02-08 14:04:28 -08001035 size_t num = mAudioSessionRefs.size();
Marco Nelissenc74b93f2011-08-02 13:33:41 -07001036 bool removed = false;
Glenn Kasten150d2382012-02-08 14:04:28 -08001037 for (size_t i = 0; i< num; ) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07001038 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten9a42ac92012-03-06 11:22:01 -08001039 ALOGV(" pid %d @ %d", ref->mPid, i);
1040 if (ref->mPid == pid) {
1041 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07001042 mAudioSessionRefs.removeAt(i);
1043 delete ref;
1044 removed = true;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07001045 num--;
Glenn Kasten150d2382012-02-08 14:04:28 -08001046 } else {
1047 i++;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07001048 }
1049 }
1050 if (removed) {
1051 purgeStaleEffects_l();
1052 }
Eric Laurent4f0f17d2010-05-12 02:05:53 -07001053}
1054
Eric Laurent296a0ec2009-09-15 07:10:12 -07001055// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenffed04a2012-03-01 09:14:51 -08001056void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Eric Laurent4f0f17d2010-05-12 02:05:53 -07001057{
Eric Laurent49f02be2009-11-19 09:00:56 -08001058 size_t size = mNotificationClients.size();
1059 for (size_t i = 0; i < size; i++) {
Glenn Kastendc3ac852012-01-25 15:28:08 -08001060 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1061 param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001062 }
1063}
1064
Eric Laurentb9481d82009-09-17 05:12:56 -07001065// removeClient_l() must be called with AudioFlinger::mLock held
1066void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001067{
Steve Block71f2cf12011-10-20 11:56:00 +01001068 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001069 mClients.removeItem(pid);
1070}
1071
Eric Laurent4f0f17d2010-05-12 02:05:53 -07001072
Eric Laurenta553c252009-07-17 12:17:14 -07001073// ----------------------------------------------------------------------------
1074
Glenn Kasten39d00cb2012-01-17 11:09:42 -08001075AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1076 uint32_t device, type_t type)
Eric Laurenta553c252009-07-17 12:17:14 -07001077 : Thread(false),
Glenn Kastenefd511a2012-01-26 10:38:26 -08001078 mType(type),
Glenn Kastendc3ac852012-01-25 15:28:08 -08001079 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
1080 // mChannelMask
1081 mChannelCount(0),
1082 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1083 mParamStatus(NO_ERROR),
Glenn Kasten761286f2012-01-06 08:39:38 -08001084 mStandby(false), mId(id),
Glenn Kastendc3ac852012-01-25 15:28:08 -08001085 mDevice(device),
1086 mDeathRecipient(new PMDeathRecipient(this))
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001087{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088}
1089
Eric Laurenta553c252009-07-17 12:17:14 -07001090AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091{
Eric Laurent8fce46a2009-08-04 09:45:33 -07001092 mParamCond.broadcast();
Eric Laurent6dbdc402011-07-22 09:04:31 -07001093 // do not lock the mutex in destructor
1094 releaseWakeLock_l();
Eric Laurent4a64a6e2011-09-27 12:07:15 -07001095 if (mPowerManager != 0) {
1096 sp<IBinder> binder = mPowerManager->asBinder();
1097 binder->unlinkToDeath(mDeathRecipient);
1098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099}
1100
Eric Laurenta553c252009-07-17 12:17:14 -07001101void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001102{
Steve Block71f2cf12011-10-20 11:56:00 +01001103 ALOGV("ThreadBase::exit");
Eric Laurenta553c252009-07-17 12:17:14 -07001104 {
Glenn Kasten761286f2012-01-06 08:39:38 -08001105 // This lock prevents the following race in thread (uniprocessor for illustration):
1106 // if (!exitPending()) {
1107 // // context switch from here to exit()
1108 // // exit() calls requestExit(), what exitPending() observes
1109 // // exit() calls signal(), which is dropped since no waiters
1110 // // context switch back from exit() to here
1111 // mWaitWorkCV.wait(...);
1112 // // now thread is hung
1113 // }
Glenn Kasten325ee1c2012-01-05 15:41:56 -08001114 AutoMutex lock(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001115 requestExit();
1116 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001117 }
Glenn Kasten761286f2012-01-06 08:39:38 -08001118 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1119 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Eric Laurenta553c252009-07-17 12:17:14 -07001120 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001121}
Eric Laurenta553c252009-07-17 12:17:14 -07001122
Eric Laurenta553c252009-07-17 12:17:14 -07001123status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1124{
Eric Laurent8fce46a2009-08-04 09:45:33 -07001125 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -07001126
Steve Block71f2cf12011-10-20 11:56:00 +01001127 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -07001128 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001129
Eric Laurent8fce46a2009-08-04 09:45:33 -07001130 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -07001131 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -07001132 // wait condition with timeout in case the thread loop has exited
1133 // before the request could be processed
Glenn Kastencbfe2e12011-12-13 11:04:14 -08001134 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Eric Laurentb7d94602009-09-29 11:12:57 -07001135 status = mParamStatus;
1136 mWaitWorkCV.signal();
1137 } else {
1138 status = TIMED_OUT;
1139 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001140 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07001141}
1142
1143void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1144{
1145 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -07001146 sendConfigEvent_l(event, param);
1147}
1148
1149// sendConfigEvent_l() must be called with ThreadBase::mLock held
1150void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1151{
Glenn Kasten4b220f02011-12-13 11:50:00 -08001152 ConfigEvent configEvent;
1153 configEvent.mEvent = event;
1154 configEvent.mParam = param;
Eric Laurenta553c252009-07-17 12:17:14 -07001155 mConfigEvents.add(configEvent);
Steve Block71f2cf12011-10-20 11:56:00 +01001156 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001157 mWaitWorkCV.signal();
1158}
1159
1160void AudioFlinger::ThreadBase::processConfigEvents()
1161{
1162 mLock.lock();
1163 while(!mConfigEvents.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001164 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kasten4b220f02011-12-13 11:50:00 -08001165 ConfigEvent configEvent = mConfigEvents[0];
Eric Laurenta553c252009-07-17 12:17:14 -07001166 mConfigEvents.removeAt(0);
Eric Laurenteb8f8502010-05-14 03:26:45 -07001167 // release mLock before locking AudioFlinger mLock: lock order is always
1168 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -07001169 mLock.unlock();
Eric Laurenteb8f8502010-05-14 03:26:45 -07001170 mAudioFlinger->mLock.lock();
Glenn Kasten4b220f02011-12-13 11:50:00 -08001171 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Eric Laurenteb8f8502010-05-14 03:26:45 -07001172 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -07001173 mLock.lock();
1174 }
1175 mLock.unlock();
1176}
1177
Eric Laurent3fdb1262009-11-07 00:01:32 -08001178status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1179{
1180 const size_t SIZE = 256;
1181 char buffer[SIZE];
1182 String8 result;
1183
1184 bool locked = tryLock(mLock);
1185 if (!locked) {
1186 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1187 write(fd, buffer, strlen(buffer));
1188 }
1189
1190 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1191 result.append(buffer);
1192 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1193 result.append(buffer);
1194 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1195 result.append(buffer);
1196 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1197 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001198 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1199 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001200 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1201 result.append(buffer);
Glenn Kastenfaf354d2012-01-11 09:48:27 -08001202 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001203 result.append(buffer);
1204
1205 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1206 result.append(buffer);
1207 result.append(" Index Command");
1208 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1209 snprintf(buffer, SIZE, "\n %02d ", i);
1210 result.append(buffer);
1211 result.append(mNewParameters[i]);
1212 }
1213
1214 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1215 result.append(buffer);
1216 snprintf(buffer, SIZE, " Index event param\n");
1217 result.append(buffer);
1218 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kasten4b220f02011-12-13 11:50:00 -08001219 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001220 result.append(buffer);
1221 }
1222 result.append("\n");
1223
1224 write(fd, result.string(), result.size());
1225
1226 if (locked) {
1227 mLock.unlock();
1228 }
1229 return NO_ERROR;
1230}
1231
Eric Laurent1345d332011-07-24 17:49:51 -07001232status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1233{
1234 const size_t SIZE = 256;
1235 char buffer[SIZE];
1236 String8 result;
1237
1238 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1239 write(fd, buffer, strlen(buffer));
1240
1241 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1242 sp<EffectChain> chain = mEffectChains[i];
1243 if (chain != 0) {
1244 chain->dump(fd, args);
1245 }
1246 }
1247 return NO_ERROR;
1248}
1249
Eric Laurent6dbdc402011-07-22 09:04:31 -07001250void AudioFlinger::ThreadBase::acquireWakeLock()
1251{
1252 Mutex::Autolock _l(mLock);
1253 acquireWakeLock_l();
1254}
1255
1256void AudioFlinger::ThreadBase::acquireWakeLock_l()
1257{
1258 if (mPowerManager == 0) {
1259 // use checkService() to avoid blocking if power service is not up yet
1260 sp<IBinder> binder =
1261 defaultServiceManager()->checkService(String16("power"));
1262 if (binder == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00001263 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001264 } else {
1265 mPowerManager = interface_cast<IPowerManager>(binder);
1266 binder->linkToDeath(mDeathRecipient);
1267 }
1268 }
1269 if (mPowerManager != 0) {
1270 sp<IBinder> binder = new BBinder();
1271 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1272 binder,
1273 String16(mName));
1274 if (status == NO_ERROR) {
1275 mWakeLockToken = binder;
1276 }
Steve Block71f2cf12011-10-20 11:56:00 +01001277 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001278 }
1279}
1280
1281void AudioFlinger::ThreadBase::releaseWakeLock()
1282{
1283 Mutex::Autolock _l(mLock);
Eric Laurentd49ead62011-07-28 13:59:02 -07001284 releaseWakeLock_l();
Eric Laurent6dbdc402011-07-22 09:04:31 -07001285}
1286
1287void AudioFlinger::ThreadBase::releaseWakeLock_l()
1288{
1289 if (mWakeLockToken != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001290 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001291 if (mPowerManager != 0) {
1292 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1293 }
1294 mWakeLockToken.clear();
1295 }
1296}
1297
1298void AudioFlinger::ThreadBase::clearPowerManager()
1299{
1300 Mutex::Autolock _l(mLock);
1301 releaseWakeLock_l();
1302 mPowerManager.clear();
1303}
1304
1305void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1306{
1307 sp<ThreadBase> thread = mThread.promote();
1308 if (thread != 0) {
1309 thread->clearPowerManager();
1310 }
Steve Block8564c8d2012-01-05 23:22:43 +00001311 ALOGW("power manager service died !!!");
Eric Laurent6dbdc402011-07-22 09:04:31 -07001312}
Eric Laurent1345d332011-07-24 17:49:51 -07001313
Eric Laurentf82fccd2011-07-27 19:49:51 -07001314void AudioFlinger::ThreadBase::setEffectSuspended(
1315 const effect_uuid_t *type, bool suspend, int sessionId)
1316{
1317 Mutex::Autolock _l(mLock);
1318 setEffectSuspended_l(type, suspend, sessionId);
1319}
1320
1321void AudioFlinger::ThreadBase::setEffectSuspended_l(
1322 const effect_uuid_t *type, bool suspend, int sessionId)
1323{
Glenn Kastenc64a6f02012-01-30 13:00:02 -08001324 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001325 if (chain != 0) {
1326 if (type != NULL) {
1327 chain->setEffectSuspended_l(type, suspend);
1328 } else {
1329 chain->setEffectSuspendedAll_l(suspend);
1330 }
1331 }
1332
1333 updateSuspendedSessions_l(type, suspend, sessionId);
1334}
1335
1336void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1337{
Glenn Kasten150d2382012-02-08 14:04:28 -08001338 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurentf82fccd2011-07-27 19:49:51 -07001339 if (index < 0) {
1340 return;
1341 }
1342
1343 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1344 mSuspendedSessions.editValueAt(index);
1345
1346 for (size_t i = 0; i < sessionEffects.size(); i++) {
1347 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1348 for (int j = 0; j < desc->mRefCount; j++) {
1349 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1350 chain->setEffectSuspendedAll_l(true);
1351 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01001352 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001353 desc->mType.timeLow);
1354 chain->setEffectSuspended_l(&desc->mType, true);
1355 }
1356 }
1357 }
1358}
1359
Eric Laurentf82fccd2011-07-27 19:49:51 -07001360void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1361 bool suspend,
1362 int sessionId)
1363{
Glenn Kasten150d2382012-02-08 14:04:28 -08001364 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001365
1366 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1367
1368 if (suspend) {
1369 if (index >= 0) {
1370 sessionEffects = mSuspendedSessions.editValueAt(index);
1371 } else {
1372 mSuspendedSessions.add(sessionId, sessionEffects);
1373 }
1374 } else {
1375 if (index < 0) {
1376 return;
1377 }
1378 sessionEffects = mSuspendedSessions.editValueAt(index);
1379 }
1380
1381
1382 int key = EffectChain::kKeyForSuspendAll;
1383 if (type != NULL) {
1384 key = type->timeLow;
1385 }
1386 index = sessionEffects.indexOfKey(key);
1387
1388 sp <SuspendedSessionDesc> desc;
1389 if (suspend) {
1390 if (index >= 0) {
1391 desc = sessionEffects.valueAt(index);
1392 } else {
1393 desc = new SuspendedSessionDesc();
1394 if (type != NULL) {
1395 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1396 }
1397 sessionEffects.add(key, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01001398 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001399 }
1400 desc->mRefCount++;
1401 } else {
1402 if (index < 0) {
1403 return;
1404 }
1405 desc = sessionEffects.valueAt(index);
1406 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001407 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001408 sessionEffects.removeItemsAt(index);
1409 if (sessionEffects.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001410 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001411 sessionId);
1412 mSuspendedSessions.removeItem(sessionId);
1413 }
1414 }
1415 }
1416 if (!sessionEffects.isEmpty()) {
1417 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1418 }
1419}
1420
1421void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1422 bool enabled,
1423 int sessionId)
1424{
1425 Mutex::Autolock _l(mLock);
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001426 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1427}
Eric Laurentf82fccd2011-07-27 19:49:51 -07001428
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001429void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1430 bool enabled,
1431 int sessionId)
1432{
Eric Laurent6752ec82011-08-10 10:37:50 -07001433 if (mType != RECORD) {
1434 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1435 // another session. This gives the priority to well behaved effect control panels
1436 // and applications not using global effects.
1437 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1438 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1439 }
1440 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07001441
1442 sp<EffectChain> chain = getEffectChain_l(sessionId);
1443 if (chain != 0) {
1444 chain->checkSuspendOnEffectEnabled(effect, enabled);
1445 }
1446}
1447
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448// ----------------------------------------------------------------------------
1449
Eric Laurent464d5b32011-06-17 21:29:58 -07001450AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1451 AudioStreamOut* output,
Glenn Kasten39d00cb2012-01-17 11:09:42 -08001452 audio_io_handle_t id,
Glenn Kastenefd511a2012-01-26 10:38:26 -08001453 uint32_t device,
1454 type_t type)
1455 : ThreadBase(audioFlinger, id, device, type),
Glenn Kastendc3ac852012-01-25 15:28:08 -08001456 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1457 // Assumes constructor is called by AudioFlinger with it's mLock held,
1458 // but it would be safer to explicitly pass initial masterMute as parameter
1459 mMasterMute(audioFlinger->masterMute_l()),
1460 // mStreamTypes[] initialized in constructor body
1461 mOutput(output),
1462 // Assumes constructor is called by AudioFlinger with it's mLock held,
1463 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossmand8cf2962012-02-08 16:37:41 -08001464 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastena13446a2012-03-08 07:47:15 -08001465 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1466 // mMixerStatus
1467 mPrevMixerStatus(MIXER_IDLE)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468{
Glenn Kasten86e33622012-02-28 12:30:08 -08001469 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001470
Eric Laurenta553c252009-07-17 12:17:14 -07001471 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472
Glenn Kasten6e987a42012-01-06 08:40:01 -08001473 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001474 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1475 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1476 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten8b02b992012-01-09 09:40:36 -08001477 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1478 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Glenn Kasten6e987a42012-01-06 08:40:01 -08001479 // initialized by stream_type_t default constructor
1480 // mStreamTypes[stream].valid = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 }
Glenn Kasten8b02b992012-01-09 09:40:36 -08001482 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1483 // because mAudioFlinger doesn't have one to copy from
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484}
1485
Eric Laurenta553c252009-07-17 12:17:14 -07001486AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487{
1488 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489}
1490
Eric Laurenta553c252009-07-17 12:17:14 -07001491status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492{
1493 dumpInternals(fd, args);
1494 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001495 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 return NO_ERROR;
1497}
1498
Eric Laurenta553c252009-07-17 12:17:14 -07001499status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500{
1501 const size_t SIZE = 256;
1502 char buffer[SIZE];
1503 String8 result;
1504
Eric Laurenta553c252009-07-17 12:17:14 -07001505 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001507 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001509 sp<Track> track = mTracks[i];
1510 if (track != 0) {
1511 track->dump(buffer, SIZE);
1512 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 }
1514 }
1515
Eric Laurenta553c252009-07-17 12:17:14 -07001516 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001518 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kastene4787422012-01-25 14:27:41 -08001520 sp<Track> track = mActiveTracks[i].promote();
1521 if (track != 0) {
1522 track->dump(buffer, SIZE);
1523 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 }
1525 }
1526 write(fd, result.string(), result.size());
1527 return NO_ERROR;
1528}
1529
Eric Laurenta553c252009-07-17 12:17:14 -07001530status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531{
1532 const size_t SIZE = 256;
1533 char buffer[SIZE];
1534 String8 result;
1535
Eric Laurent3fdb1262009-11-07 00:01:32 -08001536 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 result.append(buffer);
1538 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1539 result.append(buffer);
1540 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1541 result.append(buffer);
1542 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1543 result.append(buffer);
1544 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1545 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001546 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1547 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001548 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1549 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001551
1552 dumpBase(fd, args);
1553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554 return NO_ERROR;
1555}
1556
1557// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001558status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559{
Eric Laurent828b9772011-08-07 16:32:26 -07001560 status_t status = initCheck();
1561 if (status == NO_ERROR) {
Steve Block6215d3f2012-01-04 20:05:49 +00001562 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurent828b9772011-08-07 16:32:26 -07001563 } else {
Steve Block3762c312012-01-06 19:20:56 +00001564 ALOGE("No working audio driver found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 }
Eric Laurent828b9772011-08-07 16:32:26 -07001566 return status;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567}
1568
Eric Laurenta553c252009-07-17 12:17:14 -07001569void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001571 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572}
1573
Eric Laurenta553c252009-07-17 12:17:14 -07001574// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1575sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 const sp<AudioFlinger::Client>& client,
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001577 audio_stream_type_t streamType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08001579 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001580 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 int frameCount,
1582 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001583 int sessionId,
John Grossmand8cf2962012-02-08 16:37:41 -08001584 bool isTimed,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 status_t *status)
1586{
1587 sp<Track> track;
1588 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001589
1590 if (mType == DIRECT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001591 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1592 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block3762c312012-01-06 19:20:56 +00001593 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001594 "for output %p with format %d",
1595 sampleRate, format, channelMask, mOutput, mFormat);
1596 lStatus = BAD_VALUE;
1597 goto Exit;
1598 }
Eric Laurenta553c252009-07-17 12:17:14 -07001599 }
1600 } else {
1601 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1602 if (sampleRate > mSampleRate*2) {
Steve Block3762c312012-01-06 19:20:56 +00001603 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Eric Laurenta553c252009-07-17 12:17:14 -07001604 lStatus = BAD_VALUE;
1605 goto Exit;
1606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 }
1608
Eric Laurent464d5b32011-06-17 21:29:58 -07001609 lStatus = initCheck();
1610 if (lStatus != NO_ERROR) {
Steve Block3762c312012-01-06 19:20:56 +00001611 ALOGE("Audio driver not initialized.");
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001612 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 }
1614
Eric Laurenta553c252009-07-17 12:17:14 -07001615 { // scope for mLock
1616 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001617
1618 // all tracks in same audio session must share the same routing strategy otherwise
1619 // conflicts will happen when tracks are moved from one output to another by audio policy
1620 // manager
Glenn Kastenaae26c82012-02-08 12:35:35 -08001621 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001622 for (size_t i = 0; i < mTracks.size(); ++i) {
1623 sp<Track> t = mTracks[i];
Glenn Kasten12f32d62012-03-07 12:26:34 -08001624 if (t != 0 && !t->isOutputTrack()) {
Glenn Kastenaae26c82012-02-08 12:35:35 -08001625 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kasten9818a9d2011-10-28 10:31:42 -07001626 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block3762c312012-01-06 19:20:56 +00001627 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kasten9818a9d2011-10-28 10:31:42 -07001628 strategy, actual);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001629 lStatus = BAD_VALUE;
1630 goto Exit;
1631 }
1632 }
1633 }
1634
John Grossmand8cf2962012-02-08 16:37:41 -08001635 if (!isTimed) {
1636 track = new Track(this, client, streamType, sampleRate, format,
1637 channelMask, frameCount, sharedBuffer, sessionId);
1638 } else {
1639 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1640 channelMask, frameCount, sharedBuffer, sessionId);
1641 }
1642 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001643 lStatus = NO_MEMORY;
1644 goto Exit;
1645 }
1646 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001647
1648 sp<EffectChain> chain = getEffectChain_l(sessionId);
1649 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001650 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Eric Laurent65b65452010-06-01 23:49:17 -07001651 track->setMainBuffer(chain->inBuffer());
Glenn Kastenaae26c82012-02-08 12:35:35 -08001652 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurent90681d62011-05-09 12:09:06 -07001653 chain->incTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001654 }
Eric Laurent05ce0942011-08-30 10:18:54 -07001655
1656 // invalidate track immediately if the stream type was moved to another thread since
1657 // createTrack() was called by the client process.
1658 if (!mStreamTypes[streamType].valid) {
Steve Block8564c8d2012-01-05 23:22:43 +00001659 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent05ce0942011-08-30 10:18:54 -07001660 this, streamType);
1661 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1662 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001663 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001664 lStatus = NO_ERROR;
1665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666Exit:
1667 if(status) {
1668 *status = lStatus;
1669 }
1670 return track;
1671}
1672
Eric Laurenta553c252009-07-17 12:17:14 -07001673uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674{
Eric Laurent828b9772011-08-07 16:32:26 -07001675 Mutex::Autolock _l(mLock);
1676 if (initCheck() == NO_ERROR) {
Dima Zavin31f18882011-04-18 16:57:27 -07001677 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurent828b9772011-08-07 16:32:26 -07001678 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 return 0;
1680 }
1681}
1682
Glenn Kasten8b02b992012-01-09 09:40:36 -08001683void AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684{
Glenn Kasten8b02b992012-01-09 09:40:36 -08001685 Mutex::Autolock _l(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 mMasterVolume = value;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687}
1688
Glenn Kasten8b02b992012-01-09 09:40:36 -08001689void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690{
Glenn Kasten8b02b992012-01-09 09:40:36 -08001691 Mutex::Autolock _l(mLock);
1692 setMasterMute_l(muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693}
1694
Glenn Kasten8b02b992012-01-09 09:40:36 -08001695void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696{
Glenn Kasten8b02b992012-01-09 09:40:36 -08001697 Mutex::Autolock _l(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 mStreamTypes[stream].volume = value;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699}
1700
Glenn Kasten8b02b992012-01-09 09:40:36 -08001701void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702{
Glenn Kasten8b02b992012-01-09 09:40:36 -08001703 Mutex::Autolock _l(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 mStreamTypes[stream].mute = muted;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705}
1706
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001707float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708{
Glenn Kasten8b02b992012-01-09 09:40:36 -08001709 Mutex::Autolock _l(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 return mStreamTypes[stream].volume;
1711}
1712
Eric Laurenta553c252009-07-17 12:17:14 -07001713// addTrack_l() must be called with ThreadBase::mLock held
1714status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715{
1716 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001717
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001718 // set retry count for buffer fill
1719 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001720 if (mActiveTracks.indexOf(track) < 0) {
1721 // the track is newly added, make sure it fills up all its
1722 // buffers before playing. This is to ensure the client will
1723 // effectively get the latency it requested.
1724 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001725 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001726 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001727 if (track->mainBuffer() != mMixBuffer) {
1728 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1729 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001730 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07001731 chain->incActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001732 }
1733 }
1734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001736 }
Eric Laurenta553c252009-07-17 12:17:14 -07001737
Steve Block71f2cf12011-10-20 11:56:00 +01001738 ALOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001739 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740
1741 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001742}
1743
Eric Laurenta553c252009-07-17 12:17:14 -07001744// destroyTrack_l() must be called with ThreadBase::mLock held
1745void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001746{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001747 track->mState = TrackBase::TERMINATED;
1748 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent90681d62011-05-09 12:09:06 -07001749 removeTrack_l(track);
1750 }
1751}
1752
1753void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1754{
1755 mTracks.remove(track);
1756 deleteTrackName_l(track->name());
1757 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1758 if (chain != 0) {
1759 chain->decTrackCnt();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001760 }
1761}
1762
Eric Laurenta553c252009-07-17 12:17:14 -07001763String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001764{
Eric Laurent828b9772011-08-07 16:32:26 -07001765 String8 out_s8 = String8("");
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001766 char *s;
1767
Eric Laurent828b9772011-08-07 16:32:26 -07001768 Mutex::Autolock _l(mLock);
1769 if (initCheck() != NO_ERROR) {
1770 return out_s8;
1771 }
1772
Dima Zavin31f18882011-04-18 16:57:27 -07001773 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001774 out_s8 = String8(s);
1775 free(s);
1776 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07001777}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001778
Eric Laurent828b9772011-08-07 16:32:26 -07001779// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurenteb8f8502010-05-14 03:26:45 -07001780void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001781 AudioSystem::OutputDescriptor desc;
Glenn Kasten3694ec12012-01-27 16:47:15 -08001782 void *param2 = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07001783
Steve Block71f2cf12011-10-20 11:56:00 +01001784 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001785
1786 switch (event) {
1787 case AudioSystem::OUTPUT_OPENED:
1788 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001789 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07001790 desc.samplingRate = mSampleRate;
1791 desc.format = mFormat;
1792 desc.frameCount = mFrameCount;
1793 desc.latency = latency();
1794 param2 = &desc;
1795 break;
1796
1797 case AudioSystem::STREAM_CONFIG_CHANGED:
1798 param2 = &param;
1799 case AudioSystem::OUTPUT_CLOSED:
1800 default:
1801 break;
1802 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001803 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001804}
1805
1806void AudioFlinger::PlaybackThread::readOutputParameters()
1807{
Dima Zavin31f18882011-04-18 16:57:27 -07001808 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001809 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1810 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f18882011-04-18 16:57:27 -07001811 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenfaf354d2012-01-11 09:48:27 -08001812 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin31f18882011-04-18 16:57:27 -07001813 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001814
Eric Laurenta553c252009-07-17 12:17:14 -07001815 // FIXME - Current mixer implementation only supports stereo output: Always
1816 // Allocate a stereo buffer even if HW output is mono.
Glenn Kasten2589cf92012-01-27 18:08:45 -08001817 delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001818 mMixBuffer = new int16_t[mFrameCount * 2];
1819 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001820
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001821 // force reconfiguration of effect chains and engines to take new buffer size and audio
1822 // parameters into account
1823 // Note that mLock is not held when readOutputParameters() is called from the constructor
1824 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1825 // matter.
1826 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1827 Vector< sp<EffectChain> > effectChains = mEffectChains;
1828 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent493941b2010-07-28 01:32:47 -07001829 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001830 }
Eric Laurenta553c252009-07-17 12:17:14 -07001831}
1832
Eric Laurent0986e792010-01-19 17:37:09 -08001833status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1834{
Glenn Kasten3694ec12012-01-27 16:47:15 -08001835 if (halFrames == NULL || dspFrames == NULL) {
Eric Laurent0986e792010-01-19 17:37:09 -08001836 return BAD_VALUE;
1837 }
Eric Laurent828b9772011-08-07 16:32:26 -07001838 Mutex::Autolock _l(mLock);
Eric Laurent464d5b32011-06-17 21:29:58 -07001839 if (initCheck() != NO_ERROR) {
Eric Laurent0986e792010-01-19 17:37:09 -08001840 return INVALID_OPERATION;
1841 }
Dima Zavin31f18882011-04-18 16:57:27 -07001842 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Eric Laurent0986e792010-01-19 17:37:09 -08001843
Dima Zavin31f18882011-04-18 16:57:27 -07001844 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Eric Laurent0986e792010-01-19 17:37:09 -08001845}
1846
Eric Laurent493941b2010-07-28 01:32:47 -07001847uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Eric Laurent65b65452010-06-01 23:49:17 -07001848{
1849 Mutex::Autolock _l(mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07001850 uint32_t result = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001851 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent493941b2010-07-28 01:32:47 -07001852 result = EFFECT_SESSION;
Eric Laurent65b65452010-06-01 23:49:17 -07001853 }
1854
1855 for (size_t i = 0; i < mTracks.size(); ++i) {
1856 sp<Track> track = mTracks[i];
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001857 if (sessionId == track->sessionId() &&
1858 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent493941b2010-07-28 01:32:47 -07001859 result |= TRACK_SESSION;
1860 break;
Eric Laurent65b65452010-06-01 23:49:17 -07001861 }
1862 }
1863
Eric Laurent493941b2010-07-28 01:32:47 -07001864 return result;
Eric Laurent65b65452010-06-01 23:49:17 -07001865}
1866
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001867uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1868{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001869 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001870 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001871 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1872 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001873 }
1874 for (size_t i = 0; i < mTracks.size(); i++) {
1875 sp<Track> track = mTracks[i];
1876 if (sessionId == track->sessionId() &&
1877 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kastenaae26c82012-02-08 12:35:35 -08001878 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001879 }
1880 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001881 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001882}
1883
Eric Laurent53334cd2010-06-23 17:38:20 -07001884
Glenn Kasten5b0135e2012-01-26 09:46:34 -08001885AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent828b9772011-08-07 16:32:26 -07001886{
1887 Mutex::Autolock _l(mLock);
1888 return mOutput;
1889}
1890
1891AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1892{
1893 Mutex::Autolock _l(mLock);
1894 AudioStreamOut *output = mOutput;
1895 mOutput = NULL;
1896 return output;
1897}
1898
1899// this method must always be called either with ThreadBase mLock held or inside the thread loop
1900audio_stream_t* AudioFlinger::PlaybackThread::stream()
1901{
1902 if (mOutput == NULL) {
1903 return NULL;
1904 }
1905 return &mOutput->stream->common;
1906}
1907
Eric Laurent44331692011-12-05 09:47:19 -08001908uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1909{
1910 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1911 // decoding and transfer time. So sleeping for half of the latency would likely cause
1912 // underruns
1913 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1914 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1915 } else {
1916 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1917 }
1918}
1919
Eric Laurenta553c252009-07-17 12:17:14 -07001920// ----------------------------------------------------------------------------
1921
Glenn Kastenefd511a2012-01-26 10:38:26 -08001922AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten39d00cb2012-01-17 11:09:42 -08001923 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten67cb3122012-03-01 17:10:56 -08001924 : PlaybackThread(audioFlinger, output, id, device, type)
Eric Laurenta553c252009-07-17 12:17:14 -07001925{
Glenn Kasten67cb3122012-03-01 17:10:56 -08001926 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
Eric Laurenta553c252009-07-17 12:17:14 -07001927 // FIXME - Current mixer implementation only supports stereo output
1928 if (mChannelCount == 1) {
Steve Block3762c312012-01-06 19:20:56 +00001929 ALOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001931}
1932
Eric Laurenta553c252009-07-17 12:17:14 -07001933AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001934{
Eric Laurenta553c252009-07-17 12:17:14 -07001935 delete mAudioMixer;
1936}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937
Glenn Kasten6ec27552012-02-24 07:21:32 -08001938class CpuStats {
1939public:
1940 void sample();
1941#ifdef DEBUG_CPU_USAGE
1942private:
1943 ThreadCpuUsage mCpu;
1944#endif
1945};
1946
1947void CpuStats::sample() {
1948#ifdef DEBUG_CPU_USAGE
1949 const CentralTendencyStatistics& stats = mCpu.statistics();
1950 mCpu.sampleAndEnable();
1951 unsigned n = stats.n();
1952 // mCpu.elapsed() is expensive, so don't call it every loop
1953 if ((n & 127) == 1) {
1954 long long elapsed = mCpu.elapsed();
1955 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1956 double perLoop = elapsed / (double) n;
1957 double perLoop100 = perLoop * 0.01;
1958 double mean = stats.mean();
1959 double stddev = stats.stddev();
1960 double minimum = stats.minimum();
1961 double maximum = stats.maximum();
1962 mCpu.resetStatistics();
1963 ALOGI("CPU usage over past %.1f secs (%u mixer loops at %.1f mean ms per loop):\n us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f",
1964 elapsed * .000000001, n, perLoop * .000001,
1965 mean * .001,
1966 stddev * .001,
1967 minimum * .001,
1968 maximum * .001,
1969 mean / perLoop100,
1970 stddev / perLoop100,
1971 minimum / perLoop100,
1972 maximum / perLoop100);
1973 }
1974 }
1975#endif
1976};
1977
Glenn Kasten2521a012012-02-24 07:21:48 -08001978void AudioFlinger::PlaybackThread::checkSilentMode_l()
1979{
1980 if (!mMasterMute) {
1981 char value[PROPERTY_VALUE_MAX];
1982 if (property_get("ro.audio.silent", value, "0") > 0) {
1983 char *endptr;
1984 unsigned long ul = strtoul(value, &endptr, 0);
1985 if (*endptr == '\0' && ul != 0) {
1986 ALOGD("Silence is golden");
1987 // The setprop command will not allow a property to be changed after
1988 // the first time it is set, so we don't have to worry about un-muting.
1989 setMasterMute_l(true);
1990 }
1991 }
1992 }
1993}
1994
Glenn Kasten67cb3122012-03-01 17:10:56 -08001995bool AudioFlinger::PlaybackThread::threadLoop()
Eric Laurenta553c252009-07-17 12:17:14 -07001996{
Eric Laurenta553c252009-07-17 12:17:14 -07001997 Vector< sp<Track> > tracksToRemove;
Glenn Kastenbea6b952012-02-29 07:57:06 -08001998
Glenn Kasten67cb3122012-03-01 17:10:56 -08001999 standbyTime = systemTime();
2000 mixBufferSize = mFrameCount * mFrameSize;
2001
2002 // MIXER
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002003 // FIXME: Relaxed timing because of a certain device that can't meet latency
2004 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07002005 // increase threshold again due to low power audio mode. The way this warning threshold is
2006 // calculated and its usefulness should be reconsidered anyway.
2007 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002008 nsecs_t lastWarning = 0;
Glenn Kasten67cb3122012-03-01 17:10:56 -08002009if (mType == MIXER) {
2010 longStandbyExit = false;
2011}
Glenn Kastenbea6b952012-02-29 07:57:06 -08002012
Glenn Kasten67cb3122012-03-01 17:10:56 -08002013 // DUPLICATING
2014 // FIXME could this be made local to while loop?
2015 writeFrames = 0;
Glenn Kastenbea6b952012-02-29 07:57:06 -08002016
Glenn Kasten67cb3122012-03-01 17:10:56 -08002017 activeSleepTime = activeSleepTimeUs();
2018 idleSleepTime = idleSleepTimeUs();
2019 sleepTime = idleSleepTime;
2020
2021if (mType == MIXER) {
2022 sleepTimeShift = 0;
2023}
2024
2025 // MIXER
Glenn Kasten6ec27552012-02-24 07:21:32 -08002026 CpuStats cpuStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027
Glenn Kasten67cb3122012-03-01 17:10:56 -08002028 // DIRECT
2029if (mType == DIRECT) {
2030 // use shorter standby delay as on normal output to release
2031 // hardware resources as soon as possible
2032 standbyDelay = microseconds(activeSleepTime*2);
2033}
Glenn Kastenbea6b952012-02-29 07:57:06 -08002034
Eric Laurent6dbdc402011-07-22 09:04:31 -07002035 acquireWakeLock();
2036
Eric Laurenta553c252009-07-17 12:17:14 -07002037 while (!exitPending())
2038 {
Glenn Kasten67cb3122012-03-01 17:10:56 -08002039if (mType == MIXER) {
Glenn Kasten6ec27552012-02-24 07:21:32 -08002040 cpuStats.sample();
Glenn Kasten67cb3122012-03-01 17:10:56 -08002041}
Glenn Kastenbea6b952012-02-29 07:57:06 -08002042
Glenn Kasten3c4f0dc2012-02-29 07:56:15 -08002043 Vector< sp<EffectChain> > effectChains;
2044
Eric Laurenta553c252009-07-17 12:17:14 -07002045 processConfigEvents();
2046
Glenn Kastena13446a2012-03-08 07:47:15 -08002047 mMixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002048 { // scope for mLock
2049
2050 Mutex::Autolock _l(mLock);
2051
2052 if (checkForNewParameters_l()) {
2053 mixBufferSize = mFrameCount * mFrameSize;
Glenn Kastenbea6b952012-02-29 07:57:06 -08002054
Glenn Kasten67cb3122012-03-01 17:10:56 -08002055if (mType == MIXER) {
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002056 // FIXME: Relaxed timing because of a certain device that can't meet latency
2057 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07002058 // increase threshold again due to low power audio mode. The way this warning
2059 // threshold is calculated and its usefulness should be reconsidered anyway.
2060 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Glenn Kasten67cb3122012-03-01 17:10:56 -08002061}
2062
Glenn Kasten2bad67f2012-03-06 11:24:48 -08002063 updateWaitTime_l();
Glenn Kastenbea6b952012-02-29 07:57:06 -08002064
Eric Laurent059b4be2009-11-09 23:32:22 -08002065 activeSleepTime = activeSleepTimeUs();
2066 idleSleepTime = idleSleepTimeUs();
Glenn Kasten67cb3122012-03-01 17:10:56 -08002067
2068if (mType == DIRECT) {
2069 standbyDelay = microseconds(activeSleepTime*2);
2070}
2071
Eric Laurenta553c252009-07-17 12:17:14 -07002072 }
2073
Glenn Kasten08d2c042012-03-06 11:28:04 -08002074 saveOutputTracks();
Glenn Kasten67cb3122012-03-01 17:10:56 -08002075
Eric Laurenta553c252009-07-17 12:17:14 -07002076 // put audio hardware into standby after short delay
Glenn Kastend9cccfa2012-02-28 18:40:35 -08002077 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastene70583e2012-02-29 07:07:30 -08002078 mSuspended > 0)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002079 if (!mStandby) {
Glenn Kasten67cb3122012-03-01 17:10:56 -08002080
2081 threadLoop_standby();
2082
Eric Laurenta553c252009-07-17 12:17:14 -07002083 mStandby = true;
2084 mBytesWritten = 0;
2085 }
2086
Glenn Kastend9cccfa2012-02-28 18:40:35 -08002087 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002088 // we're about to wait, flush the binder command buffer
2089 IPCThreadState::self()->flushCommands();
2090
Glenn Kasten08d2c042012-03-06 11:28:04 -08002091 clearOutputTracks();
Glenn Kasten67cb3122012-03-01 17:10:56 -08002092
Eric Laurenta553c252009-07-17 12:17:14 -07002093 if (exitPending()) break;
2094
Eric Laurent6dbdc402011-07-22 09:04:31 -07002095 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002096 // wait until we have something to do...
Glenn Kasten3be2bc02012-02-24 11:18:09 -08002097 ALOGV("Thread %p type %d TID %d going to sleep", this, mType, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07002098 mWaitWorkCV.wait(mLock);
Glenn Kasten3be2bc02012-02-24 11:18:09 -08002099 ALOGV("Thread %p type %d TID %d waking up", this, mType, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07002100 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002101
Eric Laurent71c44962012-01-17 19:20:12 -08002102 mPrevMixerStatus = MIXER_IDLE;
Glenn Kasten67cb3122012-03-01 17:10:56 -08002103
Glenn Kasten2521a012012-02-24 07:21:48 -08002104 checkSilentMode_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002105
Glenn Kasten67cb3122012-03-01 17:10:56 -08002106if (mType == MIXER || mType == DUPLICATING) {
John Grossmand8cf2962012-02-08 16:37:41 -08002107 standbyTime = systemTime() + mStandbyTimeInNsecs;
Glenn Kasten67cb3122012-03-01 17:10:56 -08002108}
2109
2110if (mType == DIRECT) {
2111 standbyTime = systemTime() + standbyDelay;
2112}
2113
Eric Laurent059b4be2009-11-09 23:32:22 -08002114 sleepTime = idleSleepTime;
Glenn Kasten67cb3122012-03-01 17:10:56 -08002115
2116if (mType == MIXER) {
Eric Laurentf1f5fc82011-11-22 18:50:29 -08002117 sleepTimeShift = 0;
Glenn Kasten67cb3122012-03-01 17:10:56 -08002118}
2119
Eric Laurenta553c252009-07-17 12:17:14 -07002120 continue;
2121 }
2122 }
2123
Glenn Kastena13446a2012-03-08 07:47:15 -08002124 mixer_state newMixerStatus = prepareTracks_l(&tracksToRemove);
2125 // Shift in the new status; this could be a queue if it's
2126 // useful to filter the mixer status over several cycles.
2127 mPrevMixerStatus = mMixerStatus;
2128 mMixerStatus = newMixerStatus;
Eric Laurent65b65452010-06-01 23:49:17 -07002129
2130 // prevent any changes in effect chain list and in each effect chain
2131 // during mixing and effect process as the audio buffers could be deleted
2132 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002133 lockEffectChains_l(effectChains);
Glenn Kastenfb2ab9e2011-12-12 09:05:55 -08002134 }
Eric Laurenta553c252009-07-17 12:17:14 -07002135
Glenn Kastena13446a2012-03-08 07:47:15 -08002136 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten67cb3122012-03-01 17:10:56 -08002137 threadLoop_mix();
2138 } else {
2139 threadLoop_sleepTime();
2140 }
2141
2142 if (mSuspended > 0) {
2143 sleepTime = suspendSleepTimeUs();
2144 }
2145
2146 // only process effects if we're going to write
2147 if (sleepTime == 0) {
Glenn Kasten67cb3122012-03-01 17:10:56 -08002148 for (size_t i = 0; i < effectChains.size(); i ++) {
2149 effectChains[i]->process_l();
2150 }
2151 }
2152
2153 // enable changes in effect chain
2154 unlockEffectChains(effectChains);
2155
2156 // sleepTime == 0 means we must write to audio hardware
2157 if (sleepTime == 0) {
2158
2159 threadLoop_write();
2160
2161if (mType == MIXER) {
2162 // write blocked detection
2163 nsecs_t now = systemTime();
2164 nsecs_t delta = now - mLastWriteTime;
2165 if (!mStandby && delta > maxPeriod) {
2166 mNumDelayedWrites++;
2167 if ((now - lastWarning) > kWarningThrottleNs) {
2168 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2169 ns2ms(delta), mNumDelayedWrites, this);
2170 lastWarning = now;
2171 }
2172 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2173 // a different threshold. Or completely removed for what it is worth anyway...
2174 if (mStandby) {
2175 longStandbyExit = true;
2176 }
2177 }
2178}
2179
2180 mStandby = false;
2181 } else {
2182 usleep(sleepTime);
2183 }
2184
2185 // finally let go of removed track(s), without the lock held
2186 // since we can't guarantee the destructors won't acquire that
2187 // same lock.
Glenn Kasten761415b2012-03-06 11:23:32 -08002188 tracksToRemove.clear();
Glenn Kasten67cb3122012-03-01 17:10:56 -08002189
Glenn Kasten08d2c042012-03-06 11:28:04 -08002190 // FIXME I don't understand the need for this here;
2191 // it was in the original code but maybe the
2192 // assignment in saveOutputTracks() makes this unnecessary?
2193 clearOutputTracks();
Glenn Kasten67cb3122012-03-01 17:10:56 -08002194
2195 // Effect chains will be actually deleted here if they were removed from
2196 // mEffectChains list during mixing or effects processing
2197 effectChains.clear();
2198
2199 // FIXME Note that the above .clear() is no longer necessary since effectChains
2200 // is now local to this block, but will keep it for now (at least until merge done).
2201 }
2202
2203if (mType == MIXER || mType == DIRECT) {
2204 // put output stream into standby mode
2205 if (!mStandby) {
2206 mOutput->stream->common.standby(&mOutput->stream->common);
2207 }
2208}
2209if (mType == DUPLICATING) {
2210 // for DuplicatingThread, standby mode is handled by the outputTracks
2211}
2212
2213 releaseWakeLock();
2214
2215 ALOGV("Thread %p type %d exiting", this, mType);
2216 return false;
2217}
2218
2219// shared by MIXER and DIRECT, overridden by DUPLICATING
2220void AudioFlinger::PlaybackThread::threadLoop_write()
2221{
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002222 // FIXME rewrite to reduce number of system calls
2223 mLastWriteTime = systemTime();
2224 mInWrite = true;
2225 mBytesWritten += mixBufferSize;
2226 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2227 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2228 mNumWrites++;
2229 mInWrite = false;
Glenn Kasten67cb3122012-03-01 17:10:56 -08002230}
2231
2232// shared by MIXER and DIRECT, overridden by DUPLICATING
2233void AudioFlinger::PlaybackThread::threadLoop_standby()
2234{
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002235 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2236 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten67cb3122012-03-01 17:10:56 -08002237}
2238
2239void AudioFlinger::MixerThread::threadLoop_mix()
2240{
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002241 // obtain the presentation timestamp of the next output buffer
2242 int64_t pts;
2243 status_t status = INVALID_OPERATION;
John Grossmand8cf2962012-02-08 16:37:41 -08002244
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002245 if (NULL != mOutput->stream->get_next_write_timestamp) {
2246 status = mOutput->stream->get_next_write_timestamp(
2247 mOutput->stream, &pts);
2248 }
John Grossmand8cf2962012-02-08 16:37:41 -08002249
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002250 if (status != NO_ERROR) {
2251 pts = AudioBufferProvider::kInvalidPTS;
2252 }
John Grossmand8cf2962012-02-08 16:37:41 -08002253
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002254 // mix buffers...
2255 mAudioMixer->process(pts);
2256 // increase sleep time progressively when application underrun condition clears.
2257 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2258 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2259 // such that we would underrun the audio HAL.
2260 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2261 sleepTimeShift--;
2262 }
2263 sleepTime = 0;
2264 standbyTime = systemTime() + mStandbyTimeInNsecs;
2265 //TODO: delay standby when effects have a tail
Glenn Kasten67cb3122012-03-01 17:10:56 -08002266}
2267
2268void AudioFlinger::MixerThread::threadLoop_sleepTime()
2269{
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002270 // If no tracks are ready, sleep once for the duration of an output
2271 // buffer size, then write 0s to the output
2272 if (sleepTime == 0) {
Glenn Kastena13446a2012-03-08 07:47:15 -08002273 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002274 sleepTime = activeSleepTime >> sleepTimeShift;
2275 if (sleepTime < kMinThreadSleepTimeUs) {
2276 sleepTime = kMinThreadSleepTimeUs;
Eric Laurent96c08a62009-09-07 08:38:38 -07002277 }
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002278 // reduce sleep time in case of consecutive application underruns to avoid
2279 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2280 // duration we would end up writing less data than needed by the audio HAL if
2281 // the condition persists.
2282 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2283 sleepTimeShift++;
2284 }
2285 } else {
2286 sleepTime = idleSleepTime;
2287 }
2288 } else if (mBytesWritten != 0 ||
Glenn Kastena13446a2012-03-08 07:47:15 -08002289 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002290 memset (mMixBuffer, 0, mixBufferSize);
2291 sleepTime = 0;
Glenn Kastena13446a2012-03-08 07:47:15 -08002292 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002293 }
2294 // TODO add standby time extension fct of effect tail
Eric Laurenta553c252009-07-17 12:17:14 -07002295}
2296
2297// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten789fef12012-01-26 13:37:52 -08002298AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kastend9cccfa2012-02-28 18:40:35 -08002299 Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07002300{
2301
Glenn Kasten789fef12012-01-26 13:37:52 -08002302 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002303 // find out which tracks need to be processed
Glenn Kastend9cccfa2012-02-28 18:40:35 -08002304 size_t count = mActiveTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07002305 size_t mixedTracks = 0;
2306 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002307
2308 float masterVolume = mMasterVolume;
2309 bool masterMute = mMasterMute;
2310
Eric Laurent8cc93b92010-08-11 05:20:11 -07002311 if (masterMute) {
2312 masterVolume = 0;
2313 }
Eric Laurent65b65452010-06-01 23:49:17 -07002314 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002315 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07002316 if (chain != 0) {
Eric Laurent8cc93b92010-08-11 05:20:11 -07002317 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07002318 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07002319 masterVolume = (float)((v + (1 << 23)) >> 24);
2320 chain.clear();
2321 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08002322
Eric Laurenta553c252009-07-17 12:17:14 -07002323 for (size_t i=0 ; i<count ; i++) {
Glenn Kastend9cccfa2012-02-28 18:40:35 -08002324 sp<Track> t = mActiveTracks[i].promote();
Eric Laurenta553c252009-07-17 12:17:14 -07002325 if (t == 0) continue;
2326
Glenn Kasten68deb152011-12-19 15:06:39 -08002327 // this const just means the local variable doesn't change
Eric Laurenta553c252009-07-17 12:17:14 -07002328 Track* const track = t.get();
2329 audio_track_cblk_t* cblk = track->cblk();
2330
2331 // The first time a track is added we wait
2332 // for all its buffers to be filled before processing it
Glenn Kasten68deb152011-12-19 15:06:39 -08002333 int name = track->name();
Eric Laurent8a04fe02011-11-08 18:10:16 -08002334 // make sure that we have enough frames to mix one full buffer.
2335 // enforce this condition only once to enable draining the buffer in case the client
2336 // app does not call stop() and relies on underrun to stop:
Eric Laurent71c44962012-01-17 19:20:12 -08002337 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurent8a04fe02011-11-08 18:10:16 -08002338 // during last round
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002339 uint32_t minFrames = 1;
Eric Laurent8a04fe02011-11-08 18:10:16 -08002340 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent71c44962012-01-17 19:20:12 -08002341 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002342 if (t->sampleRate() == (int)mSampleRate) {
2343 minFrames = mFrameCount;
2344 } else {
Eric Laurent72dafb22011-12-22 16:08:41 -08002345 // +1 for rounding and +1 for additional sample needed for interpolation
2346 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2347 // add frames already consumed but not yet released by the resampler
2348 // because cblk->framesReady() will include these frames
2349 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2350 // the minimum track buffer size is normally twice the number of frames necessary
2351 // to fill one buffer and the resampler should not leave more than one buffer worth
2352 // of unreleased frames after each pass, but just in case...
Steve Blockec193de2012-01-09 18:35:44 +00002353 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002354 }
2355 }
John Grossmand8cf2962012-02-08 16:37:41 -08002356 if ((track->framesReady() >= minFrames) && track->isReady() &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07002357 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002358 {
Glenn Kasten68deb152011-12-19 15:06:39 -08002359 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002360
Eric Laurent65b65452010-06-01 23:49:17 -07002361 mixedTracks++;
2362
2363 // track->mainBuffer() != mMixBuffer means there is an effect chain
2364 // connected to the track
2365 chain.clear();
2366 if (track->mainBuffer() != mMixBuffer) {
2367 chain = getEffectChain_l(track->sessionId());
2368 // Delegate volume control to effect in track effect chain if needed
2369 if (chain != 0) {
2370 tracksWithEffect++;
2371 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00002372 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten68deb152011-12-19 15:06:39 -08002373 name, track->sessionId());
Eric Laurent65b65452010-06-01 23:49:17 -07002374 }
2375 }
2376
2377
2378 int param = AudioMixer::VOLUME;
2379 if (track->mFillingUpStatus == Track::FS_FILLED) {
2380 // no ramp for the first volume setting
2381 track->mFillingUpStatus = Track::FS_ACTIVE;
2382 if (track->mState == TrackBase::RESUMING) {
2383 track->mState = TrackBase::ACTIVE;
2384 param = AudioMixer::RAMP_VOLUME;
2385 }
Glenn Kasten68deb152011-12-19 15:06:39 -08002386 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent65b65452010-06-01 23:49:17 -07002387 } else if (cblk->server != 0) {
2388 // If the track is stopped before the first frame was mixed,
2389 // do not apply ramp
2390 param = AudioMixer::RAMP_VOLUME;
2391 }
2392
Eric Laurenta553c252009-07-17 12:17:14 -07002393 // compute volume for this track
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002394 uint32_t vl, vr, va;
Eric Laurent2a6b80b2010-07-29 23:43:43 -07002395 if (track->isMuted() || track->isPausing() ||
Glenn Kastenaae26c82012-02-08 12:35:35 -08002396 mStreamTypes[track->streamType()].mute) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002397 vl = vr = va = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07002398 if (track->isPausing()) {
2399 track->setPaused();
2400 }
2401 } else {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002402
Glenn Kasten871c16c2010-03-05 12:18:01 -08002403 // read original volumes with volume control
Glenn Kastenaae26c82012-02-08 12:35:35 -08002404 float typeVolume = mStreamTypes[track->streamType()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002405 float v = masterVolume * typeVolume;
Glenn Kastenbc4de882012-01-17 14:39:34 -08002406 uint32_t vlr = cblk->getVolumeLR();
Glenn Kasten0632bad2012-01-17 12:20:54 -08002407 vl = vlr & 0xFFFF;
2408 vr = vlr >> 16;
2409 // track volumes come from shared memory, so can't be trusted and must be clamped
2410 if (vl > MAX_GAIN_INT) {
2411 ALOGV("Track left volume out of range: %04X", vl);
2412 vl = MAX_GAIN_INT;
2413 }
2414 if (vr > MAX_GAIN_INT) {
2415 ALOGV("Track right volume out of range: %04X", vr);
2416 vr = MAX_GAIN_INT;
2417 }
2418 // now apply the master volume and stream type volume
2419 vl = (uint32_t)(v * vl) << 12;
2420 vr = (uint32_t)(v * vr) << 12;
2421 // assuming master volume and stream type volume each go up to 1.0,
2422 // vl and vr are now in 8.24 format
Eric Laurenta553c252009-07-17 12:17:14 -07002423
Glenn Kasten4790bd82012-01-03 14:22:33 -08002424 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2425 // send level comes from shared memory and so may be corrupt
Glenn Kasten4f22c052012-01-27 15:26:23 -08002426 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten4790bd82012-01-03 14:22:33 -08002427 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kasten0632bad2012-01-17 12:20:54 -08002428 sendLevel = MAX_GAIN_INT;
Glenn Kasten4790bd82012-01-03 14:22:33 -08002429 }
2430 va = (uint32_t)(v * sendLevel);
Eric Laurenta553c252009-07-17 12:17:14 -07002431 }
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002432 // Delegate volume control to effect in track effect chain if needed
2433 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2434 // Do not ramp volume if volume is controlled by effect
2435 param = AudioMixer::VOLUME;
2436 track->mHasVolumeController = true;
2437 } else {
2438 // force no volume ramp when volume controller was just disabled or removed
2439 // from effect chain to avoid volume spike
2440 if (track->mHasVolumeController) {
2441 param = AudioMixer::VOLUME;
2442 }
2443 track->mHasVolumeController = false;
2444 }
2445
2446 // Convert volumes from 8.24 to 4.12 format
Glenn Kasten0632bad2012-01-17 12:20:54 -08002447 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten4f22c052012-01-27 15:26:23 -08002448 vl = (vl + (1 << 11)) >> 12;
2449 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2450 vr = (vr + (1 << 11)) >> 12;
2451 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002452
Glenn Kasten4f22c052012-01-27 15:26:23 -08002453 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
Eric Laurent65b65452010-06-01 23:49:17 -07002454
Eric Laurent65b65452010-06-01 23:49:17 -07002455 // XXX: these things DON'T need to be done each time
Glenn Kasten68deb152011-12-19 15:06:39 -08002456 mAudioMixer->setBufferProvider(name, track);
2457 mAudioMixer->enable(name);
Eric Laurent65b65452010-06-01 23:49:17 -07002458
Glenn Kasten4f22c052012-01-27 15:26:23 -08002459 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2460 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2461 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Eric Laurenta553c252009-07-17 12:17:14 -07002462 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002463 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002464 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07002465 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07002466 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002467 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002468 AudioMixer::TRACK,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002469 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Eric Laurenta553c252009-07-17 12:17:14 -07002470 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002471 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002472 AudioMixer::RESAMPLE,
2473 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07002474 (void *)(cblk->sampleRate));
2475 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002476 name,
Eric Laurent65b65452010-06-01 23:49:17 -07002477 AudioMixer::TRACK,
2478 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2479 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002480 name,
Eric Laurent65b65452010-06-01 23:49:17 -07002481 AudioMixer::TRACK,
2482 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07002483
2484 // reset retry count
2485 track->mRetryCount = kMaxTrackRetries;
Eric Laurent71c44962012-01-17 19:20:12 -08002486 // If one track is ready, set the mixer ready if:
2487 // - the mixer was not ready during previous round OR
2488 // - no other track is not ready
2489 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2490 mixerStatus != MIXER_TRACKS_ENABLED) {
2491 mixerStatus = MIXER_TRACKS_READY;
2492 }
Eric Laurenta553c252009-07-17 12:17:14 -07002493 } else {
Glenn Kasten68deb152011-12-19 15:06:39 -08002494 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002495 if (track->isStopped()) {
2496 track->reset();
2497 }
2498 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2499 // We have consumed all the buffers of this track.
2500 // Remove it from the list of active tracks.
2501 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002502 } else {
2503 // No buffers for this track. Give it a few chances to
2504 // fill a buffer, then remove it from active list.
2505 if (--(track->mRetryCount) <= 0) {
Glenn Kasten68deb152011-12-19 15:06:39 -08002506 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002507 tracksToRemove->add(track);
Eric Laurent4712baa2010-09-30 16:12:31 -07002508 // indicate to client process that the track was disabled because of underrun
Eric Laurentae29b762011-03-28 18:37:07 -07002509 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent71c44962012-01-17 19:20:12 -08002510 // If one track is not ready, mark the mixer also not ready if:
2511 // - the mixer was ready during previous round OR
2512 // - no other track is ready
2513 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2514 mixerStatus != MIXER_TRACKS_READY) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002515 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002516 }
Eric Laurenta553c252009-07-17 12:17:14 -07002517 }
Glenn Kasten68deb152011-12-19 15:06:39 -08002518 mAudioMixer->disable(name);
Eric Laurenta553c252009-07-17 12:17:14 -07002519 }
2520 }
2521
2522 // remove all the tracks that need to be...
2523 count = tracksToRemove->size();
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002524 if (CC_UNLIKELY(count)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002525 for (size_t i=0 ; i<count ; i++) {
2526 const sp<Track>& track = tracksToRemove->itemAt(i);
2527 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07002528 if (track->mainBuffer() != mMixBuffer) {
2529 chain = getEffectChain_l(track->sessionId());
2530 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002531 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002532 chain->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002533 }
2534 }
Eric Laurenta553c252009-07-17 12:17:14 -07002535 if (track->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002536 removeTrack_l(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002537 }
2538 }
2539 }
2540
Eric Laurent65b65452010-06-01 23:49:17 -07002541 // mix buffer must be cleared if all tracks are connected to an
2542 // effect chain as in this case the mixer will not write to
2543 // mix buffer and track effects will accumulate into it
2544 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2545 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2546 }
2547
Eric Laurent059b4be2009-11-09 23:32:22 -08002548 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07002549}
2550
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08002551void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07002552{
Steve Block71f2cf12011-10-20 11:56:00 +01002553 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002554 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07002555 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002556
Eric Laurenta553c252009-07-17 12:17:14 -07002557 size_t size = mTracks.size();
2558 for (size_t i = 0; i < size; i++) {
2559 sp<Track> t = mTracks[i];
Glenn Kastenaae26c82012-02-08 12:35:35 -08002560 if (t->streamType() == streamType) {
Eric Laurentae29b762011-03-28 18:37:07 -07002561 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Eric Laurenteb8f8502010-05-14 03:26:45 -07002562 t->mCblk->cv.signal();
Eric Laurenta553c252009-07-17 12:17:14 -07002563 }
Eric Laurent53334cd2010-06-23 17:38:20 -07002564 }
2565}
Eric Laurenta553c252009-07-17 12:17:14 -07002566
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08002567void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent05ce0942011-08-30 10:18:54 -07002568{
Steve Block71f2cf12011-10-20 11:56:00 +01002569 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent05ce0942011-08-30 10:18:54 -07002570 this, streamType, valid);
2571 Mutex::Autolock _l(mLock);
2572
2573 mStreamTypes[streamType].valid = valid;
2574}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575
Eric Laurenta553c252009-07-17 12:17:14 -07002576// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002577int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578{
2579 return mAudioMixer->getTrackName();
2580}
2581
Eric Laurenta553c252009-07-17 12:17:14 -07002582// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002583void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584{
Steve Block71f2cf12011-10-20 11:56:00 +01002585 ALOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 mAudioMixer->deleteTrackName(name);
2587}
2588
Eric Laurenta553c252009-07-17 12:17:14 -07002589// checkForNewParameters_l() must be called with ThreadBase::mLock held
2590bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591{
Eric Laurenta553c252009-07-17 12:17:14 -07002592 bool reconfig = false;
2593
Eric Laurent8fce46a2009-08-04 09:45:33 -07002594 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002595 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002596 String8 keyValuePair = mNewParameters[0];
2597 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002598 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002599
Eric Laurenta553c252009-07-17 12:17:14 -07002600 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2601 reconfig = true;
2602 }
2603 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten0a204ed2012-01-12 12:27:51 -08002604 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07002605 status = BAD_VALUE;
2606 } else {
2607 reconfig = true;
2608 }
2609 }
2610 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002611 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurenta553c252009-07-17 12:17:14 -07002612 status = BAD_VALUE;
2613 } else {
2614 reconfig = true;
2615 }
2616 }
2617 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2618 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kastene5fb2632011-12-14 10:28:06 -08002619 // size depends on frame count and correct behavior would not be guaranteed
Eric Laurenta553c252009-07-17 12:17:14 -07002620 // if frame count is changed after track creation
2621 if (!mTracks.isEmpty()) {
2622 status = INVALID_OPERATION;
2623 } else {
2624 reconfig = true;
2625 }
2626 }
Eric Laurent65b65452010-06-01 23:49:17 -07002627 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002628 // when changing the audio output device, call addBatteryData to notify
2629 // the change
Eric Laurent90681d62011-05-09 12:09:06 -07002630 if ((int)mDevice != value) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002631 uint32_t params = 0;
2632 // check whether speaker is on
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002633 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002634 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2635 }
2636
2637 int deviceWithoutSpeaker
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002638 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9b3f1522011-02-24 14:51:45 -08002639 // check if any other device (except speaker) is on
2640 if (value & deviceWithoutSpeaker ) {
2641 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2642 }
2643
2644 if (params != 0) {
2645 addBatteryData(params);
2646 }
2647 }
2648
Eric Laurent65b65452010-06-01 23:49:17 -07002649 // forward device change to effects that have requested to be
2650 // aware of attached audio device.
2651 mDevice = (uint32_t)value;
2652 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07002653 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07002654 }
2655 }
2656
Eric Laurenta553c252009-07-17 12:17:14 -07002657 if (status == NO_ERROR) {
Dima Zavin31f18882011-04-18 16:57:27 -07002658 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002659 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002660 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f18882011-04-18 16:57:27 -07002661 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002662 mStandby = true;
2663 mBytesWritten = 0;
Dima Zavin31f18882011-04-18 16:57:27 -07002664 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002665 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002666 }
2667 if (status == NO_ERROR && reconfig) {
2668 delete mAudioMixer;
Glenn Kasten2589cf92012-01-27 18:08:45 -08002669 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2670 mAudioMixer = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07002671 readOutputParameters();
2672 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2673 for (size_t i = 0; i < mTracks.size() ; i++) {
2674 int name = getTrackName_l();
2675 if (name < 0) break;
2676 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07002677 // limit track sample rate to 2 x new output sample rate
2678 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2679 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2680 }
Eric Laurenta553c252009-07-17 12:17:14 -07002681 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07002682 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002683 }
2684 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002685
2686 mNewParameters.removeAt(0);
2687
Eric Laurenta553c252009-07-17 12:17:14 -07002688 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002689 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002690 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2691 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002692 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07002693 }
2694 return reconfig;
2695}
2696
2697status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2698{
2699 const size_t SIZE = 256;
2700 char buffer[SIZE];
2701 String8 result;
2702
2703 PlaybackThread::dumpInternals(fd, args);
2704
2705 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2706 result.append(buffer);
2707 write(fd, result.string(), result.size());
2708 return NO_ERROR;
2709}
2710
Eric Laurent059b4be2009-11-09 23:32:22 -08002711uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2712{
Eric Laurenta54d7d32010-07-29 06:50:24 -07002713 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002714}
2715
Eric Laurent8448a792010-08-18 18:13:17 -07002716uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2717{
2718 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2719}
2720
Eric Laurenta553c252009-07-17 12:17:14 -07002721// ----------------------------------------------------------------------------
Glenn Kasten39d00cb2012-01-17 11:09:42 -08002722AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2723 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kastenefd511a2012-01-26 10:38:26 -08002724 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kastendc3ac852012-01-25 15:28:08 -08002725 // mLeftVolFloat, mRightVolFloat
2726 // mLeftVolShort, mRightVolShort
Eric Laurenta553c252009-07-17 12:17:14 -07002727{
Eric Laurenta553c252009-07-17 12:17:14 -07002728}
2729
2730AudioFlinger::DirectOutputThread::~DirectOutputThread()
2731{
2732}
2733
Glenn Kasten67cb3122012-03-01 17:10:56 -08002734void AudioFlinger::DirectOutputThread::applyVolume()
Eric Laurent65b65452010-06-01 23:49:17 -07002735{
2736 // Do not apply volume on compressed audio
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002737 if (!audio_is_linear_pcm(mFormat)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002738 return;
2739 }
2740
2741 // convert to signed 16 bit before volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002742 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002743 size_t count = mFrameCount * mChannelCount;
2744 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2745 int16_t *dst = mMixBuffer + count-1;
2746 while(count--) {
2747 *dst-- = (int16_t)(*src--^0x80) << 8;
2748 }
2749 }
2750
2751 size_t frameCount = mFrameCount;
2752 int16_t *out = mMixBuffer;
Glenn Kasten67cb3122012-03-01 17:10:56 -08002753 if (rampVolume) {
Eric Laurent65b65452010-06-01 23:49:17 -07002754 if (mChannelCount == 1) {
2755 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2756 int32_t vlInc = d / (int32_t)frameCount;
2757 int32_t vl = ((int32_t)mLeftVolShort << 16);
2758 do {
2759 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2760 out++;
2761 vl += vlInc;
2762 } while (--frameCount);
2763
2764 } else {
2765 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2766 int32_t vlInc = d / (int32_t)frameCount;
2767 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2768 int32_t vrInc = d / (int32_t)frameCount;
2769 int32_t vl = ((int32_t)mLeftVolShort << 16);
2770 int32_t vr = ((int32_t)mRightVolShort << 16);
2771 do {
2772 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2773 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2774 out += 2;
2775 vl += vlInc;
2776 vr += vrInc;
2777 } while (--frameCount);
2778 }
2779 } else {
2780 if (mChannelCount == 1) {
2781 do {
2782 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2783 out++;
2784 } while (--frameCount);
2785 } else {
2786 do {
2787 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2788 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2789 out += 2;
2790 } while (--frameCount);
2791 }
2792 }
2793
2794 // convert back to unsigned 8 bit after volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002795 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002796 size_t count = mFrameCount * mChannelCount;
2797 int16_t *src = mMixBuffer;
2798 uint8_t *dst = (uint8_t *)mMixBuffer;
2799 while(count--) {
2800 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2801 }
2802 }
2803
2804 mLeftVolShort = leftVol;
2805 mRightVolShort = rightVol;
2806}
2807
Glenn Kasten761415b2012-03-06 11:23:32 -08002808AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
2809 Vector< sp<Track> > *tracksToRemove
Glenn Kasten67cb3122012-03-01 17:10:56 -08002810)
Eric Laurenta553c252009-07-17 12:17:14 -07002811{
Glenn Kasten761415b2012-03-06 11:23:32 -08002812 sp<Track> trackToRemove;
2813
Glenn Kastena13446a2012-03-08 07:47:15 -08002814 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07002815
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002816 // find out which tracks need to be processed
2817 if (mActiveTracks.size() != 0) {
2818 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastena13446a2012-03-08 07:47:15 -08002819 // The track died recently
2820 if (t == 0) return MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002821
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002822 Track* const track = t.get();
2823 audio_track_cblk_t* cblk = track->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07002824
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002825 // The first time a track is added we wait
2826 // for all its buffers to be filled before processing it
2827 if (cblk->framesReady() && track->isReady() &&
2828 !track->isPaused() && !track->isTerminated())
2829 {
2830 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002831
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002832 if (track->mFillingUpStatus == Track::FS_FILLED) {
2833 track->mFillingUpStatus = Track::FS_ACTIVE;
2834 mLeftVolFloat = mRightVolFloat = 0;
2835 mLeftVolShort = mRightVolShort = 0;
2836 if (track->mState == TrackBase::RESUMING) {
2837 track->mState = TrackBase::ACTIVE;
2838 rampVolume = true;
2839 }
2840 } else if (cblk->server != 0) {
2841 // If the track is stopped before the first frame was mixed,
2842 // do not apply ramp
2843 rampVolume = true;
2844 }
2845 // compute volume for this track
2846 float left, right;
2847 if (track->isMuted() || mMasterMute || track->isPausing() ||
2848 mStreamTypes[track->streamType()].mute) {
2849 left = right = 0;
2850 if (track->isPausing()) {
2851 track->setPaused();
2852 }
2853 } else {
2854 float typeVolume = mStreamTypes[track->streamType()].volume;
2855 float v = mMasterVolume * typeVolume;
2856 uint32_t vlr = cblk->getVolumeLR();
2857 float v_clamped = v * (vlr & 0xFFFF);
2858 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2859 left = v_clamped/MAX_GAIN;
2860 v_clamped = v * (vlr >> 16);
2861 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2862 right = v_clamped/MAX_GAIN;
2863 }
Eric Laurenta553c252009-07-17 12:17:14 -07002864
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002865 if (left != mLeftVolFloat || right != mRightVolFloat) {
2866 mLeftVolFloat = left;
2867 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002868
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002869 // If audio HAL implements volume control,
2870 // force software volume to nominal value
2871 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
2872 left = 1.0f;
2873 right = 1.0f;
2874 }
Eric Laurent65b65452010-06-01 23:49:17 -07002875
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002876 // Convert volumes from float to 8.24
2877 uint32_t vl = (uint32_t)(left * (1 << 24));
2878 uint32_t vr = (uint32_t)(right * (1 << 24));
Eric Laurent65b65452010-06-01 23:49:17 -07002879
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002880 // Delegate volume control to effect in track effect chain if needed
2881 // only one effect chain can be present on DirectOutputThread, so if
2882 // there is one, the track is connected to it
2883 if (!mEffectChains.isEmpty()) {
2884 // Do not ramp volume if volume is controlled by effect
2885 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002886 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002887 }
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002888 }
Eric Laurenta553c252009-07-17 12:17:14 -07002889
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002890 // Convert volumes from 8.24 to 4.12 format
2891 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2892 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2893 leftVol = (uint16_t)v_clamped;
2894 v_clamped = (vr + (1 << 11)) >> 12;
2895 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2896 rightVol = (uint16_t)v_clamped;
2897 } else {
2898 leftVol = mLeftVolShort;
2899 rightVol = mRightVolShort;
2900 rampVolume = false;
2901 }
2902
2903 // reset retry count
2904 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb8f96762012-03-07 17:05:59 -08002905 mActiveTrack = t;
Glenn Kastena13446a2012-03-08 07:47:15 -08002906 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002907 } else {
2908 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2909 if (track->isStopped()) {
2910 track->reset();
2911 }
2912 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2913 // We have consumed all the buffers of this track.
2914 // Remove it from the list of active tracks.
2915 trackToRemove = track;
2916 } else {
2917 // No buffers for this track. Give it a few chances to
2918 // fill a buffer, then remove it from active list.
2919 if (--(track->mRetryCount) <= 0) {
2920 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2921 trackToRemove = track;
Eric Laurenta553c252009-07-17 12:17:14 -07002922 } else {
Glenn Kastena13446a2012-03-08 07:47:15 -08002923 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002924 }
2925 }
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002926 }
2927 }
Eric Laurenta553c252009-07-17 12:17:14 -07002928
Glenn Kasten761415b2012-03-06 11:23:32 -08002929 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002930 // remove all the tracks that need to be...
2931 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten761415b2012-03-06 11:23:32 -08002932 tracksToRemove->add(trackToRemove);
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002933 mActiveTracks.remove(trackToRemove);
2934 if (!mEffectChains.isEmpty()) {
2935 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2936 trackToRemove->sessionId());
2937 mEffectChains[0]->decActiveTrackCnt();
2938 }
2939 if (trackToRemove->isTerminated()) {
2940 removeTrack_l(trackToRemove);
2941 }
2942 }
Eric Laurent65b65452010-06-01 23:49:17 -07002943
Glenn Kastena13446a2012-03-08 07:47:15 -08002944 return mixerStatus;
Glenn Kasten67cb3122012-03-01 17:10:56 -08002945}
Eric Laurenta553c252009-07-17 12:17:14 -07002946
Glenn Kasten67cb3122012-03-01 17:10:56 -08002947void AudioFlinger::DirectOutputThread::threadLoop_mix()
2948{
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002949 AudioBufferProvider::Buffer buffer;
2950 size_t frameCount = mFrameCount;
2951 int8_t *curBuf = (int8_t *)mMixBuffer;
2952 // output audio to hardware
2953 while (frameCount) {
2954 buffer.frameCount = frameCount;
Glenn Kastenb8f96762012-03-07 17:05:59 -08002955 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002956 if (CC_UNLIKELY(buffer.raw == NULL)) {
2957 memset(curBuf, 0, frameCount * mFrameSize);
2958 break;
2959 }
2960 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2961 frameCount -= buffer.frameCount;
2962 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb8f96762012-03-07 17:05:59 -08002963 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002964 }
2965 sleepTime = 0;
2966 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb8f96762012-03-07 17:05:59 -08002967 mActiveTrack.clear();
Glenn Kastene0127832012-03-06 15:52:35 -08002968 applyVolume();
Glenn Kasten67cb3122012-03-01 17:10:56 -08002969}
2970
2971void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
2972{
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002973 if (sleepTime == 0) {
Glenn Kastena13446a2012-03-08 07:47:15 -08002974 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002975 sleepTime = activeSleepTime;
2976 } else {
2977 sleepTime = idleSleepTime;
2978 }
2979 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
2980 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2981 sleepTime = 0;
2982 }
Eric Laurenta553c252009-07-17 12:17:14 -07002983}
2984
2985// getTrackName_l() must be called with ThreadBase::mLock held
2986int AudioFlinger::DirectOutputThread::getTrackName_l()
2987{
2988 return 0;
2989}
2990
2991// deleteTrackName_l() must be called with ThreadBase::mLock held
2992void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2993{
2994}
2995
2996// checkForNewParameters_l() must be called with ThreadBase::mLock held
2997bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2998{
2999 bool reconfig = false;
3000
Eric Laurent8fce46a2009-08-04 09:45:33 -07003001 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07003002 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07003003 String8 keyValuePair = mNewParameters[0];
3004 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07003005 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07003006
Eric Laurenta553c252009-07-17 12:17:14 -07003007 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3008 // do not accept frame count changes if tracks are open as the track buffer
3009 // size depends on frame count and correct behavior would not be garantied
3010 // if frame count is changed after track creation
3011 if (!mTracks.isEmpty()) {
3012 status = INVALID_OPERATION;
3013 } else {
3014 reconfig = true;
3015 }
3016 }
3017 if (status == NO_ERROR) {
Dima Zavin31f18882011-04-18 16:57:27 -07003018 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003019 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07003020 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f18882011-04-18 16:57:27 -07003021 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07003022 mStandby = true;
3023 mBytesWritten = 0;
Dima Zavin31f18882011-04-18 16:57:27 -07003024 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003025 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07003026 }
3027 if (status == NO_ERROR && reconfig) {
3028 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07003029 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07003030 }
3031 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08003032
3033 mNewParameters.removeAt(0);
3034
Eric Laurenta553c252009-07-17 12:17:14 -07003035 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07003036 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07003037 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3038 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08003039 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07003040 }
3041 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08003042}
3043
Eric Laurent059b4be2009-11-09 23:32:22 -08003044uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07003045{
3046 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003047 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent44331692011-12-05 09:47:19 -08003048 time = PlaybackThread::activeSleepTimeUs();
Eric Laurent059b4be2009-11-09 23:32:22 -08003049 } else {
3050 time = 10000;
3051 }
3052 return time;
3053}
3054
3055uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
3056{
3057 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003058 if (audio_is_linear_pcm(mFormat)) {
Eric Laurenta54d7d32010-07-29 06:50:24 -07003059 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07003060 } else {
3061 time = 10000;
3062 }
3063 return time;
3064}
3065
Eric Laurent8448a792010-08-18 18:13:17 -07003066uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
3067{
3068 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003069 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent8448a792010-08-18 18:13:17 -07003070 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3071 } else {
3072 time = 10000;
3073 }
3074 return time;
3075}
3076
3077
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003078// ----------------------------------------------------------------------------
3079
Glenn Kastenefd511a2012-01-26 10:38:26 -08003080AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten39d00cb2012-01-17 11:09:42 -08003081 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kastenefd511a2012-01-26 10:38:26 -08003082 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3083 mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07003084{
Eric Laurenta553c252009-07-17 12:17:14 -07003085 addOutputTrack(mainThread);
3086}
3087
3088AudioFlinger::DuplicatingThread::~DuplicatingThread()
3089{
Eric Laurent0a080292009-12-07 10:53:10 -08003090 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3091 mOutputTracks[i]->destroy();
3092 }
Eric Laurenta553c252009-07-17 12:17:14 -07003093}
3094
Glenn Kasten67cb3122012-03-01 17:10:56 -08003095void AudioFlinger::DuplicatingThread::threadLoop_mix()
Eric Laurenta553c252009-07-17 12:17:14 -07003096{
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08003097 // mix buffers...
3098 if (outputsReady(outputTracks)) {
3099 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3100 } else {
3101 memset(mMixBuffer, 0, mixBufferSize);
3102 }
3103 sleepTime = 0;
3104 writeFrames = mFrameCount;
Glenn Kasten67cb3122012-03-01 17:10:56 -08003105}
3106
3107void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3108{
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08003109 if (sleepTime == 0) {
Glenn Kastena13446a2012-03-08 07:47:15 -08003110 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08003111 sleepTime = activeSleepTime;
3112 } else {
3113 sleepTime = idleSleepTime;
3114 }
3115 } else if (mBytesWritten != 0) {
3116 // flush remaining overflow buffers in output tracks
3117 for (size_t i = 0; i < outputTracks.size(); i++) {
3118 if (outputTracks[i]->isActive()) {
3119 sleepTime = 0;
3120 writeFrames = 0;
3121 memset(mMixBuffer, 0, mixBufferSize);
3122 break;
Eric Laurenta553c252009-07-17 12:17:14 -07003123 }
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08003124 }
3125 }
Glenn Kasten67cb3122012-03-01 17:10:56 -08003126}
Eric Laurentf69a3f82009-09-22 00:35:48 -07003127
Glenn Kasten67cb3122012-03-01 17:10:56 -08003128void AudioFlinger::DuplicatingThread::threadLoop_write()
3129{
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08003130 standbyTime = systemTime() + mStandbyTimeInNsecs;
3131 for (size_t i = 0; i < outputTracks.size(); i++) {
3132 outputTracks[i]->write(mMixBuffer, writeFrames);
3133 }
3134 mBytesWritten += mixBufferSize;
Glenn Kasten67cb3122012-03-01 17:10:56 -08003135}
Glenn Kastenbea6b952012-02-29 07:57:06 -08003136
Glenn Kasten67cb3122012-03-01 17:10:56 -08003137void AudioFlinger::DuplicatingThread::threadLoop_standby()
3138{
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08003139 // DuplicatingThread implements standby by stopping all tracks
3140 for (size_t i = 0; i < outputTracks.size(); i++) {
3141 outputTracks[i]->stop();
3142 }
Eric Laurenta553c252009-07-17 12:17:14 -07003143}
3144
Glenn Kasten08d2c042012-03-06 11:28:04 -08003145void AudioFlinger::DuplicatingThread::saveOutputTracks()
3146{
3147 outputTracks = mOutputTracks;
3148}
3149
3150void AudioFlinger::DuplicatingThread::clearOutputTracks()
3151{
3152 outputTracks.clear();
3153}
3154
Eric Laurenta553c252009-07-17 12:17:14 -07003155void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3156{
Glenn Kasten91540ae2012-02-24 14:12:20 -08003157 Mutex::Autolock _l(mLock);
Glenn Kastenb3db2132012-01-19 08:59:58 -08003158 // FIXME explain this formula
Eric Laurenta553c252009-07-17 12:17:14 -07003159 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten685c9ce2012-01-20 13:32:16 -08003160 OutputTrack *outputTrack = new OutputTrack(thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003161 this,
Eric Laurenta553c252009-07-17 12:17:14 -07003162 mSampleRate,
3163 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003164 mChannelMask,
Eric Laurenta553c252009-07-17 12:17:14 -07003165 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07003166 if (outputTrack->cblk() != NULL) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003167 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Eric Laurent6c30a712009-08-10 23:22:32 -07003168 mOutputTracks.add(outputTrack);
Steve Block71f2cf12011-10-20 11:56:00 +01003169 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten2bad67f2012-03-06 11:24:48 -08003170 updateWaitTime_l();
Eric Laurent6c30a712009-08-10 23:22:32 -07003171 }
Eric Laurenta553c252009-07-17 12:17:14 -07003172}
3173
3174void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3175{
3176 Mutex::Autolock _l(mLock);
3177 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kasten7d3be3a2012-01-26 10:53:32 -08003178 if (mOutputTracks[i]->thread() == thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07003179 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07003180 mOutputTracks.removeAt(i);
Glenn Kasten2bad67f2012-03-06 11:24:48 -08003181 updateWaitTime_l();
Eric Laurenta553c252009-07-17 12:17:14 -07003182 return;
3183 }
3184 }
Steve Block71f2cf12011-10-20 11:56:00 +01003185 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Eric Laurenta553c252009-07-17 12:17:14 -07003186}
3187
Glenn Kasten2bad67f2012-03-06 11:24:48 -08003188// caller must hold mLock
3189void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003190{
3191 mWaitTimeMs = UINT_MAX;
3192 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3193 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten706b6182012-01-20 13:44:40 -08003194 if (strong != 0) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003195 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3196 if (waitTimeMs < mWaitTimeMs) {
3197 mWaitTimeMs = waitTimeMs;
3198 }
3199 }
3200 }
3201}
3202
3203
Glenn Kasten0fccd352012-02-24 15:42:17 -08003204bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003205{
3206 for (size_t i = 0; i < outputTracks.size(); i++) {
3207 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3208 if (thread == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003209 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003210 return false;
3211 }
3212 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3213 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block71f2cf12011-10-20 11:56:00 +01003214 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003215 return false;
3216 }
3217 }
3218 return true;
3219}
3220
3221uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3222{
3223 return (mWaitTimeMs * 1000) / 2;
3224}
3225
Eric Laurenta553c252009-07-17 12:17:14 -07003226// ----------------------------------------------------------------------------
3227
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003228// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003229AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten685c9ce2012-01-20 13:32:16 -08003230 ThreadBase *thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003231 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003232 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08003233 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003234 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003235 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003236 const sp<IMemory>& sharedBuffer,
3237 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003238 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07003239 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003240 mClient(client),
Glenn Kastendc3ac852012-01-25 15:28:08 -08003241 mCblk(NULL),
3242 // mBuffer
3243 // mBufferEnd
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003244 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003245 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003246 mFormat(format),
Glenn Kasten35269822012-02-21 10:35:56 -08003247 mStepServerFailed(false),
Eric Laurent65b65452010-06-01 23:49:17 -07003248 mSessionId(sessionId)
Glenn Kastendc3ac852012-01-25 15:28:08 -08003249 // mChannelCount
3250 // mChannelMask
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003251{
Steve Block71f2cf12011-10-20 11:56:00 +01003252 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003253
Steve Block5baa3a62011-12-20 16:23:08 +00003254 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003255 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003256 uint8_t channelCount = popcount(channelMask);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003257 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3258 if (sharedBuffer == 0) {
3259 size += bufferSize;
3260 }
3261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003262 if (client != NULL) {
3263 mCblkMemory = client->heap()->allocate(size);
3264 if (mCblkMemory != 0) {
3265 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kasten3694ec12012-01-27 16:47:15 -08003266 if (mCblk != NULL) { // construct the shared structure in-place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003267 new(mCblk) audio_track_cblk_t();
3268 // clear all buffers
3269 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003270 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003271 mChannelCount = channelCount;
3272 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003273 if (sharedBuffer == 0) {
3274 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3275 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3276 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003277 // written to buffer (other flags are cleared)
Eric Laurenteb8f8502010-05-14 03:26:45 -07003278 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279 } else {
3280 mBuffer = sharedBuffer->pointer();
3281 }
3282 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284 } else {
Steve Block3762c312012-01-06 19:20:56 +00003285 ALOGE("not enough memory for AudioTrack size=%u", size);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003286 client->heap()->dump("AudioTrack");
3287 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 } else {
3290 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenc95ca2c2012-01-06 15:03:11 -08003291 // construct the shared structure in-place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003292 new(mCblk) audio_track_cblk_t();
3293 // clear all buffers
3294 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003295 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003296 mChannelCount = channelCount;
3297 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003298 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3299 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3300 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003301 // written to buffer (other flags are cleared)
Eric Laurenteb8f8502010-05-14 03:26:45 -07003302 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003304 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003305}
3306
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003307AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003308{
Glenn Kasten3694ec12012-01-27 16:47:15 -08003309 if (mCblk != NULL) {
Glenn Kastend9d68dc2012-02-03 10:24:48 -08003310 if (mClient == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003311 delete mCblk;
Glenn Kastend9d68dc2012-02-03 10:24:48 -08003312 } else {
3313 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Eric Laurenta553c252009-07-17 12:17:14 -07003314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 }
Glenn Kastenf31d0502012-01-25 15:27:15 -08003316 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten706b6182012-01-20 13:44:40 -08003317 if (mClient != 0) {
Glenn Kastendc3ac852012-01-25 15:28:08 -08003318 // Client destructor must run with AudioFlinger mutex locked
Eric Laurentb9481d82009-09-17 05:12:56 -07003319 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten706b6182012-01-20 13:44:40 -08003320 // If the client's reference count drops to zero, the associated destructor
3321 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3322 // relying on the automatic clear() at end of scope.
Eric Laurentb9481d82009-09-17 05:12:56 -07003323 mClient.clear();
3324 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003325}
3326
Glenn Kastenc2db1192012-02-22 10:47:35 -08003327// AudioBufferProvider interface
3328// getNextBuffer() = 0;
3329// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003330void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003331{
Glenn Kastenc434c902011-12-13 11:53:26 -08003332 buffer->raw = NULL;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003333 mFrameCount = buffer->frameCount;
Glenn Kastenc2db1192012-02-22 10:47:35 -08003334 (void) step(); // ignore return value of step()
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003335 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003336}
3337
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003338bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003339 bool result;
3340 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003341
3342 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003343 if (!result) {
Steve Block71f2cf12011-10-20 11:56:00 +01003344 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten35269822012-02-21 10:35:56 -08003345 mStepServerFailed = true;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003346 }
3347 return result;
3348}
3349
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003350void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003351 audio_track_cblk_t* cblk = this->cblk();
3352
3353 cblk->user = 0;
3354 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003355 cblk->userBase = 0;
3356 cblk->serverBase = 0;
Glenn Kasten35269822012-02-21 10:35:56 -08003357 mStepServerFailed = false;
Steve Block71f2cf12011-10-20 11:56:00 +01003358 ALOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003359}
3360
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003361int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07003362 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003363}
3364
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003365void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003366 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenfaf354d2012-01-11 09:48:27 -08003367 size_t frameSize = cblk->frameSize;
3368 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3369 int8_t *bufferEnd = bufferStart + frames * frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003370
3371 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07003372 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenfaf354d2012-01-11 09:48:27 -08003373 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block3762c312012-01-06 19:20:56 +00003374 ALOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003375 server %d, serverBase %d, user %d, userBase %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003376 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003377 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kasten3694ec12012-01-27 16:47:15 -08003378 return NULL;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003379 }
3380
3381 return bufferStart;
3382}
3383
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003384// ----------------------------------------------------------------------------
3385
Eric Laurenta553c252009-07-17 12:17:14 -07003386// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3387AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten685c9ce2012-01-20 13:32:16 -08003388 PlaybackThread *thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003389 const sp<Client>& client,
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08003390 audio_stream_type_t streamType,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003391 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08003392 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003393 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003394 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003395 const sp<IMemory>& sharedBuffer,
3396 int sessionId)
Glenn Kasten35269822012-02-21 10:35:56 -08003397 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Eric Laurenta92ebfa2010-08-31 13:50:07 -07003398 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3399 mAuxEffectId(0), mHasVolumeController(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003400{
Eric Laurent8a77a992009-09-09 05:16:08 -07003401 if (mCblk != NULL) {
Glenn Kasten685c9ce2012-01-20 13:32:16 -08003402 if (thread != NULL) {
3403 mName = thread->getTrackName_l();
3404 mMainBuffer = thread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07003405 }
Glenn Kasten7ed4f0c2012-02-03 11:10:00 -08003406 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurent8a77a992009-09-09 05:16:08 -07003407 if (mName < 0) {
Steve Block3762c312012-01-06 19:20:56 +00003408 ALOGE("no more track names available");
Eric Laurent8a77a992009-09-09 05:16:08 -07003409 }
Eric Laurent8a77a992009-09-09 05:16:08 -07003410 mStreamType = streamType;
3411 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3412 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurent09508612011-07-21 19:35:01 -07003413 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07003414 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003415}
3416
Eric Laurenta553c252009-07-17 12:17:14 -07003417AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003418{
Steve Block71f2cf12011-10-20 11:56:00 +01003419 ALOGV("PlaybackThread::Track destructor");
Eric Laurenta553c252009-07-17 12:17:14 -07003420 sp<ThreadBase> thread = mThread.promote();
3421 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003422 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003423 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003424 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003425}
3426
Eric Laurenta553c252009-07-17 12:17:14 -07003427void AudioFlinger::PlaybackThread::Track::destroy()
3428{
3429 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3430 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kastenb3db2132012-01-19 08:59:58 -08003431 // destructor is called. As the destructor needs to lock mLock,
Eric Laurenta553c252009-07-17 12:17:14 -07003432 // we must acquire a strong reference on this Track before locking mLock
3433 // here so that the destructor is called only when exiting this function.
3434 // On the other hand, as long as Track::destroy() is only called by
3435 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3436 // this Track with its member mTrack.
3437 sp<Track> keep(this);
3438 { // scope for mLock
3439 sp<ThreadBase> thread = mThread.promote();
3440 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003441 if (!isOutputTrack()) {
3442 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kastenaae26c82012-02-08 12:35:35 -08003443 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9b3f1522011-02-24 14:51:45 -08003444
3445 // to track the speaker usage
3446 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurentac196e12009-12-01 02:17:41 -08003447 }
3448 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08003449 }
Eric Laurenta553c252009-07-17 12:17:14 -07003450 Mutex::Autolock _l(thread->mLock);
3451 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3452 playbackThread->destroyTrack_l(this);
3453 }
3454 }
3455}
3456
3457void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003458{
Glenn Kastenbc4de882012-01-17 14:39:34 -08003459 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003460 snprintf(buffer, size, " %05d %05d %03u %03u 0x%08x %05u %04u %1d %1d %1d %05u %05u %05u 0x%08x 0x%08x 0x%08x 0x%08x\n",
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003461 mName - AudioMixer::TRACK0,
Glenn Kasten81211142012-02-05 18:09:08 -08003462 (mClient == 0) ? getpid_cached : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003463 mStreamType,
3464 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003465 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003466 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003467 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003468 mState,
3469 mMute,
3470 mFillingUpStatus,
3471 mCblk->sampleRate,
Glenn Kasten0632bad2012-01-17 12:20:54 -08003472 vlr & 0xFFFF,
3473 vlr >> 16,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003474 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07003475 mCblk->user,
3476 (int)mMainBuffer,
3477 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003478}
3479
Glenn Kastenc2db1192012-02-22 10:47:35 -08003480// AudioBufferProvider interface
John Grossmand8cf2962012-02-08 16:37:41 -08003481status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
3482 AudioBufferProvider::Buffer* buffer, int64_t pts)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003483{
3484 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003485 uint32_t framesReady;
3486 uint32_t framesReq = buffer->frameCount;
3487
3488 // Check if last stepServer failed, try to step now
Glenn Kasten35269822012-02-21 10:35:56 -08003489 if (mStepServerFailed) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003490 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003491 ALOGV("stepServer recovered");
Glenn Kasten35269822012-02-21 10:35:56 -08003492 mStepServerFailed = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003493 }
3494
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003495 framesReady = cblk->framesReady();
3496
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003497 if (CC_LIKELY(framesReady)) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003498 uint32_t s = cblk->server;
3499 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3500
3501 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3502 if (framesReq > framesReady) {
3503 framesReq = framesReady;
3504 }
3505 if (s + framesReq > bufferEnd) {
3506 framesReq = bufferEnd - s;
3507 }
3508
3509 buffer->raw = getBuffer(s, framesReq);
Glenn Kastenc434c902011-12-13 11:53:26 -08003510 if (buffer->raw == NULL) goto getNextBuffer_exit;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003511
3512 buffer->frameCount = framesReq;
3513 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003514 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003515
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003516getNextBuffer_exit:
Glenn Kastenc434c902011-12-13 11:53:26 -08003517 buffer->raw = NULL;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003518 buffer->frameCount = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01003519 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003520 return NOT_ENOUGH_DATA;
3521}
3522
John Grossmand8cf2962012-02-08 16:37:41 -08003523uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const{
3524 return mCblk->framesReady();
3525}
3526
Eric Laurenta553c252009-07-17 12:17:14 -07003527bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurent9a30fc12010-10-05 14:41:42 -07003528 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003529
John Grossmand8cf2962012-02-08 16:37:41 -08003530 if (framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f8502010-05-14 03:26:45 -07003531 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003532 mFillingUpStatus = FS_FILLED;
Eric Laurentae29b762011-03-28 18:37:07 -07003533 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003534 return true;
3535 }
3536 return false;
3537}
3538
Glenn Kasten6a20b262012-02-02 10:56:47 -08003539status_t AudioFlinger::PlaybackThread::Track::start(pid_t tid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003540{
Eric Laurent49f02be2009-11-19 09:00:56 -08003541 status_t status = NO_ERROR;
Glenn Kasten6a20b262012-02-02 10:56:47 -08003542 ALOGV("start(%d), calling pid %d session %d tid %d",
3543 mName, IPCThreadState::self()->getCallingPid(), mSessionId, tid);
Eric Laurenta553c252009-07-17 12:17:14 -07003544 sp<ThreadBase> thread = mThread.promote();
3545 if (thread != 0) {
3546 Mutex::Autolock _l(thread->mLock);
Glenn Kasten56356202012-01-26 13:39:18 -08003547 track_state state = mState;
Eric Laurent49f02be2009-11-19 09:00:56 -08003548 // here the track could be either new, or restarted
3549 // in both cases "unstop" the track
3550 if (mState == PAUSED) {
3551 mState = TrackBase::RESUMING;
Steve Block71f2cf12011-10-20 11:56:00 +01003552 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003553 } else {
3554 mState = TrackBase::ACTIVE;
Steve Block71f2cf12011-10-20 11:56:00 +01003555 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003556 }
3557
3558 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3559 thread->mLock.unlock();
Glenn Kastenaae26c82012-02-08 12:35:35 -08003560 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003561 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003562
3563 // to track the speaker usage
3564 if (status == NO_ERROR) {
3565 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3566 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003567 }
3568 if (status == NO_ERROR) {
3569 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3570 playbackThread->addTrack_l(this);
3571 } else {
3572 mState = state;
3573 }
3574 } else {
3575 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003576 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003577 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003578}
3579
Eric Laurenta553c252009-07-17 12:17:14 -07003580void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003581{
Glenn Kasten7ed4f0c2012-02-03 11:10:00 -08003582 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003583 sp<ThreadBase> thread = mThread.promote();
3584 if (thread != 0) {
3585 Mutex::Autolock _l(thread->mLock);
Glenn Kasten56356202012-01-26 13:39:18 -08003586 track_state state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07003587 if (mState > STOPPED) {
3588 mState = STOPPED;
3589 // If the track is not active (PAUSED and buffers full), flush buffers
3590 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3591 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3592 reset();
3593 }
Steve Block71f2cf12011-10-20 11:56:00 +01003594 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003595 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003596 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3597 thread->mLock.unlock();
Glenn Kastenaae26c82012-02-08 12:35:35 -08003598 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003599 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003600
3601 // to track the speaker usage
3602 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003603 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003604 }
3605}
3606
Eric Laurenta553c252009-07-17 12:17:14 -07003607void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003608{
Glenn Kasten7ed4f0c2012-02-03 11:10:00 -08003609 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003610 sp<ThreadBase> thread = mThread.promote();
3611 if (thread != 0) {
3612 Mutex::Autolock _l(thread->mLock);
3613 if (mState == ACTIVE || mState == RESUMING) {
3614 mState = PAUSING;
Steve Block71f2cf12011-10-20 11:56:00 +01003615 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003616 if (!isOutputTrack()) {
3617 thread->mLock.unlock();
Glenn Kastenaae26c82012-02-08 12:35:35 -08003618 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003619 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003620
3621 // to track the speaker usage
3622 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003623 }
Eric Laurenta553c252009-07-17 12:17:14 -07003624 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003625 }
3626}
3627
Eric Laurenta553c252009-07-17 12:17:14 -07003628void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003629{
Steve Block71f2cf12011-10-20 11:56:00 +01003630 ALOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003631 sp<ThreadBase> thread = mThread.promote();
3632 if (thread != 0) {
3633 Mutex::Autolock _l(thread->mLock);
3634 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3635 return;
3636 }
3637 // No point remaining in PAUSED state after a flush => go to
3638 // STOPPED state
3639 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003640
Eric Laurentae29b762011-03-28 18:37:07 -07003641 // do not reset the track if it is still in the process of being stopped or paused.
3642 // this will be done by prepareTracks_l() when the track is stopped.
3643 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3644 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3645 reset();
3646 }
Eric Laurenta553c252009-07-17 12:17:14 -07003647 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003648}
3649
Eric Laurenta553c252009-07-17 12:17:14 -07003650void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003651{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003652 // Do not reset twice to avoid discarding data written just after a flush and before
3653 // the audioflinger thread detects the track is stopped.
3654 if (!mResetDone) {
3655 TrackBase::reset();
3656 // Force underrun condition to avoid false underrun callback until first data is
3657 // written to buffer
Eric Laurentae29b762011-03-28 18:37:07 -07003658 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3659 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003660 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003661 mResetDone = true;
3662 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003663}
3664
Eric Laurenta553c252009-07-17 12:17:14 -07003665void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003666{
3667 mMute = muted;
3668}
3669
Eric Laurent65b65452010-06-01 23:49:17 -07003670status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3671{
3672 status_t status = DEAD_OBJECT;
3673 sp<ThreadBase> thread = mThread.promote();
3674 if (thread != 0) {
3675 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3676 status = playbackThread->attachAuxEffect(this, EffectId);
3677 }
3678 return status;
3679}
3680
3681void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3682{
3683 mAuxEffectId = EffectId;
3684 mAuxBuffer = buffer;
3685}
3686
John Grossmand8cf2962012-02-08 16:37:41 -08003687// timed audio tracks
3688
3689sp<AudioFlinger::PlaybackThread::TimedTrack>
3690AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten685c9ce2012-01-20 13:32:16 -08003691 PlaybackThread *thread,
John Grossmand8cf2962012-02-08 16:37:41 -08003692 const sp<Client>& client,
3693 audio_stream_type_t streamType,
3694 uint32_t sampleRate,
3695 audio_format_t format,
3696 uint32_t channelMask,
3697 int frameCount,
3698 const sp<IMemory>& sharedBuffer,
3699 int sessionId) {
3700 if (!client->reserveTimedTrack())
3701 return NULL;
3702
3703 sp<TimedTrack> track = new TimedTrack(
3704 thread, client, streamType, sampleRate, format, channelMask, frameCount,
3705 sharedBuffer, sessionId);
3706
3707 if (track == NULL) {
3708 client->releaseTimedTrack();
3709 return NULL;
3710 }
3711
3712 return track;
3713}
3714
3715AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten685c9ce2012-01-20 13:32:16 -08003716 PlaybackThread *thread,
John Grossmand8cf2962012-02-08 16:37:41 -08003717 const sp<Client>& client,
3718 audio_stream_type_t streamType,
3719 uint32_t sampleRate,
3720 audio_format_t format,
3721 uint32_t channelMask,
3722 int frameCount,
3723 const sp<IMemory>& sharedBuffer,
3724 int sessionId)
3725 : Track(thread, client, streamType, sampleRate, format, channelMask,
3726 frameCount, sharedBuffer, sessionId),
3727 mTimedSilenceBuffer(NULL),
3728 mTimedSilenceBufferSize(0),
3729 mTimedAudioOutputOnTime(false),
3730 mMediaTimeTransformValid(false)
3731{
3732 LocalClock lc;
3733 mLocalTimeFreq = lc.getLocalFreq();
3734
3735 mLocalTimeToSampleTransform.a_zero = 0;
3736 mLocalTimeToSampleTransform.b_zero = 0;
3737 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3738 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3739 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3740 &mLocalTimeToSampleTransform.a_to_b_denom);
3741}
3742
3743AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3744 mClient->releaseTimedTrack();
3745 delete [] mTimedSilenceBuffer;
3746}
3747
3748status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3749 size_t size, sp<IMemory>* buffer) {
3750
3751 Mutex::Autolock _l(mTimedBufferQueueLock);
3752
3753 trimTimedBufferQueue_l();
3754
3755 // lazily initialize the shared memory heap for timed buffers
3756 if (mTimedMemoryDealer == NULL) {
3757 const int kTimedBufferHeapSize = 512 << 10;
3758
3759 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3760 "AudioFlingerTimed");
3761 if (mTimedMemoryDealer == NULL)
3762 return NO_MEMORY;
3763 }
3764
3765 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3766 if (newBuffer == NULL) {
3767 newBuffer = mTimedMemoryDealer->allocate(size);
3768 if (newBuffer == NULL)
3769 return NO_MEMORY;
3770 }
3771
3772 *buffer = newBuffer;
3773 return NO_ERROR;
3774}
3775
3776// caller must hold mTimedBufferQueueLock
3777void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
3778 int64_t mediaTimeNow;
3779 {
3780 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3781 if (!mMediaTimeTransformValid)
3782 return;
3783
3784 int64_t targetTimeNow;
3785 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
3786 ? mCCHelper.getCommonTime(&targetTimeNow)
3787 : mCCHelper.getLocalTime(&targetTimeNow);
3788
3789 if (OK != res)
3790 return;
3791
3792 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
3793 &mediaTimeNow)) {
3794 return;
3795 }
3796 }
3797
3798 size_t trimIndex;
3799 for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
3800 if (mTimedBufferQueue[trimIndex].pts() > mediaTimeNow)
3801 break;
3802 }
3803
3804 if (trimIndex) {
3805 mTimedBufferQueue.removeItemsAt(0, trimIndex);
3806 }
3807}
3808
3809status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
3810 const sp<IMemory>& buffer, int64_t pts) {
3811
3812 {
3813 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3814 if (!mMediaTimeTransformValid)
3815 return INVALID_OPERATION;
3816 }
3817
3818 Mutex::Autolock _l(mTimedBufferQueueLock);
3819
3820 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
3821
3822 return NO_ERROR;
3823}
3824
3825status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
3826 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
3827
3828 ALOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
3829 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
3830 target);
3831
3832 if (!(target == TimedAudioTrack::LOCAL_TIME ||
3833 target == TimedAudioTrack::COMMON_TIME)) {
3834 return BAD_VALUE;
3835 }
3836
3837 Mutex::Autolock lock(mMediaTimeTransformLock);
3838 mMediaTimeTransform = xform;
3839 mMediaTimeTransformTarget = target;
3840 mMediaTimeTransformValid = true;
3841
3842 return NO_ERROR;
3843}
3844
3845#define min(a, b) ((a) < (b) ? (a) : (b))
3846
3847// implementation of getNextBuffer for tracks whose buffers have timestamps
3848status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
3849 AudioBufferProvider::Buffer* buffer, int64_t pts)
3850{
3851 if (pts == AudioBufferProvider::kInvalidPTS) {
3852 buffer->raw = 0;
3853 buffer->frameCount = 0;
3854 return INVALID_OPERATION;
3855 }
3856
John Grossmand8cf2962012-02-08 16:37:41 -08003857 Mutex::Autolock _l(mTimedBufferQueueLock);
3858
3859 while (true) {
3860
3861 // if we have no timed buffers, then fail
3862 if (mTimedBufferQueue.isEmpty()) {
3863 buffer->raw = 0;
3864 buffer->frameCount = 0;
3865 return NOT_ENOUGH_DATA;
3866 }
3867
3868 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
3869
3870 // calculate the PTS of the head of the timed buffer queue expressed in
3871 // local time
3872 int64_t headLocalPTS;
3873 {
3874 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3875
3876 assert(mMediaTimeTransformValid);
3877
3878 if (mMediaTimeTransform.a_to_b_denom == 0) {
3879 // the transform represents a pause, so yield silence
3880 timedYieldSilence(buffer->frameCount, buffer);
3881 return NO_ERROR;
3882 }
3883
3884 int64_t transformedPTS;
3885 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
3886 &transformedPTS)) {
3887 // the transform failed. this shouldn't happen, but if it does
3888 // then just drop this buffer
3889 ALOGW("timedGetNextBuffer transform failed");
3890 buffer->raw = 0;
3891 buffer->frameCount = 0;
3892 mTimedBufferQueue.removeAt(0);
3893 return NO_ERROR;
3894 }
3895
3896 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
3897 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
3898 &headLocalPTS)) {
3899 buffer->raw = 0;
3900 buffer->frameCount = 0;
3901 return INVALID_OPERATION;
3902 }
3903 } else {
3904 headLocalPTS = transformedPTS;
3905 }
3906 }
3907
3908 // adjust the head buffer's PTS to reflect the portion of the head buffer
3909 // that has already been consumed
3910 int64_t effectivePTS = headLocalPTS +
3911 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
3912
3913 // Calculate the delta in samples between the head of the input buffer
3914 // queue and the start of the next output buffer that will be written.
3915 // If the transformation fails because of over or underflow, it means
3916 // that the sample's position in the output stream is so far out of
3917 // whack that it should just be dropped.
3918 int64_t sampleDelta;
3919 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
3920 ALOGV("*** head buffer is too far from PTS: dropped buffer");
3921 mTimedBufferQueue.removeAt(0);
3922 continue;
3923 }
3924 if (!mLocalTimeToSampleTransform.doForwardTransform(
3925 (effectivePTS - pts) << 32, &sampleDelta)) {
3926 ALOGV("*** too late during sample rate transform: dropped buffer");
3927 mTimedBufferQueue.removeAt(0);
3928 continue;
3929 }
3930
3931 ALOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
3932 __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
3933 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
3934 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
3935
3936 // if the delta between the ideal placement for the next input sample and
3937 // the current output position is within this threshold, then we will
3938 // concatenate the next input samples to the previous output
3939 const int64_t kSampleContinuityThreshold =
3940 (static_cast<int64_t>(sampleRate()) << 32) / 10;
3941
3942 // if this is the first buffer of audio that we're emitting from this track
3943 // then it should be almost exactly on time.
3944 const int64_t kSampleStartupThreshold = 1LL << 32;
3945
3946 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
3947 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
3948 // the next input is close enough to being on time, so concatenate it
3949 // with the last output
3950 timedYieldSamples(buffer);
3951
3952 ALOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
3953 return NO_ERROR;
3954 } else if (sampleDelta > 0) {
3955 // the gap between the current output position and the proper start of
3956 // the next input sample is too big, so fill it with silence
3957 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
3958
3959 timedYieldSilence(framesUntilNextInput, buffer);
3960 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
3961 return NO_ERROR;
3962 } else {
3963 // the next input sample is late
3964 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
3965 size_t onTimeSamplePosition =
3966 head.position() + lateFrames * mCblk->frameSize;
3967
3968 if (onTimeSamplePosition > head.buffer()->size()) {
3969 // all the remaining samples in the head are too late, so
3970 // drop it and move on
3971 ALOGV("*** too late: dropped buffer");
3972 mTimedBufferQueue.removeAt(0);
3973 continue;
3974 } else {
3975 // skip over the late samples
3976 head.setPosition(onTimeSamplePosition);
3977
3978 // yield the available samples
3979 timedYieldSamples(buffer);
3980
3981 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
3982 return NO_ERROR;
3983 }
3984 }
3985 }
3986}
3987
3988// Yield samples from the timed buffer queue head up to the given output
3989// buffer's capacity.
3990//
3991// Caller must hold mTimedBufferQueueLock
3992void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples(
3993 AudioBufferProvider::Buffer* buffer) {
3994
3995 const TimedBuffer& head = mTimedBufferQueue[0];
3996
3997 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
3998 head.position());
3999
4000 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4001 mCblk->frameSize);
4002 size_t framesRequested = buffer->frameCount;
4003 buffer->frameCount = min(framesLeftInHead, framesRequested);
4004
4005 mTimedAudioOutputOnTime = true;
4006}
4007
4008// Yield samples of silence up to the given output buffer's capacity
4009//
4010// Caller must hold mTimedBufferQueueLock
4011void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence(
4012 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4013
4014 // lazily allocate a buffer filled with silence
4015 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4016 delete [] mTimedSilenceBuffer;
4017 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4018 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4019 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4020 }
4021
4022 buffer->raw = mTimedSilenceBuffer;
4023 size_t framesRequested = buffer->frameCount;
4024 buffer->frameCount = min(numFrames, framesRequested);
4025
4026 mTimedAudioOutputOnTime = false;
4027}
4028
Glenn Kastenc2db1192012-02-22 10:47:35 -08004029// AudioBufferProvider interface
John Grossmand8cf2962012-02-08 16:37:41 -08004030void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4031 AudioBufferProvider::Buffer* buffer) {
4032
4033 Mutex::Autolock _l(mTimedBufferQueueLock);
4034
John Grossman8c010612012-02-12 17:51:21 -08004035 // If the buffer which was just released is part of the buffer at the head
4036 // of the queue, be sure to update the amt of the buffer which has been
4037 // consumed. If the buffer being returned is not part of the head of the
4038 // queue, its either because the buffer is part of the silence buffer, or
4039 // because the head of the timed queue was trimmed after the mixer called
4040 // getNextBuffer but before the mixer called releaseBuffer.
4041 if ((buffer->raw != mTimedSilenceBuffer) && mTimedBufferQueue.size()) {
John Grossmand8cf2962012-02-08 16:37:41 -08004042 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossman8c010612012-02-12 17:51:21 -08004043
4044 void* start = head.buffer()->pointer();
Glenn Kasten175b2be2012-02-17 16:24:10 -08004045 void* end = (char *) head.buffer()->pointer() + head.buffer()->size();
John Grossman8c010612012-02-12 17:51:21 -08004046
4047 if ((buffer->raw >= start) && (buffer->raw <= end)) {
4048 head.setPosition(head.position() +
4049 (buffer->frameCount * mCblk->frameSize));
4050 if (static_cast<size_t>(head.position()) >= head.buffer()->size()) {
4051 mTimedBufferQueue.removeAt(0);
4052 }
John Grossmand8cf2962012-02-08 16:37:41 -08004053 }
4054 }
4055
4056 buffer->raw = 0;
4057 buffer->frameCount = 0;
4058}
4059
4060uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4061 Mutex::Autolock _l(mTimedBufferQueueLock);
4062
4063 uint32_t frames = 0;
4064 for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4065 const TimedBuffer& tb = mTimedBufferQueue[i];
4066 frames += (tb.buffer()->size() - tb.position()) / mCblk->frameSize;
4067 }
4068
4069 return frames;
4070}
4071
4072AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4073 : mPTS(0), mPosition(0) {}
4074
4075AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4076 const sp<IMemory>& buffer, int64_t pts)
4077 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4078
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004079// ----------------------------------------------------------------------------
4080
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004081// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07004082AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten685c9ce2012-01-20 13:32:16 -08004083 RecordThread *thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004085 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004086 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004087 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004088 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07004089 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07004090 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten35269822012-02-21 10:35:56 -08004091 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07004092 mOverflow(false)
4093{
Eric Laurent8a77a992009-09-09 05:16:08 -07004094 if (mCblk != NULL) {
Steve Block71f2cf12011-10-20 11:56:00 +01004095 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004096 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004097 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004098 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004099 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Eric Laurent8a77a992009-09-09 05:16:08 -07004100 } else {
4101 mCblk->frameSize = sizeof(int8_t);
4102 }
4103 }
Eric Laurenta553c252009-07-17 12:17:14 -07004104}
4105
4106AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004107{
Eric Laurent49f02be2009-11-19 09:00:56 -08004108 sp<ThreadBase> thread = mThread.promote();
4109 if (thread != 0) {
4110 AudioSystem::releaseInput(thread->id());
4111 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004112}
4113
Glenn Kastenc2db1192012-02-22 10:47:35 -08004114// AudioBufferProvider interface
John Grossmand8cf2962012-02-08 16:37:41 -08004115status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004116{
4117 audio_track_cblk_t* cblk = this->cblk();
4118 uint32_t framesAvail;
4119 uint32_t framesReq = buffer->frameCount;
4120
4121 // Check if last stepServer failed, try to step now
Glenn Kasten35269822012-02-21 10:35:56 -08004122 if (mStepServerFailed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004123 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01004124 ALOGV("stepServer recovered");
Glenn Kasten35269822012-02-21 10:35:56 -08004125 mStepServerFailed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004126 }
4127
4128 framesAvail = cblk->framesAvailable_l();
4129
Glenn Kastene80a4cc2011-12-15 09:51:17 -08004130 if (CC_LIKELY(framesAvail)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004131 uint32_t s = cblk->server;
4132 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4133
4134 if (framesReq > framesAvail) {
4135 framesReq = framesAvail;
4136 }
4137 if (s + framesReq > bufferEnd) {
4138 framesReq = bufferEnd - s;
4139 }
4140
4141 buffer->raw = getBuffer(s, framesReq);
Glenn Kastenc434c902011-12-13 11:53:26 -08004142 if (buffer->raw == NULL) goto getNextBuffer_exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004143
4144 buffer->frameCount = framesReq;
4145 return NO_ERROR;
4146 }
4147
4148getNextBuffer_exit:
Glenn Kastenc434c902011-12-13 11:53:26 -08004149 buffer->raw = NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150 buffer->frameCount = 0;
4151 return NOT_ENOUGH_DATA;
4152}
4153
Glenn Kasten6a20b262012-02-02 10:56:47 -08004154status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155{
Eric Laurenta553c252009-07-17 12:17:14 -07004156 sp<ThreadBase> thread = mThread.promote();
4157 if (thread != 0) {
4158 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten6a20b262012-02-02 10:56:47 -08004159 return recordThread->start(this, tid);
Eric Laurent49f02be2009-11-19 09:00:56 -08004160 } else {
4161 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07004162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004163}
4164
Eric Laurenta553c252009-07-17 12:17:14 -07004165void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004166{
Eric Laurenta553c252009-07-17 12:17:14 -07004167 sp<ThreadBase> thread = mThread.promote();
4168 if (thread != 0) {
4169 RecordThread *recordThread = (RecordThread *)thread.get();
4170 recordThread->stop(this);
Eric Laurentae29b762011-03-28 18:37:07 -07004171 TrackBase::reset();
4172 // Force overerrun condition to avoid false overrun callback until first data is
4173 // read from buffer
4174 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07004175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004176}
4177
Eric Laurent3fdb1262009-11-07 00:01:32 -08004178void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4179{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004180 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten81211142012-02-05 18:09:08 -08004181 (mClient == 0) ? getpid_cached : mClient->pid(),
Eric Laurent3fdb1262009-11-07 00:01:32 -08004182 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004183 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07004184 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08004185 mFrameCount,
4186 mState,
4187 mCblk->sampleRate,
4188 mCblk->server,
4189 mCblk->user);
4190}
4191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004192
4193// ----------------------------------------------------------------------------
4194
Eric Laurenta553c252009-07-17 12:17:14 -07004195AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten685c9ce2012-01-20 13:32:16 -08004196 PlaybackThread *playbackThread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08004197 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004198 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004199 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004200 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004201 int frameCount)
Glenn Kasten685c9ce2012-01-20 13:32:16 -08004202 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08004203 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004204{
Eric Laurenta553c252009-07-17 12:17:14 -07004205
Eric Laurent6c30a712009-08-10 23:22:32 -07004206 if (mCblk != NULL) {
Eric Laurenteb8f8502010-05-14 03:26:45 -07004207 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07004208 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Eric Laurent6c30a712009-08-10 23:22:32 -07004209 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07004210 playbackThread->mTracks.add(this);
Steve Block71f2cf12011-10-20 11:56:00 +01004211 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004212 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4213 mCblk, mBuffer, mCblk->buffers,
4214 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07004215 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00004216 ALOGW("Error creating output track on thread %p", playbackThread);
Eric Laurent6c30a712009-08-10 23:22:32 -07004217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004218}
4219
Eric Laurenta553c252009-07-17 12:17:14 -07004220AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004221{
Eric Laurent6c30a712009-08-10 23:22:32 -07004222 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004223}
4224
Glenn Kasten6a20b262012-02-02 10:56:47 -08004225status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004226{
Glenn Kasten6a20b262012-02-02 10:56:47 -08004227 status_t status = Track::start(tid);
Eric Laurenta553c252009-07-17 12:17:14 -07004228 if (status != NO_ERROR) {
4229 return status;
4230 }
4231
4232 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004233 mRetryCount = 127;
4234 return status;
4235}
4236
Eric Laurenta553c252009-07-17 12:17:14 -07004237void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004238{
4239 Track::stop();
4240 clearBufferQueue();
4241 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004242 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004243}
4244
Eric Laurenta553c252009-07-17 12:17:14 -07004245bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004246{
4247 Buffer *pInBuffer;
4248 Buffer inBuffer;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004249 uint32_t channelCount = mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07004250 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004251 inBuffer.frameCount = frames;
4252 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07004253
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08004254 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07004255
Eric Laurent62443f52009-10-05 20:29:18 -07004256 if (!mActive && frames != 0) {
Glenn Kasten6a20b262012-02-02 10:56:47 -08004257 start(0);
Eric Laurenta553c252009-07-17 12:17:14 -07004258 sp<ThreadBase> thread = mThread.promote();
4259 if (thread != 0) {
4260 MixerThread *mixerThread = (MixerThread *)thread.get();
4261 if (mCblk->frameCount > frames){
4262 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4263 uint32_t startFrames = (mCblk->frameCount - frames);
4264 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07004265 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07004266 pInBuffer->frameCount = startFrames;
4267 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07004268 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07004269 mBufferQueue.add(pInBuffer);
4270 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00004271 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurenta553c252009-07-17 12:17:14 -07004272 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004273 }
Eric Laurenta553c252009-07-17 12:17:14 -07004274 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004275 }
4276
Eric Laurenta553c252009-07-17 12:17:14 -07004277 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004278 // First write pending buffers, then new data
4279 if (mBufferQueue.size()) {
4280 pInBuffer = mBufferQueue.itemAt(0);
4281 } else {
4282 pInBuffer = &inBuffer;
4283 }
Eric Laurenta553c252009-07-17 12:17:14 -07004284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004285 if (pInBuffer->frameCount == 0) {
4286 break;
4287 }
Eric Laurenta553c252009-07-17 12:17:14 -07004288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004289 if (mOutBuffer.frameCount == 0) {
4290 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07004291 nsecs_t startTime = systemTime();
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08004292 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block71f2cf12011-10-20 11:56:00 +01004293 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07004294 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004295 break;
4296 }
Eric Laurenta553c252009-07-17 12:17:14 -07004297 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07004298 if (waitTimeLeftMs >= waitTimeMs) {
4299 waitTimeLeftMs -= waitTimeMs;
4300 } else {
4301 waitTimeLeftMs = 0;
4302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004303 }
Eric Laurenta553c252009-07-17 12:17:14 -07004304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004305 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07004306 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004307 mCblk->stepUser(outFrames);
4308 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07004309 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004310 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07004311 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07004312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004313 if (pInBuffer->frameCount == 0) {
4314 if (mBufferQueue.size()) {
4315 mBufferQueue.removeAt(0);
4316 delete [] pInBuffer->mBuffer;
4317 delete pInBuffer;
Steve Block71f2cf12011-10-20 11:56:00 +01004318 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004319 } else {
4320 break;
4321 }
4322 }
4323 }
Eric Laurenta553c252009-07-17 12:17:14 -07004324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004325 // If we could not write all frames, allocate a buffer and queue it for next time.
4326 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08004327 sp<ThreadBase> thread = mThread.promote();
4328 if (thread != 0 && !thread->standby()) {
4329 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4330 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07004331 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08004332 pInBuffer->frameCount = inBuffer.frameCount;
4333 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07004334 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08004335 mBufferQueue.add(pInBuffer);
Steve Block71f2cf12011-10-20 11:56:00 +01004336 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08004337 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00004338 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08004339 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004340 }
4341 }
Eric Laurenta553c252009-07-17 12:17:14 -07004342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004343 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07004344 // If no more buffers are pending, fill output track buffer to make sure it is started
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004345 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07004346 if (frames == 0 && mBufferQueue.size() == 0) {
4347 if (mCblk->user < mCblk->frameCount) {
4348 frames = mCblk->frameCount - mCblk->user;
4349 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07004350 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07004351 pInBuffer->frameCount = frames;
4352 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07004353 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07004354 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07004355 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07004356 stop();
4357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004358 }
4359
Eric Laurenta553c252009-07-17 12:17:14 -07004360 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004361}
4362
Eric Laurenta553c252009-07-17 12:17:14 -07004363status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004364{
4365 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004366 status_t result;
4367 audio_track_cblk_t* cblk = mCblk;
4368 uint32_t framesReq = buffer->frameCount;
4369
Steve Block71f2cf12011-10-20 11:56:00 +01004370// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004371 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004373 uint32_t framesAvail = cblk->framesAvailable();
4374
Eric Laurenta553c252009-07-17 12:17:14 -07004375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004376 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004377 Mutex::Autolock _l(cblk->lock);
4378 goto start_loop_here;
4379 while (framesAvail == 0) {
4380 active = mActive;
Glenn Kastene80a4cc2011-12-15 09:51:17 -08004381 if (CC_UNLIKELY(!active)) {
Steve Block71f2cf12011-10-20 11:56:00 +01004382 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08004383 return NO_MORE_BUFFERS;
Eric Laurenta553c252009-07-17 12:17:14 -07004384 }
4385 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4386 if (result != NO_ERROR) {
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08004387 return NO_MORE_BUFFERS;
Eric Laurenta553c252009-07-17 12:17:14 -07004388 }
4389 // read the server count again
4390 start_loop_here:
4391 framesAvail = cblk->framesAvailable_l();
4392 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004393 }
4394
Eric Laurenta553c252009-07-17 12:17:14 -07004395// if (framesAvail < framesReq) {
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08004396// return NO_MORE_BUFFERS;
Eric Laurenta553c252009-07-17 12:17:14 -07004397// }
4398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004399 if (framesReq > framesAvail) {
4400 framesReq = framesAvail;
4401 }
4402
4403 uint32_t u = cblk->user;
4404 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4405
4406 if (u + framesReq > bufferEnd) {
4407 framesReq = bufferEnd - u;
4408 }
4409
4410 buffer->frameCount = framesReq;
4411 buffer->raw = (void *)cblk->buffer(u);
4412 return NO_ERROR;
4413}
4414
4415
Eric Laurenta553c252009-07-17 12:17:14 -07004416void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004417{
4418 size_t size = mBufferQueue.size();
Eric Laurenta553c252009-07-17 12:17:14 -07004419
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004420 for (size_t i = 0; i < size; i++) {
Glenn Kasten7d3be3a2012-01-26 10:53:32 -08004421 Buffer *pBuffer = mBufferQueue.itemAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004422 delete [] pBuffer->mBuffer;
4423 delete pBuffer;
4424 }
4425 mBufferQueue.clear();
4426}
4427
4428// ----------------------------------------------------------------------------
4429
4430AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4431 : RefBase(),
4432 mAudioFlinger(audioFlinger),
Glenn Kastenb3db2132012-01-19 08:59:58 -08004433 // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below
Mathias Agopian6faf7892010-01-25 19:00:00 -08004434 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossmand8cf2962012-02-08 16:37:41 -08004435 mPid(pid),
4436 mTimedTrackCount(0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004437{
4438 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4439}
4440
Eric Laurentb9481d82009-09-17 05:12:56 -07004441// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004442AudioFlinger::Client::~Client()
4443{
Eric Laurentb9481d82009-09-17 05:12:56 -07004444 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004445}
4446
Glenn Kasten1f812f72012-01-30 10:15:48 -08004447sp<MemoryDealer> AudioFlinger::Client::heap() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004448{
4449 return mMemoryDealer;
4450}
4451
John Grossmand8cf2962012-02-08 16:37:41 -08004452// Reserve one of the limited slots for a timed audio track associated
4453// with this client
4454bool AudioFlinger::Client::reserveTimedTrack()
4455{
4456 const int kMaxTimedTracksPerClient = 4;
4457
4458 Mutex::Autolock _l(mTimedTrackLock);
4459
4460 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4461 ALOGW("can not create timed track - pid %d has exceeded the limit",
4462 mPid);
4463 return false;
4464 }
4465
4466 mTimedTrackCount++;
4467 return true;
4468}
4469
4470// Release a slot for a timed audio track
4471void AudioFlinger::Client::releaseTimedTrack()
4472{
4473 Mutex::Autolock _l(mTimedTrackLock);
4474 mTimedTrackCount--;
4475}
4476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004477// ----------------------------------------------------------------------------
4478
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004479AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4480 const sp<IAudioFlingerClient>& client,
4481 pid_t pid)
Glenn Kastendc3ac852012-01-25 15:28:08 -08004482 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004483{
4484}
4485
4486AudioFlinger::NotificationClient::~NotificationClient()
4487{
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004488}
4489
4490void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4491{
4492 sp<NotificationClient> keep(this);
Glenn Kasten7d3be3a2012-01-26 10:53:32 -08004493 mAudioFlinger->removeNotificationClient(mPid);
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004494}
4495
4496// ----------------------------------------------------------------------------
4497
Eric Laurenta553c252009-07-17 12:17:14 -07004498AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004499 : BnAudioTrack(),
4500 mTrack(track)
4501{
4502}
4503
4504AudioFlinger::TrackHandle::~TrackHandle() {
4505 // just stop the track on deletion, associated resources
4506 // will be freed from the main thread once all pending buffers have
4507 // been played. Unless it's not in the active track list, in which
4508 // case we free everything now...
4509 mTrack->destroy();
4510}
4511
Glenn Kasten0ae4d972012-01-26 13:40:12 -08004512sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4513 return mTrack->getCblk();
4514}
4515
Glenn Kasten6a20b262012-02-02 10:56:47 -08004516status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4517 return mTrack->start(tid);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004518}
4519
4520void AudioFlinger::TrackHandle::stop() {
4521 mTrack->stop();
4522}
4523
4524void AudioFlinger::TrackHandle::flush() {
4525 mTrack->flush();
4526}
4527
4528void AudioFlinger::TrackHandle::mute(bool e) {
4529 mTrack->mute(e);
4530}
4531
4532void AudioFlinger::TrackHandle::pause() {
4533 mTrack->pause();
4534}
4535
Eric Laurent65b65452010-06-01 23:49:17 -07004536status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4537{
4538 return mTrack->attachAuxEffect(EffectId);
4539}
4540
John Grossmand8cf2962012-02-08 16:37:41 -08004541status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4542 sp<IMemory>* buffer) {
4543 if (!mTrack->isTimedTrack())
4544 return INVALID_OPERATION;
4545
4546 PlaybackThread::TimedTrack* tt =
4547 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4548 return tt->allocateTimedBuffer(size, buffer);
4549}
4550
4551status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4552 int64_t pts) {
4553 if (!mTrack->isTimedTrack())
4554 return INVALID_OPERATION;
4555
4556 PlaybackThread::TimedTrack* tt =
4557 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4558 return tt->queueTimedBuffer(buffer, pts);
4559}
4560
4561status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4562 const LinearTransform& xform, int target) {
4563
4564 if (!mTrack->isTimedTrack())
4565 return INVALID_OPERATION;
4566
4567 PlaybackThread::TimedTrack* tt =
4568 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4569 return tt->setMediaTimeTransform(
4570 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4571}
4572
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004573status_t AudioFlinger::TrackHandle::onTransact(
4574 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4575{
4576 return BnAudioTrack::onTransact(code, data, reply, flags);
4577}
4578
4579// ----------------------------------------------------------------------------
4580
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004581sp<IAudioRecord> AudioFlinger::openRecord(
4582 pid_t pid,
Glenn Kasten39d00cb2012-01-17 11:09:42 -08004583 audio_io_handle_t input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004584 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004585 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004586 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004587 int frameCount,
Glenn Kasten35269822012-02-21 10:35:56 -08004588 // FIXME dead, remove from IAudioFlinger
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004589 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07004590 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004591 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004592{
Eric Laurenta553c252009-07-17 12:17:14 -07004593 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004594 sp<RecordHandle> recordHandle;
4595 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004596 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07004597 RecordThread *thread;
4598 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07004599 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004600
4601 // check calling permissions
4602 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004603 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004604 goto Exit;
4605 }
4606
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004607 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004608 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004609 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004610 thread = checkRecordThread_l(input);
4611 if (thread == NULL) {
4612 lStatus = BAD_VALUE;
4613 goto Exit;
4614 }
4615
Glenn Kasten803a86a2012-01-25 14:28:29 -08004616 client = registerPid_l(pid);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004617
Eric Laurent65b65452010-06-01 23:49:17 -07004618 // If no audio session id is provided, create one here
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004619 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07004620 lSessionId = *sessionId;
4621 } else {
Eric Laurent464d5b32011-06-17 21:29:58 -07004622 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004623 if (sessionId != NULL) {
4624 *sessionId = lSessionId;
4625 }
4626 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004627 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent464d5b32011-06-17 21:29:58 -07004628 recordTrack = thread->createRecordTrack_l(client,
4629 sampleRate,
4630 format,
4631 channelMask,
4632 frameCount,
Eric Laurent464d5b32011-06-17 21:29:58 -07004633 lSessionId,
4634 &lStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004635 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004636 if (lStatus != NO_ERROR) {
Eric Laurentb9481d82009-09-17 05:12:56 -07004637 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4638 // destructor is called by the TrackBase destructor with mLock held
4639 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004640 recordTrack.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004641 goto Exit;
4642 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004643
4644 // return to handle to client
4645 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004646 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004647
4648Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004649 if (status) {
4650 *status = lStatus;
4651 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004652 return recordHandle;
4653}
4654
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004655// ----------------------------------------------------------------------------
4656
Eric Laurenta553c252009-07-17 12:17:14 -07004657AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004658 : BnAudioRecord(),
4659 mRecordTrack(recordTrack)
4660{
4661}
4662
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004663AudioFlinger::RecordHandle::~RecordHandle() {
4664 stop();
4665}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004666
Glenn Kasten0ae4d972012-01-26 13:40:12 -08004667sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4668 return mRecordTrack->getCblk();
4669}
4670
Glenn Kasten6a20b262012-02-02 10:56:47 -08004671status_t AudioFlinger::RecordHandle::start(pid_t tid) {
Steve Block71f2cf12011-10-20 11:56:00 +01004672 ALOGV("RecordHandle::start()");
Glenn Kasten6a20b262012-02-02 10:56:47 -08004673 return mRecordTrack->start(tid);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004674}
4675
4676void AudioFlinger::RecordHandle::stop() {
Steve Block71f2cf12011-10-20 11:56:00 +01004677 ALOGV("RecordHandle::stop()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004678 mRecordTrack->stop();
4679}
4680
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004681status_t AudioFlinger::RecordHandle::onTransact(
4682 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4683{
4684 return BnAudioRecord::onTransact(code, data, reply, flags);
4685}
4686
4687// ----------------------------------------------------------------------------
4688
Eric Laurent464d5b32011-06-17 21:29:58 -07004689AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4690 AudioStreamIn *input,
4691 uint32_t sampleRate,
4692 uint32_t channels,
Glenn Kasten39d00cb2012-01-17 11:09:42 -08004693 audio_io_handle_t id,
Eric Laurent464d5b32011-06-17 21:29:58 -07004694 uint32_t device) :
Glenn Kastenefd511a2012-01-26 10:38:26 -08004695 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kastendc3ac852012-01-25 15:28:08 -08004696 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4697 // mRsmpInIndex and mInputBytes set by readInputParameters()
4698 mReqChannelCount(popcount(channels)),
4699 mReqSampleRate(sampleRate)
4700 // mBytesRead is only meaningful while active, and so is cleared in start()
4701 // (but might be better to also clear here for dump?)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004702{
Glenn Kasten86e33622012-02-28 12:30:08 -08004703 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurent6dbdc402011-07-22 09:04:31 -07004704
Eric Laurenta553c252009-07-17 12:17:14 -07004705 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004706}
4707
Eric Laurenta553c252009-07-17 12:17:14 -07004708
4709AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004710{
Eric Laurenta553c252009-07-17 12:17:14 -07004711 delete[] mRsmpInBuffer;
Glenn Kasten2589cf92012-01-27 18:08:45 -08004712 delete mResampler;
4713 delete[] mRsmpOutBuffer;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004714}
4715
Eric Laurenta553c252009-07-17 12:17:14 -07004716void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004717{
Eric Laurent6dbdc402011-07-22 09:04:31 -07004718 run(mName, PRIORITY_URGENT_AUDIO);
Eric Laurenta553c252009-07-17 12:17:14 -07004719}
Eric Laurent49f02be2009-11-19 09:00:56 -08004720
Eric Laurent828b9772011-08-07 16:32:26 -07004721status_t AudioFlinger::RecordThread::readyToRun()
4722{
4723 status_t status = initCheck();
Steve Block8564c8d2012-01-05 23:22:43 +00004724 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurent828b9772011-08-07 16:32:26 -07004725 return status;
4726}
4727
Eric Laurenta553c252009-07-17 12:17:14 -07004728bool AudioFlinger::RecordThread::threadLoop()
4729{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004730 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004731 sp<RecordTrack> activeTrack;
Eric Laurent464d5b32011-06-17 21:29:58 -07004732 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004733
Eric Laurent4712baa2010-09-30 16:12:31 -07004734 nsecs_t lastWarning = 0;
4735
Eric Laurent6dbdc402011-07-22 09:04:31 -07004736 acquireWakeLock();
4737
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004738 // start recording
4739 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004740
Eric Laurenta553c252009-07-17 12:17:14 -07004741 processConfigEvents();
4742
4743 { // scope for mLock
4744 Mutex::Autolock _l(mLock);
4745 checkForNewParameters_l();
4746 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4747 if (!mStandby) {
Dima Zavin31f18882011-04-18 16:57:27 -07004748 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004749 mStandby = true;
4750 }
4751
4752 if (exitPending()) break;
4753
Eric Laurent6dbdc402011-07-22 09:04:31 -07004754 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01004755 ALOGV("RecordThread: loop stopping");
Eric Laurenta553c252009-07-17 12:17:14 -07004756 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004757 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01004758 ALOGV("RecordThread: loop starting");
Eric Laurent6dbdc402011-07-22 09:04:31 -07004759 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004760 continue;
4761 }
4762 if (mActiveTrack != 0) {
4763 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08004764 if (!mStandby) {
Dima Zavin31f18882011-04-18 16:57:27 -07004765 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent9cc489a2009-12-05 05:20:01 -08004766 mStandby = true;
4767 }
Eric Laurenta553c252009-07-17 12:17:14 -07004768 mActiveTrack.clear();
4769 mStartStopCond.broadcast();
4770 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07004771 if (mReqChannelCount != mActiveTrack->channelCount()) {
4772 mActiveTrack.clear();
Eric Laurent9cc489a2009-12-05 05:20:01 -08004773 mStartStopCond.broadcast();
4774 } else if (mBytesRead != 0) {
4775 // record start succeeds only if first read from audio input
4776 // succeeds
4777 if (mBytesRead > 0) {
4778 mActiveTrack->mState = TrackBase::ACTIVE;
4779 } else {
4780 mActiveTrack.clear();
4781 }
4782 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07004783 }
Eric Laurent9cc489a2009-12-05 05:20:01 -08004784 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07004785 }
Eric Laurenta553c252009-07-17 12:17:14 -07004786 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004787 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07004788 }
4789
4790 if (mActiveTrack != 0) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08004791 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4792 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004793 unlockEffectChains(effectChains);
4794 usleep(kRecordThreadSleepUs);
Eric Laurent49f02be2009-11-19 09:00:56 -08004795 continue;
4796 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004797 for (size_t i = 0; i < effectChains.size(); i ++) {
4798 effectChains[i]->process_l();
4799 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004800
Eric Laurenta553c252009-07-17 12:17:14 -07004801 buffer.frameCount = mFrameCount;
Glenn Kastenc2db1192012-02-22 10:47:35 -08004802 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004803 size_t framesOut = buffer.frameCount;
Glenn Kastenc434c902011-12-13 11:53:26 -08004804 if (mResampler == NULL) {
Eric Laurenta553c252009-07-17 12:17:14 -07004805 // no resampling
4806 while (framesOut) {
4807 size_t framesIn = mFrameCount - mRsmpInIndex;
4808 if (framesIn) {
4809 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4810 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4811 if (framesIn > framesOut)
4812 framesIn = framesOut;
4813 mRsmpInIndex += framesIn;
4814 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07004815 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004816 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07004817 memcpy(dst, src, framesIn * mFrameSize);
4818 } else {
4819 int16_t *src16 = (int16_t *)src;
4820 int16_t *dst16 = (int16_t *)dst;
4821 if (mChannelCount == 1) {
4822 while (framesIn--) {
4823 *dst16++ = *src16;
4824 *dst16++ = *src16++;
4825 }
4826 } else {
4827 while (framesIn--) {
4828 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4829 src16 += 2;
4830 }
4831 }
4832 }
4833 }
4834 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07004835 if (framesOut == mFrameCount &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004836 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin31f18882011-04-18 16:57:27 -07004837 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004838 framesOut = 0;
4839 } else {
Dima Zavin31f18882011-04-18 16:57:27 -07004840 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004841 mRsmpInIndex = 0;
4842 }
Eric Laurent9cc489a2009-12-05 05:20:01 -08004843 if (mBytesRead < 0) {
Steve Block3762c312012-01-06 19:20:56 +00004844 ALOGE("Error reading audio input");
Eric Laurent9cc489a2009-12-05 05:20:01 -08004845 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004846 // Force input into standby so that it tries to
4847 // recover at next read attempt
Dima Zavin31f18882011-04-18 16:57:27 -07004848 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004849 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a2009-12-05 05:20:01 -08004850 }
Eric Laurenta553c252009-07-17 12:17:14 -07004851 mRsmpInIndex = mFrameCount;
4852 framesOut = 0;
4853 buffer.frameCount = 0;
4854 }
4855 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004856 }
4857 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07004858 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004859
Eric Laurenta553c252009-07-17 12:17:14 -07004860 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4861 // alter output frame count as if we were expecting stereo samples
4862 if (mChannelCount == 1 && mReqChannelCount == 1) {
4863 framesOut >>= 1;
4864 }
4865 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4866 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4867 // are 32 bit aligned which should be always true.
4868 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten490909d2011-12-15 09:52:39 -08004869 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Eric Laurenta553c252009-07-17 12:17:14 -07004870 // the resampler always outputs stereo samples: do post stereo to mono conversion
4871 int16_t *src = (int16_t *)mRsmpOutBuffer;
4872 int16_t *dst = buffer.i16;
4873 while (framesOut--) {
4874 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4875 src += 2;
4876 }
4877 } else {
Glenn Kasten490909d2011-12-15 09:52:39 -08004878 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Eric Laurenta553c252009-07-17 12:17:14 -07004879 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004880
Eric Laurenta553c252009-07-17 12:17:14 -07004881 }
4882 mActiveTrack->releaseBuffer(&buffer);
4883 mActiveTrack->overflow();
4884 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004885 // client isn't retrieving buffers fast enough
4886 else {
Eric Laurent4712baa2010-09-30 16:12:31 -07004887 if (!mActiveTrack->setOverflow()) {
4888 nsecs_t now = systemTime();
Glenn Kastencbfe2e12011-12-13 11:04:14 -08004889 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block8564c8d2012-01-05 23:22:43 +00004890 ALOGW("RecordThread: buffer overflow");
Eric Laurent4712baa2010-09-30 16:12:31 -07004891 lastWarning = now;
4892 }
4893 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004894 // Release the processor for a while before asking for a new buffer.
4895 // This will give the application more chance to read from the buffer and
4896 // clear the overflow.
Eric Laurent464d5b32011-06-17 21:29:58 -07004897 usleep(kRecordThreadSleepUs);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004898 }
4899 }
Eric Laurent21b5c472011-07-26 20:54:46 -07004900 // enable changes in effect chain
4901 unlockEffectChains(effectChains);
Eric Laurent464d5b32011-06-17 21:29:58 -07004902 effectChains.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004903 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004904
Eric Laurenta553c252009-07-17 12:17:14 -07004905 if (!mStandby) {
Dima Zavin31f18882011-04-18 16:57:27 -07004906 mInput->stream->common.standby(&mInput->stream->common);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004907 }
Eric Laurenta553c252009-07-17 12:17:14 -07004908 mActiveTrack.clear();
4909
Eric Laurent49f02be2009-11-19 09:00:56 -08004910 mStartStopCond.broadcast();
4911
Eric Laurent6dbdc402011-07-22 09:04:31 -07004912 releaseWakeLock();
4913
Steve Block71f2cf12011-10-20 11:56:00 +01004914 ALOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004915 return false;
4916}
4917
Eric Laurent464d5b32011-06-17 21:29:58 -07004918
4919sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4920 const sp<AudioFlinger::Client>& client,
4921 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004922 audio_format_t format,
Eric Laurent464d5b32011-06-17 21:29:58 -07004923 int channelMask,
4924 int frameCount,
Eric Laurent464d5b32011-06-17 21:29:58 -07004925 int sessionId,
4926 status_t *status)
4927{
4928 sp<RecordTrack> track;
4929 status_t lStatus;
4930
4931 lStatus = initCheck();
4932 if (lStatus != NO_ERROR) {
Steve Block3762c312012-01-06 19:20:56 +00004933 ALOGE("Audio driver not initialized.");
Eric Laurent464d5b32011-06-17 21:29:58 -07004934 goto Exit;
4935 }
4936
4937 { // scope for mLock
4938 Mutex::Autolock _l(mLock);
4939
4940 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten35269822012-02-21 10:35:56 -08004941 format, channelMask, frameCount, sessionId);
Eric Laurent464d5b32011-06-17 21:29:58 -07004942
Glenn Kasten706b6182012-01-20 13:44:40 -08004943 if (track->getCblk() == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004944 lStatus = NO_MEMORY;
4945 goto Exit;
4946 }
4947
4948 mTrack = track.get();
Eric Laurent6639b552011-08-01 09:52:20 -07004949 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4950 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004951 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004952 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4953 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent464d5b32011-06-17 21:29:58 -07004954 }
4955 lStatus = NO_ERROR;
4956
4957Exit:
4958 if (status) {
4959 *status = lStatus;
4960 }
4961 return track;
4962}
4963
Glenn Kasten6a20b262012-02-02 10:56:47 -08004964status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, pid_t tid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004965{
Glenn Kasten6a20b262012-02-02 10:56:47 -08004966 ALOGV("RecordThread::start tid=%d", tid);
Eric Laurent49f02be2009-11-19 09:00:56 -08004967 sp <ThreadBase> strongMe = this;
4968 status_t status = NO_ERROR;
4969 {
Glenn Kasten325ee1c2012-01-05 15:41:56 -08004970 AutoMutex lock(mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08004971 if (mActiveTrack != 0) {
4972 if (recordTrack != mActiveTrack.get()) {
4973 status = -EBUSY;
4974 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08004975 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08004976 }
4977 return status;
4978 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004979
Eric Laurent49f02be2009-11-19 09:00:56 -08004980 recordTrack->mState = TrackBase::IDLE;
4981 mActiveTrack = recordTrack;
4982 mLock.unlock();
4983 status_t status = AudioSystem::startInput(mId);
4984 mLock.lock();
4985 if (status != NO_ERROR) {
4986 mActiveTrack.clear();
4987 return status;
4988 }
Eric Laurent9cc489a2009-12-05 05:20:01 -08004989 mRsmpInIndex = mFrameCount;
4990 mBytesRead = 0;
Eric Laurent4bb21c42011-02-28 16:52:51 -08004991 if (mResampler != NULL) {
4992 mResampler->reset();
4993 }
4994 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent49f02be2009-11-19 09:00:56 -08004995 // signal thread to start
Steve Block71f2cf12011-10-20 11:56:00 +01004996 ALOGV("Signal record thread");
Eric Laurent49f02be2009-11-19 09:00:56 -08004997 mWaitWorkCV.signal();
4998 // do not wait for mStartStopCond if exiting
Glenn Kasten761286f2012-01-06 08:39:38 -08004999 if (exitPending()) {
Eric Laurent49f02be2009-11-19 09:00:56 -08005000 mActiveTrack.clear();
5001 status = INVALID_OPERATION;
5002 goto startError;
5003 }
5004 mStartStopCond.wait(mLock);
5005 if (mActiveTrack == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01005006 ALOGV("Record failed to start");
Eric Laurent49f02be2009-11-19 09:00:56 -08005007 status = BAD_VALUE;
5008 goto startError;
5009 }
Steve Block71f2cf12011-10-20 11:56:00 +01005010 ALOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08005011 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07005012 }
Eric Laurent49f02be2009-11-19 09:00:56 -08005013startError:
5014 AudioSystem::stopInput(mId);
5015 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07005016}
5017
Eric Laurenta553c252009-07-17 12:17:14 -07005018void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block71f2cf12011-10-20 11:56:00 +01005019 ALOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08005020 sp <ThreadBase> strongMe = this;
5021 {
Glenn Kasten325ee1c2012-01-05 15:41:56 -08005022 AutoMutex lock(mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08005023 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5024 mActiveTrack->mState = TrackBase::PAUSING;
5025 // do not wait for mStartStopCond if exiting
Glenn Kasten761286f2012-01-06 08:39:38 -08005026 if (exitPending()) {
Eric Laurent49f02be2009-11-19 09:00:56 -08005027 return;
5028 }
5029 mStartStopCond.wait(mLock);
5030 // if we have been restarted, recordTrack == mActiveTrack.get() here
5031 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5032 mLock.unlock();
5033 AudioSystem::stopInput(mId);
5034 mLock.lock();
Steve Block71f2cf12011-10-20 11:56:00 +01005035 ALOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08005036 }
5037 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07005038 }
5039}
5040
Eric Laurenta553c252009-07-17 12:17:14 -07005041status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005042{
5043 const size_t SIZE = 256;
5044 char buffer[SIZE];
5045 String8 result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005046
Eric Laurent3fdb1262009-11-07 00:01:32 -08005047 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5048 result.append(buffer);
5049
5050 if (mActiveTrack != 0) {
5051 result.append("Active Track:\n");
Jean-Michel Trivi54392232011-05-24 15:53:33 -07005052 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08005053 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005054 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08005055
5056 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5057 result.append(buffer);
5058 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5059 result.append(buffer);
Glenn Kastenc434c902011-12-13 11:53:26 -08005060 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Eric Laurent3fdb1262009-11-07 00:01:32 -08005061 result.append(buffer);
5062 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5063 result.append(buffer);
5064 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5065 result.append(buffer);
5066
5067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005068 } else {
5069 result.append("No record client\n");
5070 }
5071 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08005072
5073 dumpBase(fd, args);
Eric Laurent1345d332011-07-24 17:49:51 -07005074 dumpEffectChains(fd, args);
Eric Laurent3fdb1262009-11-07 00:01:32 -08005075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005076 return NO_ERROR;
5077}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07005078
Glenn Kastenc2db1192012-02-22 10:47:35 -08005079// AudioBufferProvider interface
John Grossmand8cf2962012-02-08 16:37:41 -08005080status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Eric Laurenta553c252009-07-17 12:17:14 -07005081{
5082 size_t framesReq = buffer->frameCount;
5083 size_t framesReady = mFrameCount - mRsmpInIndex;
5084 int channelCount;
5085
5086 if (framesReady == 0) {
Dima Zavin31f18882011-04-18 16:57:27 -07005087 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurent9cc489a2009-12-05 05:20:01 -08005088 if (mBytesRead < 0) {
Steve Block3762c312012-01-06 19:20:56 +00005089 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a2009-12-05 05:20:01 -08005090 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08005091 // Force input into standby so that it tries to
5092 // recover at next read attempt
Dima Zavin31f18882011-04-18 16:57:27 -07005093 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07005094 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a2009-12-05 05:20:01 -08005095 }
Glenn Kastenc434c902011-12-13 11:53:26 -08005096 buffer->raw = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07005097 buffer->frameCount = 0;
5098 return NOT_ENOUGH_DATA;
5099 }
5100 mRsmpInIndex = 0;
5101 framesReady = mFrameCount;
5102 }
5103
5104 if (framesReq > framesReady) {
5105 framesReq = framesReady;
5106 }
5107
5108 if (mChannelCount == 1 && mReqChannelCount == 2) {
5109 channelCount = 1;
5110 } else {
5111 channelCount = 2;
5112 }
5113 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5114 buffer->frameCount = framesReq;
5115 return NO_ERROR;
5116}
5117
Glenn Kastenc2db1192012-02-22 10:47:35 -08005118// AudioBufferProvider interface
Eric Laurenta553c252009-07-17 12:17:14 -07005119void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5120{
5121 mRsmpInIndex += buffer->frameCount;
5122 buffer->frameCount = 0;
5123}
5124
5125bool AudioFlinger::RecordThread::checkForNewParameters_l()
5126{
5127 bool reconfig = false;
5128
Eric Laurent8fce46a2009-08-04 09:45:33 -07005129 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07005130 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07005131 String8 keyValuePair = mNewParameters[0];
5132 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07005133 int value;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005134 audio_format_t reqFormat = mFormat;
Eric Laurenta553c252009-07-17 12:17:14 -07005135 int reqSamplingRate = mReqSampleRate;
5136 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07005137
Eric Laurenta553c252009-07-17 12:17:14 -07005138 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5139 reqSamplingRate = value;
5140 reconfig = true;
5141 }
5142 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005143 reqFormat = (audio_format_t) value;
Eric Laurenta553c252009-07-17 12:17:14 -07005144 reconfig = true;
5145 }
5146 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005147 reqChannelCount = popcount(value);
Eric Laurenta553c252009-07-17 12:17:14 -07005148 reconfig = true;
5149 }
5150 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5151 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kastenb3db2132012-01-19 08:59:58 -08005152 // size depends on frame count and correct behavior would not be guaranteed
Eric Laurenta553c252009-07-17 12:17:14 -07005153 // if frame count is changed after track creation
5154 if (mActiveTrack != 0) {
5155 status = INVALID_OPERATION;
5156 } else {
5157 reconfig = true;
5158 }
5159 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005160 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5161 // forward device change to effects that have requested to be
5162 // aware of attached audio device.
5163 for (size_t i = 0; i < mEffectChains.size(); i++) {
5164 mEffectChains[i]->setDevice_l(value);
5165 }
5166 // store input device and output device but do not forward output device to audio HAL.
5167 // Note that status is ignored by the caller for output device
5168 // (see AudioFlinger::setParameters()
5169 if (value & AUDIO_DEVICE_OUT_ALL) {
5170 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5171 status = BAD_VALUE;
5172 } else {
5173 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent6639b552011-08-01 09:52:20 -07005174 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5175 if (mTrack != NULL) {
5176 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07005177 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07005178 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5179 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5180 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005181 }
5182 mDevice |= (uint32_t)value;
5183 }
Eric Laurenta553c252009-07-17 12:17:14 -07005184 if (status == NO_ERROR) {
Dima Zavin31f18882011-04-18 16:57:27 -07005185 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07005186 if (status == INVALID_OPERATION) {
Dima Zavin31f18882011-04-18 16:57:27 -07005187 mInput->stream->common.standby(&mInput->stream->common);
5188 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07005189 }
5190 if (reconfig) {
5191 if (status == BAD_VALUE &&
Dima Zavin31f18882011-04-18 16:57:27 -07005192 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005193 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin31f18882011-04-18 16:57:27 -07005194 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kastend8f32c22012-03-08 12:32:47 -08005195 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
5196 (reqChannelCount <= FCC_2)) {
Eric Laurenta553c252009-07-17 12:17:14 -07005197 status = NO_ERROR;
5198 }
5199 if (status == NO_ERROR) {
5200 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07005201 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07005202 }
5203 }
5204 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08005205
5206 mNewParameters.removeAt(0);
5207
Eric Laurenta553c252009-07-17 12:17:14 -07005208 mParamStatus = status;
5209 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07005210 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5211 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08005212 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07005213 }
5214 return reconfig;
5215}
5216
5217String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5218{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005219 char *s;
Eric Laurent828b9772011-08-07 16:32:26 -07005220 String8 out_s8 = String8();
5221
5222 Mutex::Autolock _l(mLock);
5223 if (initCheck() != NO_ERROR) {
5224 return out_s8;
5225 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005226
Dima Zavin31f18882011-04-18 16:57:27 -07005227 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005228 out_s8 = String8(s);
5229 free(s);
5230 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07005231}
5232
Eric Laurenteb8f8502010-05-14 03:26:45 -07005233void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07005234 AudioSystem::OutputDescriptor desc;
Glenn Kasten3694ec12012-01-27 16:47:15 -08005235 void *param2 = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07005236
5237 switch (event) {
5238 case AudioSystem::INPUT_OPENED:
5239 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07005240 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07005241 desc.samplingRate = mSampleRate;
5242 desc.format = mFormat;
5243 desc.frameCount = mFrameCount;
5244 desc.latency = 0;
5245 param2 = &desc;
5246 break;
5247
5248 case AudioSystem::INPUT_CLOSED:
5249 default:
5250 break;
5251 }
Eric Laurent49f02be2009-11-19 09:00:56 -08005252 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07005253}
5254
5255void AudioFlinger::RecordThread::readInputParameters()
5256{
Glenn Kasten2589cf92012-01-27 18:08:45 -08005257 delete mRsmpInBuffer;
5258 // mRsmpInBuffer is always assigned a new[] below
5259 delete mRsmpOutBuffer;
5260 mRsmpOutBuffer = NULL;
5261 delete mResampler;
Glenn Kastenc434c902011-12-13 11:53:26 -08005262 mResampler = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07005263
Dima Zavin31f18882011-04-18 16:57:27 -07005264 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07005265 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5266 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f18882011-04-18 16:57:27 -07005267 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenfaf354d2012-01-11 09:48:27 -08005268 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin31f18882011-04-18 16:57:27 -07005269 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07005270 mFrameCount = mInputBytes / mFrameSize;
5271 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5272
Glenn Kastend8f32c22012-03-08 12:32:47 -08005273 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Eric Laurenta553c252009-07-17 12:17:14 -07005274 {
5275 int channelCount;
5276 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5277 // stereo to mono post process as the resampler always outputs stereo.
5278 if (mChannelCount == 1 && mReqChannelCount == 2) {
5279 channelCount = 1;
5280 } else {
5281 channelCount = 2;
5282 }
5283 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5284 mResampler->setSampleRate(mSampleRate);
5285 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5286 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5287
5288 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5289 if (mChannelCount == 1 && mReqChannelCount == 1) {
5290 mFrameCount >>= 1;
5291 }
5292
5293 }
5294 mRsmpInIndex = mFrameCount;
5295}
5296
Eric Laurent47d0a922010-02-26 02:47:27 -08005297unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5298{
Eric Laurent828b9772011-08-07 16:32:26 -07005299 Mutex::Autolock _l(mLock);
5300 if (initCheck() != NO_ERROR) {
5301 return 0;
5302 }
5303
Dima Zavin31f18882011-04-18 16:57:27 -07005304 return mInput->stream->get_input_frames_lost(mInput->stream);
Eric Laurent47d0a922010-02-26 02:47:27 -08005305}
5306
Eric Laurent464d5b32011-06-17 21:29:58 -07005307uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5308{
5309 Mutex::Autolock _l(mLock);
5310 uint32_t result = 0;
5311 if (getEffectChain_l(sessionId) != 0) {
5312 result = EFFECT_SESSION;
5313 }
5314
5315 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5316 result |= TRACK_SESSION;
5317 }
5318
5319 return result;
5320}
5321
Eric Laurent6639b552011-08-01 09:52:20 -07005322AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5323{
5324 Mutex::Autolock _l(mLock);
5325 return mTrack;
5326}
5327
Glenn Kasten5b0135e2012-01-26 09:46:34 -08005328AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurent828b9772011-08-07 16:32:26 -07005329{
5330 Mutex::Autolock _l(mLock);
5331 return mInput;
5332}
5333
5334AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5335{
5336 Mutex::Autolock _l(mLock);
5337 AudioStreamIn *input = mInput;
5338 mInput = NULL;
5339 return input;
5340}
5341
5342// this method must always be called either with ThreadBase mLock held or inside the thread loop
5343audio_stream_t* AudioFlinger::RecordThread::stream()
5344{
5345 if (mInput == NULL) {
5346 return NULL;
5347 }
5348 return &mInput->stream->common;
5349}
5350
5351
Eric Laurenta553c252009-07-17 12:17:14 -07005352// ----------------------------------------------------------------------------
5353
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005354audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07005355 uint32_t *pSamplingRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005356 audio_format_t *pFormat,
Eric Laurenta553c252009-07-17 12:17:14 -07005357 uint32_t *pChannels,
5358 uint32_t *pLatencyMs,
Glenn Kasten28b269f2012-03-07 09:15:37 -08005359 audio_policy_output_flags_t flags)
Eric Laurenta553c252009-07-17 12:17:14 -07005360{
5361 status_t status;
5362 PlaybackThread *thread = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07005363 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005364 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Eric Laurenta553c252009-07-17 12:17:14 -07005365 uint32_t channels = pChannels ? *pChannels : 0;
5366 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin31f18882011-04-18 16:57:27 -07005367 audio_stream_out_t *outStream;
5368 audio_hw_device_t *outHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07005369
Steve Block71f2cf12011-10-20 11:56:00 +01005370 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Eric Laurenta553c252009-07-17 12:17:14 -07005371 pDevices ? *pDevices : 0,
5372 samplingRate,
5373 format,
5374 channels,
5375 flags);
5376
5377 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005378 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005379 }
Dima Zavin31f18882011-04-18 16:57:27 -07005380
Eric Laurenta553c252009-07-17 12:17:14 -07005381 Mutex::Autolock _l(mLock);
5382
Dima Zavin31f18882011-04-18 16:57:27 -07005383 outHwDev = findSuitableHwDev_l(*pDevices);
5384 if (outHwDev == NULL)
5385 return 0;
5386
Glenn Kasten23c9c742012-02-02 14:16:03 -08005387 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005388 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin31f18882011-04-18 16:57:27 -07005389 &channels, &samplingRate, &outStream);
Glenn Kasten23c9c742012-02-02 14:16:03 -08005390 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block71f2cf12011-10-20 11:56:00 +01005391 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin31f18882011-04-18 16:57:27 -07005392 outStream,
Eric Laurenta553c252009-07-17 12:17:14 -07005393 samplingRate,
5394 format,
5395 channels,
5396 status);
5397
Dima Zavin31f18882011-04-18 16:57:27 -07005398 if (outStream != NULL) {
5399 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005400 audio_io_handle_t id = nextUniqueId();
Dima Zavin31f18882011-04-18 16:57:27 -07005401
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005402 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5403 (format != AUDIO_FORMAT_PCM_16_BIT) ||
5404 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07005405 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01005406 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07005407 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07005408 thread = new MixerThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01005409 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07005410 }
Eric Laurent65b65452010-06-01 23:49:17 -07005411 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07005412
Glenn Kasten3694ec12012-01-27 16:47:15 -08005413 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5414 if (pFormat != NULL) *pFormat = format;
5415 if (pChannels != NULL) *pChannels = channels;
5416 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Eric Laurent9cc489a2009-12-05 05:20:01 -08005417
Eric Laurenteb8f8502010-05-14 03:26:45 -07005418 // notify client processes of the new output creation
5419 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07005420 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07005421 }
5422
Eric Laurent9cc489a2009-12-05 05:20:01 -08005423 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005424}
5425
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005426audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
5427 audio_io_handle_t output2)
Eric Laurenta553c252009-07-17 12:17:14 -07005428{
5429 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07005430 MixerThread *thread1 = checkMixerThread_l(output1);
5431 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07005432
Eric Laurentddb78e72009-07-28 08:44:33 -07005433 if (thread1 == NULL || thread2 == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005434 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005435 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005436 }
5437
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005438 audio_io_handle_t id = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07005439 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07005440 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07005441 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f8502010-05-14 03:26:45 -07005442 // notify client processes of the new output creation
5443 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07005444 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07005445}
5446
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005447status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Eric Laurenta553c252009-07-17 12:17:14 -07005448{
Eric Laurent49018a52009-08-04 08:37:05 -07005449 // keep strong reference on the playback thread so that
5450 // it is not destroyed while exit() is executed
5451 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07005452 {
5453 Mutex::Autolock _l(mLock);
5454 thread = checkPlaybackThread_l(output);
5455 if (thread == NULL) {
5456 return BAD_VALUE;
5457 }
5458
Steve Block71f2cf12011-10-20 11:56:00 +01005459 ALOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005460
Eric Laurent464d5b32011-06-17 21:29:58 -07005461 if (thread->type() == ThreadBase::MIXER) {
Eric Laurenta553c252009-07-17 12:17:14 -07005462 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005463 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005464 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07005465 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07005466 }
5467 }
5468 }
Glenn Kasten7d3be3a2012-01-26 10:53:32 -08005469 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Eric Laurentddb78e72009-07-28 08:44:33 -07005470 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07005471 }
5472 thread->exit();
Glenn Kasten761286f2012-01-06 08:39:38 -08005473 // The thread entity (active unit of execution) is no longer running here,
5474 // but the ThreadBase container still exists.
Eric Laurenta553c252009-07-17 12:17:14 -07005475
Eric Laurent464d5b32011-06-17 21:29:58 -07005476 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurent828b9772011-08-07 16:32:26 -07005477 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5b0135e2012-01-26 09:46:34 -08005478 assert(out != NULL);
Eric Laurent828b9772011-08-07 16:32:26 -07005479 // from now on thread->mOutput is NULL
Dima Zavin31f18882011-04-18 16:57:27 -07005480 out->hwDev->close_output_stream(out->hwDev, out->stream);
5481 delete out;
Eric Laurent49018a52009-08-04 08:37:05 -07005482 }
Eric Laurenta553c252009-07-17 12:17:14 -07005483 return NO_ERROR;
5484}
5485
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005486status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Eric Laurenta553c252009-07-17 12:17:14 -07005487{
5488 Mutex::Autolock _l(mLock);
5489 PlaybackThread *thread = checkPlaybackThread_l(output);
5490
5491 if (thread == NULL) {
5492 return BAD_VALUE;
5493 }
5494
Steve Block71f2cf12011-10-20 11:56:00 +01005495 ALOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005496 thread->suspend();
5497
5498 return NO_ERROR;
5499}
5500
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005501status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Eric Laurenta553c252009-07-17 12:17:14 -07005502{
5503 Mutex::Autolock _l(mLock);
5504 PlaybackThread *thread = checkPlaybackThread_l(output);
5505
5506 if (thread == NULL) {
5507 return BAD_VALUE;
5508 }
5509
Steve Block71f2cf12011-10-20 11:56:00 +01005510 ALOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005511
5512 thread->restore();
5513
5514 return NO_ERROR;
5515}
5516
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005517audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07005518 uint32_t *pSamplingRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005519 audio_format_t *pFormat,
Eric Laurenta553c252009-07-17 12:17:14 -07005520 uint32_t *pChannels,
Glenn Kasten882c0a22012-01-27 12:32:34 -08005521 audio_in_acoustics_t acoustics)
Eric Laurenta553c252009-07-17 12:17:14 -07005522{
5523 status_t status;
5524 RecordThread *thread = NULL;
5525 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005526 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Eric Laurenta553c252009-07-17 12:17:14 -07005527 uint32_t channels = pChannels ? *pChannels : 0;
5528 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005529 audio_format_t reqFormat = format;
Eric Laurenta553c252009-07-17 12:17:14 -07005530 uint32_t reqChannels = channels;
Dima Zavin31f18882011-04-18 16:57:27 -07005531 audio_stream_in_t *inStream;
5532 audio_hw_device_t *inHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07005533
5534 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005535 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005536 }
Dima Zavin31f18882011-04-18 16:57:27 -07005537
Eric Laurenta553c252009-07-17 12:17:14 -07005538 Mutex::Autolock _l(mLock);
5539
Dima Zavin31f18882011-04-18 16:57:27 -07005540 inHwDev = findSuitableHwDev_l(*pDevices);
5541 if (inHwDev == NULL)
5542 return 0;
5543
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005544 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin31f18882011-04-18 16:57:27 -07005545 &channels, &samplingRate,
Glenn Kasten882c0a22012-01-27 12:32:34 -08005546 acoustics,
Dima Zavin31f18882011-04-18 16:57:27 -07005547 &inStream);
Steve Block71f2cf12011-10-20 11:56:00 +01005548 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin31f18882011-04-18 16:57:27 -07005549 inStream,
Eric Laurenta553c252009-07-17 12:17:14 -07005550 samplingRate,
5551 format,
5552 channels,
5553 acoustics,
5554 status);
5555
5556 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5557 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5558 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin31f18882011-04-18 16:57:27 -07005559 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005560 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Eric Laurenta553c252009-07-17 12:17:14 -07005561 (samplingRate <= 2 * reqSamplingRate) &&
Glenn Kastend8f32c22012-03-08 12:32:47 -08005562 (popcount(channels) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block71f2cf12011-10-20 11:56:00 +01005563 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005564 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin31f18882011-04-18 16:57:27 -07005565 &channels, &samplingRate,
Glenn Kasten882c0a22012-01-27 12:32:34 -08005566 acoustics,
Dima Zavin31f18882011-04-18 16:57:27 -07005567 &inStream);
Eric Laurenta553c252009-07-17 12:17:14 -07005568 }
5569
Dima Zavin31f18882011-04-18 16:57:27 -07005570 if (inStream != NULL) {
5571 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5572
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005573 audio_io_handle_t id = nextUniqueId();
Eric Laurent464d5b32011-06-17 21:29:58 -07005574 // Start record thread
5575 // RecorThread require both input and output device indication to forward to audio
5576 // pre processing modules
5577 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5578 thread = new RecordThread(this,
5579 input,
5580 reqSamplingRate,
5581 reqChannels,
5582 id,
5583 device);
Eric Laurent65b65452010-06-01 23:49:17 -07005584 mRecordThreads.add(id, thread);
Steve Block71f2cf12011-10-20 11:56:00 +01005585 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kasten3694ec12012-01-27 16:47:15 -08005586 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5587 if (pFormat != NULL) *pFormat = format;
5588 if (pChannels != NULL) *pChannels = reqChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07005589
Dima Zavin31f18882011-04-18 16:57:27 -07005590 input->stream->common.standby(&input->stream->common);
Eric Laurent9cc489a2009-12-05 05:20:01 -08005591
Eric Laurenteb8f8502010-05-14 03:26:45 -07005592 // notify client processes of the new input creation
5593 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07005594 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07005595 }
5596
Eric Laurent9cc489a2009-12-05 05:20:01 -08005597 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005598}
5599
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005600status_t AudioFlinger::closeInput(audio_io_handle_t input)
Eric Laurenta553c252009-07-17 12:17:14 -07005601{
Eric Laurent49018a52009-08-04 08:37:05 -07005602 // keep strong reference on the record thread so that
5603 // it is not destroyed while exit() is executed
5604 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07005605 {
5606 Mutex::Autolock _l(mLock);
5607 thread = checkRecordThread_l(input);
5608 if (thread == NULL) {
5609 return BAD_VALUE;
5610 }
5611
Steve Block71f2cf12011-10-20 11:56:00 +01005612 ALOGV("closeInput() %d", input);
Glenn Kasten7d3be3a2012-01-26 10:53:32 -08005613 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Eric Laurentddb78e72009-07-28 08:44:33 -07005614 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07005615 }
5616 thread->exit();
Glenn Kasten761286f2012-01-06 08:39:38 -08005617 // The thread entity (active unit of execution) is no longer running here,
5618 // but the ThreadBase container still exists.
Eric Laurenta553c252009-07-17 12:17:14 -07005619
Eric Laurent828b9772011-08-07 16:32:26 -07005620 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5b0135e2012-01-26 09:46:34 -08005621 assert(in != NULL);
Eric Laurent828b9772011-08-07 16:32:26 -07005622 // from now on thread->mInput is NULL
Dima Zavin31f18882011-04-18 16:57:27 -07005623 in->hwDev->close_input_stream(in->hwDev, in->stream);
5624 delete in;
Eric Laurent49018a52009-08-04 08:37:05 -07005625
Eric Laurenta553c252009-07-17 12:17:14 -07005626 return NO_ERROR;
5627}
5628
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005629status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Eric Laurenta553c252009-07-17 12:17:14 -07005630{
5631 Mutex::Autolock _l(mLock);
5632 MixerThread *dstThread = checkMixerThread_l(output);
5633 if (dstThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005634 ALOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005635 return BAD_VALUE;
5636 }
5637
Steve Block71f2cf12011-10-20 11:56:00 +01005638 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f8502010-05-14 03:26:45 -07005639 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005640
Eric Laurent05ce0942011-08-30 10:18:54 -07005641 dstThread->setStreamValid(stream, true);
5642
Eric Laurenta553c252009-07-17 12:17:14 -07005643 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005644 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kasten7d3be3a2012-01-26 10:53:32 -08005645 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005646 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent05ce0942011-08-30 10:18:54 -07005647 srcThread->setStreamValid(stream, false);
Eric Laurenteb8f8502010-05-14 03:26:45 -07005648 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005649 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005650 }
Eric Laurentd069f322009-09-01 05:56:26 -07005651
Eric Laurenta553c252009-07-17 12:17:14 -07005652 return NO_ERROR;
5653}
5654
Eric Laurent65b65452010-06-01 23:49:17 -07005655
5656int AudioFlinger::newAudioSessionId()
5657{
Eric Laurent464d5b32011-06-17 21:29:58 -07005658 return nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07005659}
5660
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005661void AudioFlinger::acquireAudioSessionId(int audioSession)
5662{
5663 Mutex::Autolock _l(mLock);
Glenn Kastend153b1f2012-02-03 11:10:26 -08005664 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005665 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten150d2382012-02-08 14:04:28 -08005666 size_t num = mAudioSessionRefs.size();
5667 for (size_t i = 0; i< num; i++) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005668 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten9a42ac92012-03-06 11:22:01 -08005669 if (ref->mSessionid == audioSession && ref->mPid == caller) {
5670 ref->mCnt++;
5671 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005672 return;
5673 }
5674 }
Glenn Kastendc3ac852012-01-25 15:28:08 -08005675 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5676 ALOGV(" added new entry for %d", audioSession);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005677}
5678
5679void AudioFlinger::releaseAudioSessionId(int audioSession)
5680{
5681 Mutex::Autolock _l(mLock);
Glenn Kastend153b1f2012-02-03 11:10:26 -08005682 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005683 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten150d2382012-02-08 14:04:28 -08005684 size_t num = mAudioSessionRefs.size();
5685 for (size_t i = 0; i< num; i++) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005686 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten9a42ac92012-03-06 11:22:01 -08005687 if (ref->mSessionid == audioSession && ref->mPid == caller) {
5688 ref->mCnt--;
5689 ALOGV(" decremented refcount to %d", ref->mCnt);
5690 if (ref->mCnt == 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005691 mAudioSessionRefs.removeAt(i);
5692 delete ref;
5693 purgeStaleEffects_l();
5694 }
5695 return;
5696 }
5697 }
Steve Block8564c8d2012-01-05 23:22:43 +00005698 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005699}
5700
5701void AudioFlinger::purgeStaleEffects_l() {
5702
Steve Block71f2cf12011-10-20 11:56:00 +01005703 ALOGV("purging stale effects");
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005704
5705 Vector< sp<EffectChain> > chains;
5706
5707 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5708 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5709 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5710 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen2255a1e2011-08-12 14:14:39 -07005711 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5712 chains.push(ec);
5713 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005714 }
5715 }
5716 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5717 sp<RecordThread> t = mRecordThreads.valueAt(i);
5718 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5719 sp<EffectChain> ec = t->mEffectChains[j];
5720 chains.push(ec);
5721 }
5722 }
5723
5724 for (size_t i = 0; i < chains.size(); i++) {
5725 sp<EffectChain> ec = chains[i];
5726 int sessionid = ec->sessionId();
5727 sp<ThreadBase> t = ec->mThread.promote();
5728 if (t == 0) {
5729 continue;
5730 }
5731 size_t numsessionrefs = mAudioSessionRefs.size();
5732 bool found = false;
5733 for (size_t k = 0; k < numsessionrefs; k++) {
5734 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten9a42ac92012-03-06 11:22:01 -08005735 if (ref->mSessionid == sessionid) {
Steve Block71f2cf12011-10-20 11:56:00 +01005736 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kasten9a42ac92012-03-06 11:22:01 -08005737 sessionid, ref->mPid, ref->mCnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005738 found = true;
5739 break;
5740 }
5741 }
5742 if (!found) {
5743 // remove all effects from the chain
5744 while (ec->mEffects.size()) {
5745 sp<EffectModule> effect = ec->mEffects[0];
5746 effect->unPin();
5747 Mutex::Autolock _l (t->mLock);
5748 t->removeEffect_l(effect);
5749 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5750 sp<EffectHandle> handle = effect->mHandles[j].promote();
5751 if (handle != 0) {
5752 handle->mEffect.clear();
Eric Laurent7fa1cee2011-10-19 11:44:54 -07005753 if (handle->mHasControl && handle->mEnabled) {
5754 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5755 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005756 }
5757 }
5758 AudioSystem::unregisterEffect(effect->id());
5759 }
5760 }
5761 }
5762 return;
5763}
5764
Eric Laurenta553c252009-07-17 12:17:14 -07005765// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005766AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005767{
Glenn Kasten7d3be3a2012-01-26 10:53:32 -08005768 return mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005769}
5770
5771// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005772AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005773{
5774 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kasten7d3be3a2012-01-26 10:53:32 -08005775 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07005776}
5777
5778// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005779AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Eric Laurenta553c252009-07-17 12:17:14 -07005780{
Glenn Kasten7d3be3a2012-01-26 10:53:32 -08005781 return mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005782}
5783
Eric Laurent464d5b32011-06-17 21:29:58 -07005784uint32_t AudioFlinger::nextUniqueId()
Eric Laurent65b65452010-06-01 23:49:17 -07005785{
Eric Laurent464d5b32011-06-17 21:29:58 -07005786 return android_atomic_inc(&mNextUniqueId);
Eric Laurent65b65452010-06-01 23:49:17 -07005787}
5788
Glenn Kasten0fccd352012-02-24 15:42:17 -08005789AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent464d5b32011-06-17 21:29:58 -07005790{
5791 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5792 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent828b9772011-08-07 16:32:26 -07005793 AudioStreamOut *output = thread->getOutput();
5794 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005795 return thread;
5796 }
5797 }
5798 return NULL;
5799}
5800
Glenn Kasten0fccd352012-02-24 15:42:17 -08005801uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent464d5b32011-06-17 21:29:58 -07005802{
5803 PlaybackThread *thread = primaryPlaybackThread_l();
5804
5805 if (thread == NULL) {
5806 return 0;
5807 }
5808
5809 return thread->device();
5810}
5811
5812
Eric Laurent65b65452010-06-01 23:49:17 -07005813// ----------------------------------------------------------------------------
5814// Effect management
5815// ----------------------------------------------------------------------------
5816
5817
Glenn Kasten3f6d83a2012-01-26 16:25:10 -08005818status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Eric Laurent65b65452010-06-01 23:49:17 -07005819{
5820 Mutex::Autolock _l(mLock);
5821 return EffectQueryNumberEffects(numEffects);
5822}
5823
Glenn Kasten3f6d83a2012-01-26 16:25:10 -08005824status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Eric Laurent65b65452010-06-01 23:49:17 -07005825{
5826 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005827 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07005828}
5829
Glenn Kasten67313332012-01-30 07:40:52 -08005830status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kasten3f6d83a2012-01-26 16:25:10 -08005831 effect_descriptor_t *descriptor) const
Eric Laurent65b65452010-06-01 23:49:17 -07005832{
5833 Mutex::Autolock _l(mLock);
5834 return EffectGetDescriptor(pUuid, descriptor);
5835}
5836
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005837
Eric Laurent65b65452010-06-01 23:49:17 -07005838sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5839 effect_descriptor_t *pDesc,
5840 const sp<IEffectClient>& effectClient,
5841 int32_t priority,
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005842 audio_io_handle_t io,
Eric Laurent65b65452010-06-01 23:49:17 -07005843 int sessionId,
5844 status_t *status,
5845 int *id,
5846 int *enabled)
5847{
5848 status_t lStatus = NO_ERROR;
5849 sp<EffectHandle> handle;
Eric Laurent65b65452010-06-01 23:49:17 -07005850 effect_descriptor_t desc;
Eric Laurent65b65452010-06-01 23:49:17 -07005851
Glenn Kasten803a86a2012-01-25 14:28:29 -08005852 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent464d5b32011-06-17 21:29:58 -07005853 pid, effectClient.get(), priority, sessionId, io);
Eric Laurent65b65452010-06-01 23:49:17 -07005854
5855 if (pDesc == NULL) {
5856 lStatus = BAD_VALUE;
5857 goto Exit;
5858 }
5859
Eric Laurent98c92592010-09-23 16:10:16 -07005860 // check audio settings permission for global effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005861 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent98c92592010-09-23 16:10:16 -07005862 lStatus = PERMISSION_DENIED;
5863 goto Exit;
5864 }
5865
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005866 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent98c92592010-09-23 16:10:16 -07005867 // that can only be created by audio policy manager (running in same process)
Glenn Kasten81211142012-02-05 18:09:08 -08005868 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent98c92592010-09-23 16:10:16 -07005869 lStatus = PERMISSION_DENIED;
5870 goto Exit;
5871 }
5872
Eric Laurent464d5b32011-06-17 21:29:58 -07005873 if (io == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005874 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent98c92592010-09-23 16:10:16 -07005875 // output must be specified by AudioPolicyManager when using session
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005876 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent98c92592010-09-23 16:10:16 -07005877 lStatus = BAD_VALUE;
5878 goto Exit;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005879 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent98c92592010-09-23 16:10:16 -07005880 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent464d5b32011-06-17 21:29:58 -07005881 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent98c92592010-09-23 16:10:16 -07005882 // and we will exit safely
Eric Laurent464d5b32011-06-17 21:29:58 -07005883 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent98c92592010-09-23 16:10:16 -07005884 }
5885 }
5886
Eric Laurent65b65452010-06-01 23:49:17 -07005887 {
5888 Mutex::Autolock _l(mLock);
5889
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005890
Eric Laurent65b65452010-06-01 23:49:17 -07005891 if (!EffectIsNullUuid(&pDesc->uuid)) {
5892 // if uuid is specified, request effect descriptor
5893 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5894 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005895 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005896 goto Exit;
5897 }
5898 } else {
5899 // if uuid is not specified, look for an available implementation
5900 // of the required type in effect factory
5901 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block8564c8d2012-01-05 23:22:43 +00005902 ALOGW("createEffect() no effect type");
Eric Laurent65b65452010-06-01 23:49:17 -07005903 lStatus = BAD_VALUE;
5904 goto Exit;
5905 }
5906 uint32_t numEffects = 0;
5907 effect_descriptor_t d;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005908 d.flags = 0; // prevent compiler warning
Eric Laurent65b65452010-06-01 23:49:17 -07005909 bool found = false;
5910
5911 lStatus = EffectQueryNumberEffects(&numEffects);
5912 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005913 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005914 goto Exit;
5915 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005916 for (uint32_t i = 0; i < numEffects; i++) {
5917 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005918 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005919 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005920 continue;
5921 }
5922 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5923 // If matching type found save effect descriptor. If the session is
5924 // 0 and the effect is not auxiliary, continue enumeration in case
5925 // an auxiliary version of this effect type is available
5926 found = true;
5927 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005928 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07005929 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5930 break;
5931 }
5932 }
5933 }
5934 if (!found) {
5935 lStatus = BAD_VALUE;
Steve Block8564c8d2012-01-05 23:22:43 +00005936 ALOGW("createEffect() effect not found");
Eric Laurent65b65452010-06-01 23:49:17 -07005937 goto Exit;
5938 }
5939 // For same effect type, chose auxiliary version over insert version if
5940 // connect to output mix (Compliance to OpenSL ES)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005941 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005942 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5943 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5944 }
5945 }
5946
5947 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005948 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005949 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5950 lStatus = INVALID_OPERATION;
5951 goto Exit;
5952 }
5953
Eric Laurentf82fccd2011-07-27 19:49:51 -07005954 // check recording permission for visualizer
5955 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5956 !recordingAllowed()) {
5957 lStatus = PERMISSION_DENIED;
5958 goto Exit;
5959 }
5960
Eric Laurent65b65452010-06-01 23:49:17 -07005961 // return effect descriptor
5962 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5963
5964 // If output is not specified try to find a matching audio session ID in one of the
5965 // output threads.
Eric Laurent98c92592010-09-23 16:10:16 -07005966 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5967 // because of code checking output when entering the function.
Eric Laurent464d5b32011-06-17 21:29:58 -07005968 // Note: io is never 0 when creating an effect on an input
5969 if (io == 0) {
Eric Laurent98c92592010-09-23 16:10:16 -07005970 // look for the thread where the specified audio session is present
5971 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5972 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005973 io = mPlaybackThreads.keyAt(i);
Eric Laurent98c92592010-09-23 16:10:16 -07005974 break;
Eric Laurent493941b2010-07-28 01:32:47 -07005975 }
Eric Laurent65b65452010-06-01 23:49:17 -07005976 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005977 if (io == 0) {
5978 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5979 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5980 io = mRecordThreads.keyAt(i);
5981 break;
5982 }
5983 }
5984 }
Eric Laurent98c92592010-09-23 16:10:16 -07005985 // If no output thread contains the requested session ID, default to
5986 // first output. The effect chain will be moved to the correct output
5987 // thread when a track with the same session ID is created
Eric Laurent464d5b32011-06-17 21:29:58 -07005988 if (io == 0 && mPlaybackThreads.size()) {
5989 io = mPlaybackThreads.keyAt(0);
5990 }
Steve Block71f2cf12011-10-20 11:56:00 +01005991 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent464d5b32011-06-17 21:29:58 -07005992 }
5993 ThreadBase *thread = checkRecordThread_l(io);
5994 if (thread == NULL) {
5995 thread = checkPlaybackThread_l(io);
5996 if (thread == NULL) {
Steve Block3762c312012-01-06 19:20:56 +00005997 ALOGE("createEffect() unknown output thread");
Eric Laurent464d5b32011-06-17 21:29:58 -07005998 lStatus = BAD_VALUE;
5999 goto Exit;
Eric Laurent98c92592010-09-23 16:10:16 -07006000 }
Eric Laurent65b65452010-06-01 23:49:17 -07006001 }
Eric Laurent98c92592010-09-23 16:10:16 -07006002
Glenn Kasten803a86a2012-01-25 14:28:29 -08006003 sp<Client> client = registerPid_l(pid);
Eric Laurent65b65452010-06-01 23:49:17 -07006004
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006005 // create effect on selected output thread
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006006 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6007 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006008 if (handle != 0 && id != NULL) {
6009 *id = handle->id();
6010 }
6011 }
6012
6013Exit:
6014 if(status) {
6015 *status = lStatus;
6016 }
6017 return handle;
6018}
6019
Glenn Kasten39d00cb2012-01-17 11:09:42 -08006020status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
6021 audio_io_handle_t dstOutput)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006022{
Steve Block71f2cf12011-10-20 11:56:00 +01006023 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07006024 sessionId, srcOutput, dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006025 Mutex::Autolock _l(mLock);
6026 if (srcOutput == dstOutput) {
Steve Block8564c8d2012-01-05 23:22:43 +00006027 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006028 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07006029 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006030 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6031 if (srcThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00006032 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006033 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07006034 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006035 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6036 if (dstThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00006037 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006038 return BAD_VALUE;
6039 }
6040
6041 Mutex::Autolock _dl(dstThread->mLock);
6042 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006043 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006044
Eric Laurent53334cd2010-06-23 17:38:20 -07006045 return NO_ERROR;
6046}
6047
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006048// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurentf82fccd2011-07-27 19:49:51 -07006049status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006050 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent493941b2010-07-28 01:32:47 -07006051 AudioFlinger::PlaybackThread *dstThread,
6052 bool reRegister)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006053{
Steve Block71f2cf12011-10-20 11:56:00 +01006054 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07006055 sessionId, srcThread, dstThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006056
Eric Laurentf82fccd2011-07-27 19:49:51 -07006057 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006058 if (chain == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00006059 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07006060 sessionId, srcThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006061 return INVALID_OPERATION;
6062 }
6063
Eric Laurent493941b2010-07-28 01:32:47 -07006064 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006065 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurent6fccbd02011-10-05 17:42:25 -07006066 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006067 // removed.
6068 srcThread->removeEffectChain_l(chain);
6069
6070 // transfer all effects one by one so that new effect chain is created on new thread with
6071 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten39d00cb2012-01-17 11:09:42 -08006072 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent493941b2010-07-28 01:32:47 -07006073 sp<EffectChain> dstChain;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006074 uint32_t strategy = 0; // prevent compiler warning
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006075 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6076 while (effect != 0) {
6077 srcThread->removeEffect_l(effect);
6078 dstThread->addEffect_l(effect);
Eric Laurent6fccbd02011-10-05 17:42:25 -07006079 // removeEffect_l() has stopped the effect if it was active so it must be restarted
6080 if (effect->state() == EffectModule::ACTIVE ||
6081 effect->state() == EffectModule::STOPPING) {
6082 effect->start();
6083 }
Eric Laurent493941b2010-07-28 01:32:47 -07006084 // if the move request is not received from audio policy manager, the effect must be
6085 // re-registered with the new strategy and output
6086 if (dstChain == 0) {
6087 dstChain = effect->chain().promote();
6088 if (dstChain == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00006089 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent493941b2010-07-28 01:32:47 -07006090 srcThread->addEffect_l(effect);
6091 return NO_INIT;
6092 }
6093 strategy = dstChain->strategy();
6094 }
6095 if (reRegister) {
6096 AudioSystem::unregisterEffect(effect->id());
6097 AudioSystem::registerEffect(&effect->desc(),
6098 dstOutput,
6099 strategy,
Eric Laurentf82fccd2011-07-27 19:49:51 -07006100 sessionId,
Eric Laurent493941b2010-07-28 01:32:47 -07006101 effect->id());
6102 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006103 effect = chain->getEffectFromId_l(0);
6104 }
6105
6106 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07006107}
6108
Eric Laurent464d5b32011-06-17 21:29:58 -07006109
Eric Laurent65b65452010-06-01 23:49:17 -07006110// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07006111sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Eric Laurent65b65452010-06-01 23:49:17 -07006112 const sp<AudioFlinger::Client>& client,
6113 const sp<IEffectClient>& effectClient,
6114 int32_t priority,
6115 int sessionId,
6116 effect_descriptor_t *desc,
6117 int *enabled,
6118 status_t *status
6119 )
6120{
6121 sp<EffectModule> effect;
6122 sp<EffectHandle> handle;
6123 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -07006124 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006125 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07006126 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07006127 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07006128
Eric Laurent464d5b32011-06-17 21:29:58 -07006129 lStatus = initCheck();
6130 if (lStatus != NO_ERROR) {
Steve Block8564c8d2012-01-05 23:22:43 +00006131 ALOGW("createEffect_l() Audio driver not initialized.");
Eric Laurent65b65452010-06-01 23:49:17 -07006132 goto Exit;
6133 }
6134
6135 // Do not allow effects with session ID 0 on direct output or duplicating threads
6136 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006137 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block8564c8d2012-01-05 23:22:43 +00006138 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006139 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07006140 lStatus = BAD_VALUE;
6141 goto Exit;
6142 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006143 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kasten7d3be3a2012-01-26 10:53:32 -08006144 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block8564c8d2012-01-05 23:22:43 +00006145 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent464d5b32011-06-17 21:29:58 -07006146 desc->name, desc->flags, mType);
6147 lStatus = BAD_VALUE;
6148 goto Exit;
6149 }
Eric Laurent65b65452010-06-01 23:49:17 -07006150
Steve Block71f2cf12011-10-20 11:56:00 +01006151 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07006152
6153 { // scope for mLock
6154 Mutex::Autolock _l(mLock);
6155
6156 // check for existing effect chain with the requested audio session
6157 chain = getEffectChain_l(sessionId);
6158 if (chain == 0) {
6159 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01006160 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07006161 chain = new EffectChain(this, sessionId);
6162 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006163 chain->setStrategy(getStrategyForSession_l(sessionId));
6164 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07006165 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07006166 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07006167 }
6168
Glenn Kasten70ed6b72012-01-10 10:46:34 -08006169 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Eric Laurent65b65452010-06-01 23:49:17 -07006170
6171 if (effect == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07006172 int id = mAudioFlinger->nextUniqueId();
Eric Laurent53334cd2010-06-23 17:38:20 -07006173 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006174 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07006175 if (lStatus != NO_ERROR) {
6176 goto Exit;
6177 }
6178 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07006179 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006180 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07006181 lStatus = effect->status();
6182 if (lStatus != NO_ERROR) {
6183 goto Exit;
6184 }
Eric Laurent76c40f72010-07-15 12:50:15 -07006185 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07006186 if (lStatus != NO_ERROR) {
6187 goto Exit;
6188 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006189 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07006190
6191 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07006192 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07006193 }
6194 // create effect handle and connect it to effect module
6195 handle = new EffectHandle(effect, client, effectClient, priority);
6196 lStatus = effect->addHandle(handle);
Glenn Kasten3694ec12012-01-27 16:47:15 -08006197 if (enabled != NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006198 *enabled = (int)effect->isEnabled();
6199 }
6200 }
6201
6202Exit:
6203 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006204 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07006205 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006206 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07006207 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006208 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006209 AudioSystem::unregisterEffect(effect->id());
6210 }
6211 if (chainCreated) {
6212 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07006213 }
Eric Laurent65b65452010-06-01 23:49:17 -07006214 handle.clear();
6215 }
6216
6217 if(status) {
6218 *status = lStatus;
6219 }
6220 return handle;
6221}
6222
Eric Laurent464d5b32011-06-17 21:29:58 -07006223sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6224{
Eric Laurent464d5b32011-06-17 21:29:58 -07006225 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kastenc64a6f02012-01-30 13:00:02 -08006226 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent464d5b32011-06-17 21:29:58 -07006227}
6228
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006229// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6230// PlaybackThread::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07006231status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006232{
6233 // check for existing effect chain with the requested audio session
6234 int sessionId = effect->sessionId();
6235 sp<EffectChain> chain = getEffectChain_l(sessionId);
6236 bool chainCreated = false;
6237
6238 if (chain == 0) {
6239 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01006240 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006241 chain = new EffectChain(this, sessionId);
6242 addEffectChain_l(chain);
6243 chain->setStrategy(getStrategyForSession_l(sessionId));
6244 chainCreated = true;
6245 }
Steve Block71f2cf12011-10-20 11:56:00 +01006246 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006247
6248 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00006249 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006250 this, effect->desc().name, chain.get());
6251 return BAD_VALUE;
6252 }
6253
6254 status_t status = chain->addEffect_l(effect);
6255 if (status != NO_ERROR) {
6256 if (chainCreated) {
6257 removeEffectChain_l(chain);
6258 }
6259 return status;
6260 }
6261
6262 effect->setDevice(mDevice);
6263 effect->setMode(mAudioFlinger->getMode());
6264 return NO_ERROR;
6265}
6266
Eric Laurent464d5b32011-06-17 21:29:58 -07006267void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006268
Steve Block71f2cf12011-10-20 11:56:00 +01006269 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07006270 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006271 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6272 detachAuxEffect_l(effect->id());
6273 }
6274
6275 sp<EffectChain> chain = effect->chain().promote();
6276 if (chain != 0) {
6277 // remove effect chain if removing last effect
6278 if (chain->removeEffect_l(effect) == 0) {
6279 removeEffectChain_l(chain);
6280 }
6281 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00006282 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006283 }
6284}
6285
Eric Laurent464d5b32011-06-17 21:29:58 -07006286void AudioFlinger::ThreadBase::lockEffectChains_l(
6287 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
6288{
6289 effectChains = mEffectChains;
6290 for (size_t i = 0; i < mEffectChains.size(); i++) {
6291 mEffectChains[i]->lock();
6292 }
6293}
6294
6295void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kasten0fccd352012-02-24 15:42:17 -08006296 const Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Eric Laurent464d5b32011-06-17 21:29:58 -07006297{
6298 for (size_t i = 0; i < effectChains.size(); i++) {
6299 effectChains[i]->unlock();
6300 }
6301}
6302
6303sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6304{
6305 Mutex::Autolock _l(mLock);
6306 return getEffectChain_l(sessionId);
6307}
6308
6309sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6310{
Eric Laurent464d5b32011-06-17 21:29:58 -07006311 size_t size = mEffectChains.size();
6312 for (size_t i = 0; i < size; i++) {
6313 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kastenc64a6f02012-01-30 13:00:02 -08006314 return mEffectChains[i];
Eric Laurent464d5b32011-06-17 21:29:58 -07006315 }
6316 }
Glenn Kastenc64a6f02012-01-30 13:00:02 -08006317 return 0;
Eric Laurent464d5b32011-06-17 21:29:58 -07006318}
6319
Glenn Kastenaccb1142012-01-04 11:00:47 -08006320void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent464d5b32011-06-17 21:29:58 -07006321{
6322 Mutex::Autolock _l(mLock);
6323 size_t size = mEffectChains.size();
6324 for (size_t i = 0; i < size; i++) {
6325 mEffectChains[i]->setMode_l(mode);
6326 }
6327}
6328
6329void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006330 const wp<EffectHandle>& handle,
Glenn Kasten29441ff2012-02-03 10:32:24 -08006331 bool unpinIfLast) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006332
Eric Laurent53334cd2010-06-23 17:38:20 -07006333 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006334 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07006335 // delete the effect module if removing last handle on it
6336 if (effect->removeHandle(handle) == 0) {
Glenn Kasten29441ff2012-02-03 10:32:24 -08006337 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006338 removeEffect_l(effect);
6339 AudioSystem::unregisterEffect(effect->id());
6340 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006341 }
6342}
6343
Eric Laurent65b65452010-06-01 23:49:17 -07006344status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6345{
6346 int session = chain->sessionId();
6347 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07006348 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07006349
Steve Block71f2cf12011-10-20 11:56:00 +01006350 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07006351 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07006352 // Only one effect chain can be present in direct output thread and it uses
6353 // the mix buffer as input
6354 if (mType != DIRECT) {
6355 size_t numSamples = mFrameCount * mChannelCount;
6356 buffer = new int16_t[numSamples];
6357 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block71f2cf12011-10-20 11:56:00 +01006358 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Eric Laurent65b65452010-06-01 23:49:17 -07006359 ownsBuffer = true;
6360 }
Eric Laurent65b65452010-06-01 23:49:17 -07006361
Eric Laurent53334cd2010-06-23 17:38:20 -07006362 // Attach all tracks with same session ID to this chain.
6363 for (size_t i = 0; i < mTracks.size(); ++i) {
6364 sp<Track> track = mTracks[i];
6365 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01006366 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Eric Laurent53334cd2010-06-23 17:38:20 -07006367 track->setMainBuffer(buffer);
Eric Laurent90681d62011-05-09 12:09:06 -07006368 chain->incTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07006369 }
6370 }
6371
6372 // indicate all active tracks in the chain
6373 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6374 sp<Track> track = mActiveTracks[i].promote();
6375 if (track == 0) continue;
6376 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01006377 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurent90681d62011-05-09 12:09:06 -07006378 chain->incActiveTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07006379 }
Eric Laurent65b65452010-06-01 23:49:17 -07006380 }
6381 }
6382
Eric Laurent53334cd2010-06-23 17:38:20 -07006383 chain->setInBuffer(buffer, ownsBuffer);
6384 chain->setOutBuffer(mMixBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006385 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006386 // chains list in order to be processed last as it contains output stage effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006387 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6388 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07006389 // after track specific effects and before output stage
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006390 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6391 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006392 // Effect chain for other sessions are inserted at beginning of effect
6393 // chains list to be processed before output mix effects. Relative order between other
6394 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07006395 size_t size = mEffectChains.size();
6396 size_t i = 0;
6397 for (i = 0; i < size; i++) {
6398 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07006399 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006400 mEffectChains.insertAt(chain, i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006401 checkSuspendOnAddEffectChain_l(chain);
Eric Laurent65b65452010-06-01 23:49:17 -07006402
6403 return NO_ERROR;
6404}
6405
6406size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6407{
6408 int session = chain->sessionId();
6409
Steve Block71f2cf12011-10-20 11:56:00 +01006410 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Eric Laurent65b65452010-06-01 23:49:17 -07006411
6412 for (size_t i = 0; i < mEffectChains.size(); i++) {
6413 if (chain == mEffectChains[i]) {
6414 mEffectChains.removeAt(i);
Eric Laurent90681d62011-05-09 12:09:06 -07006415 // detach all active tracks from the chain
6416 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6417 sp<Track> track = mActiveTracks[i].promote();
6418 if (track == 0) continue;
6419 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01006420 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurent90681d62011-05-09 12:09:06 -07006421 chain.get(), session);
6422 chain->decActiveTrackCnt();
6423 }
6424 }
6425
Eric Laurent65b65452010-06-01 23:49:17 -07006426 // detach all tracks with same session ID from this chain
6427 for (size_t i = 0; i < mTracks.size(); ++i) {
6428 sp<Track> track = mTracks[i];
6429 if (session == track->sessionId()) {
6430 track->setMainBuffer(mMixBuffer);
Eric Laurent90681d62011-05-09 12:09:06 -07006431 chain->decTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07006432 }
6433 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006434 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006435 }
6436 }
6437 return mEffectChains.size();
6438}
6439
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006440status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6441 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07006442{
6443 Mutex::Autolock _l(mLock);
6444 return attachAuxEffect_l(track, EffectId);
6445}
6446
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006447status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6448 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07006449{
6450 status_t status = NO_ERROR;
6451
6452 if (EffectId == 0) {
6453 track->setAuxBuffer(0, NULL);
6454 } else {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006455 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6456 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07006457 if (effect != 0) {
6458 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6459 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6460 } else {
6461 status = INVALID_OPERATION;
6462 }
6463 } else {
6464 status = BAD_VALUE;
6465 }
6466 }
6467 return status;
6468}
6469
6470void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6471{
6472 for (size_t i = 0; i < mTracks.size(); ++i) {
6473 sp<Track> track = mTracks[i];
6474 if (track->auxEffectId() == effectId) {
6475 attachAuxEffect_l(track, 0);
6476 }
6477 }
6478}
6479
Eric Laurent464d5b32011-06-17 21:29:58 -07006480status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6481{
6482 // only one chain per input thread
6483 if (mEffectChains.size() != 0) {
6484 return INVALID_OPERATION;
6485 }
Steve Block71f2cf12011-10-20 11:56:00 +01006486 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent464d5b32011-06-17 21:29:58 -07006487
6488 chain->setInBuffer(NULL);
6489 chain->setOutBuffer(NULL);
6490
Eric Laurentf82fccd2011-07-27 19:49:51 -07006491 checkSuspendOnAddEffectChain_l(chain);
6492
Eric Laurent464d5b32011-06-17 21:29:58 -07006493 mEffectChains.add(chain);
6494
6495 return NO_ERROR;
6496}
6497
6498size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6499{
Steve Block71f2cf12011-10-20 11:56:00 +01006500 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block8564c8d2012-01-05 23:22:43 +00006501 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent464d5b32011-06-17 21:29:58 -07006502 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6503 chain.get(), mEffectChains.size(), this);
6504 if (mEffectChains.size() == 1) {
6505 mEffectChains.removeAt(0);
6506 }
6507 return 0;
6508}
6509
Eric Laurent65b65452010-06-01 23:49:17 -07006510// ----------------------------------------------------------------------------
6511// EffectModule implementation
6512// ----------------------------------------------------------------------------
6513
6514#undef LOG_TAG
6515#define LOG_TAG "AudioFlinger::EffectModule"
6516
Glenn Kasten685c9ce2012-01-20 13:32:16 -08006517AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Eric Laurent65b65452010-06-01 23:49:17 -07006518 const wp<AudioFlinger::EffectChain>& chain,
6519 effect_descriptor_t *desc,
6520 int id,
6521 int sessionId)
Glenn Kasten685c9ce2012-01-20 13:32:16 -08006522 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006523 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006524{
Steve Block71f2cf12011-10-20 11:56:00 +01006525 ALOGV("Constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006526 int lStatus;
Glenn Kasten685c9ce2012-01-20 13:32:16 -08006527 if (thread == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006528 return;
6529 }
Eric Laurent65b65452010-06-01 23:49:17 -07006530
6531 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6532
6533 // create effect engine from effect factory
Eric Laurent464d5b32011-06-17 21:29:58 -07006534 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Eric Laurent53334cd2010-06-23 17:38:20 -07006535
Eric Laurent65b65452010-06-01 23:49:17 -07006536 if (mStatus != NO_ERROR) {
6537 return;
6538 }
6539 lStatus = init();
6540 if (lStatus < 0) {
6541 mStatus = lStatus;
6542 goto Error;
6543 }
6544
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006545 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6546 mPinned = true;
6547 }
Steve Block71f2cf12011-10-20 11:56:00 +01006548 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006549 return;
6550Error:
6551 EffectRelease(mEffectInterface);
6552 mEffectInterface = NULL;
Steve Block71f2cf12011-10-20 11:56:00 +01006553 ALOGV("Constructor Error %d", mStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006554}
6555
6556AudioFlinger::EffectModule::~EffectModule()
6557{
Steve Block71f2cf12011-10-20 11:56:00 +01006558 ALOGV("Destructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006559 if (mEffectInterface != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07006560 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6561 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6562 sp<ThreadBase> thread = mThread.promote();
6563 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006564 audio_stream_t *stream = thread->stream();
6565 if (stream != NULL) {
6566 stream->remove_audio_effect(stream, mEffectInterface);
6567 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006568 }
6569 }
Eric Laurent65b65452010-06-01 23:49:17 -07006570 // release effect engine
6571 EffectRelease(mEffectInterface);
6572 }
6573}
6574
Glenn Kasten1f812f72012-01-30 10:15:48 -08006575status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Eric Laurent65b65452010-06-01 23:49:17 -07006576{
6577 status_t status;
6578
6579 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006580 int priority = handle->priority();
6581 size_t size = mHandles.size();
6582 sp<EffectHandle> h;
6583 size_t i;
6584 for (i = 0; i < size; i++) {
6585 h = mHandles[i].promote();
6586 if (h == 0) continue;
6587 if (h->priority() <= priority) break;
6588 }
6589 // if inserted in first place, move effect control from previous owner to this handle
6590 if (i == 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006591 bool enabled = false;
Eric Laurent65b65452010-06-01 23:49:17 -07006592 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006593 enabled = h->enabled();
6594 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006595 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006596 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006597 status = NO_ERROR;
6598 } else {
6599 status = ALREADY_EXISTS;
6600 }
Steve Block71f2cf12011-10-20 11:56:00 +01006601 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Eric Laurent65b65452010-06-01 23:49:17 -07006602 mHandles.insertAt(handle, i);
6603 return status;
6604}
6605
6606size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6607{
6608 Mutex::Autolock _l(mLock);
6609 size_t size = mHandles.size();
6610 size_t i;
6611 for (i = 0; i < size; i++) {
6612 if (mHandles[i] == handle) break;
6613 }
6614 if (i == size) {
6615 return size;
6616 }
Steve Block71f2cf12011-10-20 11:56:00 +01006617 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006618
6619 bool enabled = false;
6620 EffectHandle *hdl = handle.unsafe_get();
Glenn Kasten3694ec12012-01-27 16:47:15 -08006621 if (hdl != NULL) {
Steve Block71f2cf12011-10-20 11:56:00 +01006622 ALOGV("removeHandle() unsafe_get OK");
Eric Laurentf82fccd2011-07-27 19:49:51 -07006623 enabled = hdl->enabled();
6624 }
Eric Laurent65b65452010-06-01 23:49:17 -07006625 mHandles.removeAt(i);
6626 size = mHandles.size();
6627 // if removed from first place, move effect control from this handle to next in line
6628 if (i == 0 && size != 0) {
6629 sp<EffectHandle> h = mHandles[0].promote();
6630 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006631 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006632 }
6633 }
6634
Eric Laurent21b5c472011-07-26 20:54:46 -07006635 // Prevent calls to process() and other functions on effect interface from now on.
6636 // The effect engine will be released by the destructor when the last strong reference on
6637 // this object is released which can happen after next process is called.
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006638 if (size == 0 && !mPinned) {
Eric Laurent21b5c472011-07-26 20:54:46 -07006639 mState = DESTROYED;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006640 }
6641
Eric Laurent65b65452010-06-01 23:49:17 -07006642 return size;
6643}
6644
Eric Laurentf82fccd2011-07-27 19:49:51 -07006645sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6646{
6647 Mutex::Autolock _l(mLock);
Glenn Kastenc64a6f02012-01-30 13:00:02 -08006648 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurentf82fccd2011-07-27 19:49:51 -07006649}
6650
Glenn Kasten29441ff2012-02-03 10:32:24 -08006651void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Eric Laurent65b65452010-06-01 23:49:17 -07006652{
Glenn Kasten0765c442012-01-27 15:24:38 -08006653 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Eric Laurent65b65452010-06-01 23:49:17 -07006654 // keep a strong reference on this EffectModule to avoid calling the
6655 // destructor before we exit
6656 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07006657 {
6658 sp<ThreadBase> thread = mThread.promote();
6659 if (thread != 0) {
Glenn Kasten29441ff2012-02-03 10:32:24 -08006660 thread->disconnectEffect(keep, handle, unpinIfLast);
Eric Laurent65b65452010-06-01 23:49:17 -07006661 }
6662 }
6663}
6664
Eric Laurent7d850f22010-07-09 13:34:17 -07006665void AudioFlinger::EffectModule::updateState() {
6666 Mutex::Autolock _l(mLock);
6667
6668 switch (mState) {
6669 case RESTART:
6670 reset_l();
6671 // FALL THROUGH
6672
6673 case STARTING:
6674 // clear auxiliary effect input buffer for next accumulation
6675 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6676 memset(mConfig.inputCfg.buffer.raw,
6677 0,
6678 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6679 }
6680 start_l();
6681 mState = ACTIVE;
6682 break;
6683 case STOPPING:
6684 stop_l();
6685 mDisableWaitCnt = mMaxDisableWaitCnt;
6686 mState = STOPPED;
6687 break;
6688 case STOPPED:
6689 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6690 // turn off sequence.
6691 if (--mDisableWaitCnt == 0) {
6692 reset_l();
6693 mState = IDLE;
6694 }
6695 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006696 default: //IDLE , ACTIVE, DESTROYED
Eric Laurent7d850f22010-07-09 13:34:17 -07006697 break;
6698 }
6699}
6700
Eric Laurent65b65452010-06-01 23:49:17 -07006701void AudioFlinger::EffectModule::process()
6702{
6703 Mutex::Autolock _l(mLock);
6704
Eric Laurent21b5c472011-07-26 20:54:46 -07006705 if (mState == DESTROYED || mEffectInterface == NULL ||
Eric Laurent7d850f22010-07-09 13:34:17 -07006706 mConfig.inputCfg.buffer.raw == NULL ||
6707 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006708 return;
6709 }
6710
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006711 if (isProcessEnabled()) {
Eric Laurent65b65452010-06-01 23:49:17 -07006712 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6713 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten490909d2011-12-15 09:52:39 -08006714 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Eric Laurent65b65452010-06-01 23:49:17 -07006715 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006716 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07006717 }
6718
Eric Laurent65b65452010-06-01 23:49:17 -07006719 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07006720 int ret = (*mEffectInterface)->process(mEffectInterface,
6721 &mConfig.inputCfg.buffer,
6722 &mConfig.outputCfg.buffer);
6723
6724 // force transition to IDLE state when engine is ready
6725 if (mState == STOPPED && ret == -ENODATA) {
6726 mDisableWaitCnt = 1;
6727 }
Eric Laurent65b65452010-06-01 23:49:17 -07006728
6729 // clear auxiliary effect input buffer for next accumulation
6730 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006731 memset(mConfig.inputCfg.buffer.raw, 0,
6732 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006733 }
6734 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent67b5ed32011-01-19 18:36:13 -08006735 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6736 // If an insert effect is idle and input buffer is different from output buffer,
6737 // accumulate input onto output
Eric Laurent65b65452010-06-01 23:49:17 -07006738 sp<EffectChain> chain = mChain.promote();
Eric Laurent90681d62011-05-09 12:09:06 -07006739 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006740 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6741 int16_t *in = mConfig.inputCfg.buffer.s16;
6742 int16_t *out = mConfig.outputCfg.buffer.s16;
6743 for (size_t i = 0; i < frameCnt; i++) {
6744 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Eric Laurent65b65452010-06-01 23:49:17 -07006745 }
Eric Laurent65b65452010-06-01 23:49:17 -07006746 }
6747 }
6748}
6749
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006750void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006751{
6752 if (mEffectInterface == NULL) {
6753 return;
6754 }
6755 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6756}
6757
6758status_t AudioFlinger::EffectModule::configure()
6759{
6760 uint32_t channels;
6761 if (mEffectInterface == NULL) {
6762 return NO_INIT;
6763 }
6764
6765 sp<ThreadBase> thread = mThread.promote();
6766 if (thread == 0) {
6767 return DEAD_OBJECT;
6768 }
6769
6770 // TODO: handle configuration of effects replacing track process
6771 if (thread->channelCount() == 1) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006772 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006773 } else {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006774 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurent65b65452010-06-01 23:49:17 -07006775 }
6776
6777 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006778 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006779 } else {
6780 mConfig.inputCfg.channels = channels;
6781 }
6782 mConfig.outputCfg.channels = channels;
Eric Laurent0fb66c22011-05-17 19:16:02 -07006783 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6784 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurent65b65452010-06-01 23:49:17 -07006785 mConfig.inputCfg.samplingRate = thread->sampleRate();
6786 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6787 mConfig.inputCfg.bufferProvider.cookie = NULL;
6788 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6789 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6790 mConfig.outputCfg.bufferProvider.cookie = NULL;
6791 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6792 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6793 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6794 // Insert effect:
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006795 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006796 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07006797 // - in other sessions:
6798 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6799 // other effect: overwrites output buffer: input buffer == output buffer
6800 // Auxiliary effect:
6801 // accumulates in output buffer: input buffer != output buffer
6802 // Therefore: accumulate <=> input buffer != output buffer
6803 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6804 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6805 } else {
6806 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6807 }
6808 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6809 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6810 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6811 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6812
Steve Block71f2cf12011-10-20 11:56:00 +01006813 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006814 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6815
Eric Laurent65b65452010-06-01 23:49:17 -07006816 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006817 uint32_t size = sizeof(int);
6818 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent4abf8822011-12-16 15:30:36 -08006819 EFFECT_CMD_SET_CONFIG,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006820 sizeof(effect_config_t),
6821 &mConfig,
6822 &size,
6823 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006824 if (status == 0) {
6825 status = cmdStatus;
6826 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006827
6828 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6829 (1000 * mConfig.outputCfg.buffer.frameCount);
6830
Eric Laurent65b65452010-06-01 23:49:17 -07006831 return status;
6832}
6833
6834status_t AudioFlinger::EffectModule::init()
6835{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006836 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006837 if (mEffectInterface == NULL) {
6838 return NO_INIT;
6839 }
6840 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006841 uint32_t size = sizeof(status_t);
6842 status_t status = (*mEffectInterface)->command(mEffectInterface,
6843 EFFECT_CMD_INIT,
6844 0,
6845 NULL,
6846 &size,
6847 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006848 if (status == 0) {
6849 status = cmdStatus;
6850 }
6851 return status;
6852}
6853
Eric Laurent6fccbd02011-10-05 17:42:25 -07006854status_t AudioFlinger::EffectModule::start()
6855{
6856 Mutex::Autolock _l(mLock);
6857 return start_l();
6858}
6859
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006860status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006861{
6862 if (mEffectInterface == NULL) {
6863 return NO_INIT;
6864 }
6865 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006866 uint32_t size = sizeof(status_t);
6867 status_t status = (*mEffectInterface)->command(mEffectInterface,
6868 EFFECT_CMD_ENABLE,
6869 0,
6870 NULL,
6871 &size,
6872 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006873 if (status == 0) {
6874 status = cmdStatus;
6875 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006876 if (status == 0 &&
6877 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6878 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6879 sp<ThreadBase> thread = mThread.promote();
6880 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006881 audio_stream_t *stream = thread->stream();
6882 if (stream != NULL) {
6883 stream->add_audio_effect(stream, mEffectInterface);
6884 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006885 }
6886 }
Eric Laurent65b65452010-06-01 23:49:17 -07006887 return status;
6888}
6889
Eric Laurent21b5c472011-07-26 20:54:46 -07006890status_t AudioFlinger::EffectModule::stop()
6891{
6892 Mutex::Autolock _l(mLock);
6893 return stop_l();
6894}
6895
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006896status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006897{
6898 if (mEffectInterface == NULL) {
6899 return NO_INIT;
6900 }
6901 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006902 uint32_t size = sizeof(status_t);
6903 status_t status = (*mEffectInterface)->command(mEffectInterface,
6904 EFFECT_CMD_DISABLE,
6905 0,
6906 NULL,
6907 &size,
6908 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006909 if (status == 0) {
6910 status = cmdStatus;
6911 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006912 if (status == 0 &&
6913 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6914 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6915 sp<ThreadBase> thread = mThread.promote();
6916 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006917 audio_stream_t *stream = thread->stream();
6918 if (stream != NULL) {
6919 stream->remove_audio_effect(stream, mEffectInterface);
6920 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006921 }
6922 }
Eric Laurent65b65452010-06-01 23:49:17 -07006923 return status;
6924}
6925
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006926status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6927 uint32_t cmdSize,
6928 void *pCmdData,
6929 uint32_t *replySize,
6930 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006931{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006932 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006933// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006934
Eric Laurent21b5c472011-07-26 20:54:46 -07006935 if (mState == DESTROYED || mEffectInterface == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006936 return NO_INIT;
6937 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006938 status_t status = (*mEffectInterface)->command(mEffectInterface,
6939 cmdCode,
6940 cmdSize,
6941 pCmdData,
6942 replySize,
6943 pReplyData);
Eric Laurent65b65452010-06-01 23:49:17 -07006944 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006945 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07006946 for (size_t i = 1; i < mHandles.size(); i++) {
6947 sp<EffectHandle> h = mHandles[i].promote();
6948 if (h != 0) {
6949 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6950 }
6951 }
6952 }
6953 return status;
6954}
6955
6956status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6957{
Eric Laurent6752ec82011-08-10 10:37:50 -07006958
Eric Laurent65b65452010-06-01 23:49:17 -07006959 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006960 ALOGV("setEnabled %p enabled %d", this, enabled);
Eric Laurent65b65452010-06-01 23:49:17 -07006961
6962 if (enabled != isEnabled()) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006963 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6964 if (enabled && status != NO_ERROR) {
6965 return status;
6966 }
6967
Eric Laurent65b65452010-06-01 23:49:17 -07006968 switch (mState) {
6969 // going from disabled to enabled
6970 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07006971 mState = STARTING;
6972 break;
6973 case STOPPED:
6974 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07006975 break;
6976 case STOPPING:
6977 mState = ACTIVE;
6978 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006979
6980 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07006981 case RESTART:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006982 mState = STOPPED;
6983 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006984 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07006985 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07006986 break;
6987 case ACTIVE:
6988 mState = STOPPING;
6989 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006990 case DESTROYED:
6991 return NO_ERROR; // simply ignore as we are being destroyed
Eric Laurent65b65452010-06-01 23:49:17 -07006992 }
6993 for (size_t i = 1; i < mHandles.size(); i++) {
6994 sp<EffectHandle> h = mHandles[i].promote();
6995 if (h != 0) {
6996 h->setEnabled(enabled);
6997 }
6998 }
6999 }
7000 return NO_ERROR;
7001}
7002
Glenn Kasteneabd94a2012-02-02 14:06:11 -08007003bool AudioFlinger::EffectModule::isEnabled() const
Eric Laurent65b65452010-06-01 23:49:17 -07007004{
7005 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07007006 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07007007 case STARTING:
7008 case ACTIVE:
7009 return true;
7010 case IDLE:
7011 case STOPPING:
7012 case STOPPED:
Eric Laurent21b5c472011-07-26 20:54:46 -07007013 case DESTROYED:
Eric Laurent65b65452010-06-01 23:49:17 -07007014 default:
7015 return false;
7016 }
7017}
7018
Glenn Kasteneabd94a2012-02-02 14:06:11 -08007019bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurenta92ebfa2010-08-31 13:50:07 -07007020{
7021 switch (mState) {
7022 case RESTART:
7023 case ACTIVE:
7024 case STOPPING:
7025 case STOPPED:
7026 return true;
7027 case IDLE:
7028 case STARTING:
Eric Laurent21b5c472011-07-26 20:54:46 -07007029 case DESTROYED:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07007030 default:
7031 return false;
7032 }
7033}
7034
Eric Laurent65b65452010-06-01 23:49:17 -07007035status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7036{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07007037 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07007038 status_t status = NO_ERROR;
7039
7040 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7041 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurenta92ebfa2010-08-31 13:50:07 -07007042 if (isProcessEnabled() &&
Eric Laurent0d7e0482010-07-19 06:24:46 -07007043 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7044 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07007045 status_t cmdStatus;
7046 uint32_t volume[2];
7047 uint32_t *pVolume = NULL;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007048 uint32_t size = sizeof(volume);
Eric Laurent65b65452010-06-01 23:49:17 -07007049 volume[0] = *left;
7050 volume[1] = *right;
7051 if (controller) {
7052 pVolume = volume;
7053 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007054 status = (*mEffectInterface)->command(mEffectInterface,
7055 EFFECT_CMD_SET_VOLUME,
7056 size,
7057 volume,
7058 &size,
7059 pVolume);
Eric Laurent65b65452010-06-01 23:49:17 -07007060 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7061 *left = volume[0];
7062 *right = volume[1];
7063 }
7064 }
7065 return status;
7066}
7067
7068status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7069{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07007070 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07007071 status_t status = NO_ERROR;
Eric Laurent464d5b32011-06-17 21:29:58 -07007072 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7073 // audio pre processing modules on RecordThread can receive both output and
7074 // input device indication in the same call
7075 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7076 if (dev) {
7077 status_t cmdStatus;
7078 uint32_t size = sizeof(status_t);
7079
7080 status = (*mEffectInterface)->command(mEffectInterface,
7081 EFFECT_CMD_SET_DEVICE,
7082 sizeof(uint32_t),
7083 &dev,
7084 &size,
7085 &cmdStatus);
7086 if (status == NO_ERROR) {
7087 status = cmdStatus;
7088 }
7089 }
7090 dev = device & AUDIO_DEVICE_IN_ALL;
7091 if (dev) {
7092 status_t cmdStatus;
7093 uint32_t size = sizeof(status_t);
7094
7095 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7096 EFFECT_CMD_SET_INPUT_DEVICE,
7097 sizeof(uint32_t),
7098 &dev,
7099 &size,
7100 &cmdStatus);
7101 if (status2 == NO_ERROR) {
7102 status2 = cmdStatus;
7103 }
7104 if (status == NO_ERROR) {
7105 status = status2;
7106 }
Eric Laurent65b65452010-06-01 23:49:17 -07007107 }
7108 }
7109 return status;
7110}
7111
Glenn Kastenaccb1142012-01-04 11:00:47 -08007112status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07007113{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07007114 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07007115 status_t status = NO_ERROR;
7116 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Eric Laurent53334cd2010-06-23 17:38:20 -07007117 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007118 uint32_t size = sizeof(status_t);
7119 status = (*mEffectInterface)->command(mEffectInterface,
7120 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenaccb1142012-01-04 11:00:47 -08007121 sizeof(audio_mode_t),
Eric Laurent0fb66c22011-05-17 19:16:02 -07007122 &mode,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007123 &size,
7124 &cmdStatus);
Eric Laurent53334cd2010-06-23 17:38:20 -07007125 if (status == NO_ERROR) {
7126 status = cmdStatus;
7127 }
7128 }
7129 return status;
7130}
7131
Eric Laurentf82fccd2011-07-27 19:49:51 -07007132void AudioFlinger::EffectModule::setSuspended(bool suspended)
7133{
7134 Mutex::Autolock _l(mLock);
7135 mSuspended = suspended;
7136}
Glenn Kasten1dce8412012-01-04 11:01:11 -08007137
7138bool AudioFlinger::EffectModule::suspended() const
Eric Laurentf82fccd2011-07-27 19:49:51 -07007139{
7140 Mutex::Autolock _l(mLock);
7141 return mSuspended;
7142}
7143
Eric Laurent65b65452010-06-01 23:49:17 -07007144status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7145{
7146 const size_t SIZE = 256;
7147 char buffer[SIZE];
7148 String8 result;
7149
7150 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7151 result.append(buffer);
7152
7153 bool locked = tryLock(mLock);
7154 // failed to lock - AudioFlinger is probably deadlocked
7155 if (!locked) {
7156 result.append("\t\tCould not lock Fx mutex:\n");
7157 }
7158
7159 result.append("\t\tSession Status State Engine:\n");
7160 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7161 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7162 result.append(buffer);
7163
7164 result.append("\t\tDescriptor:\n");
7165 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7166 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7167 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7168 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7169 result.append(buffer);
7170 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7171 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7172 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7173 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7174 result.append(buffer);
Eric Laurent0fb66c22011-05-17 19:16:02 -07007175 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Eric Laurent65b65452010-06-01 23:49:17 -07007176 mDescriptor.apiVersion,
7177 mDescriptor.flags);
7178 result.append(buffer);
7179 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7180 mDescriptor.name);
7181 result.append(buffer);
7182 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7183 mDescriptor.implementor);
7184 result.append(buffer);
7185
7186 result.append("\t\t- Input configuration:\n");
7187 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7188 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7189 (uint32_t)mConfig.inputCfg.buffer.raw,
7190 mConfig.inputCfg.buffer.frameCount,
7191 mConfig.inputCfg.samplingRate,
7192 mConfig.inputCfg.channels,
7193 mConfig.inputCfg.format);
7194 result.append(buffer);
7195
7196 result.append("\t\t- Output configuration:\n");
7197 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7198 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7199 (uint32_t)mConfig.outputCfg.buffer.raw,
7200 mConfig.outputCfg.buffer.frameCount,
7201 mConfig.outputCfg.samplingRate,
7202 mConfig.outputCfg.channels,
7203 mConfig.outputCfg.format);
7204 result.append(buffer);
7205
7206 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7207 result.append(buffer);
7208 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7209 for (size_t i = 0; i < mHandles.size(); ++i) {
7210 sp<EffectHandle> handle = mHandles[i].promote();
7211 if (handle != 0) {
7212 handle->dump(buffer, SIZE);
7213 result.append(buffer);
7214 }
7215 }
7216
7217 result.append("\n");
7218
7219 write(fd, result.string(), result.length());
7220
7221 if (locked) {
7222 mLock.unlock();
7223 }
7224
7225 return NO_ERROR;
7226}
7227
7228// ----------------------------------------------------------------------------
7229// EffectHandle implementation
7230// ----------------------------------------------------------------------------
7231
7232#undef LOG_TAG
7233#define LOG_TAG "AudioFlinger::EffectHandle"
7234
7235AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7236 const sp<AudioFlinger::Client>& client,
7237 const sp<IEffectClient>& effectClient,
7238 int32_t priority)
7239 : BnEffect(),
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007240 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07007241 mPriority(priority), mHasControl(false), mEnabled(false)
Eric Laurent65b65452010-06-01 23:49:17 -07007242{
Steve Block71f2cf12011-10-20 11:56:00 +01007243 ALOGV("constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07007244
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007245 if (client == 0) {
7246 return;
7247 }
Eric Laurent65b65452010-06-01 23:49:17 -07007248 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7249 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7250 if (mCblkMemory != 0) {
7251 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7252
Glenn Kasten3694ec12012-01-27 16:47:15 -08007253 if (mCblk != NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07007254 new(mCblk) effect_param_cblk_t();
7255 mBuffer = (uint8_t *)mCblk + bufOffset;
7256 }
7257 } else {
Steve Block3762c312012-01-06 19:20:56 +00007258 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Eric Laurent65b65452010-06-01 23:49:17 -07007259 return;
7260 }
7261}
7262
7263AudioFlinger::EffectHandle::~EffectHandle()
7264{
Steve Block71f2cf12011-10-20 11:56:00 +01007265 ALOGV("Destructor %p", this);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007266 disconnect(false);
Steve Block71f2cf12011-10-20 11:56:00 +01007267 ALOGV("Destructor DONE %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07007268}
7269
7270status_t AudioFlinger::EffectHandle::enable()
7271{
Steve Block71f2cf12011-10-20 11:56:00 +01007272 ALOGV("enable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07007273 if (!mHasControl) return INVALID_OPERATION;
7274 if (mEffect == 0) return DEAD_OBJECT;
7275
Eric Laurent6752ec82011-08-10 10:37:50 -07007276 if (mEnabled) {
7277 return NO_ERROR;
7278 }
7279
Eric Laurentf82fccd2011-07-27 19:49:51 -07007280 mEnabled = true;
7281
7282 sp<ThreadBase> thread = mEffect->thread().promote();
7283 if (thread != 0) {
7284 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7285 }
7286
7287 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7288 if (mEffect->suspended()) {
7289 return NO_ERROR;
7290 }
7291
Eric Laurent6752ec82011-08-10 10:37:50 -07007292 status_t status = mEffect->setEnabled(true);
7293 if (status != NO_ERROR) {
7294 if (thread != 0) {
7295 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7296 }
7297 mEnabled = false;
7298 }
7299 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07007300}
7301
7302status_t AudioFlinger::EffectHandle::disable()
7303{
Steve Block71f2cf12011-10-20 11:56:00 +01007304 ALOGV("disable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07007305 if (!mHasControl) return INVALID_OPERATION;
Eric Laurentf82fccd2011-07-27 19:49:51 -07007306 if (mEffect == 0) return DEAD_OBJECT;
Eric Laurent65b65452010-06-01 23:49:17 -07007307
Eric Laurent6752ec82011-08-10 10:37:50 -07007308 if (!mEnabled) {
7309 return NO_ERROR;
7310 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007311 mEnabled = false;
7312
7313 if (mEffect->suspended()) {
7314 return NO_ERROR;
7315 }
7316
7317 status_t status = mEffect->setEnabled(false);
7318
7319 sp<ThreadBase> thread = mEffect->thread().promote();
7320 if (thread != 0) {
7321 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7322 }
7323
7324 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07007325}
7326
7327void AudioFlinger::EffectHandle::disconnect()
7328{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007329 disconnect(true);
7330}
7331
Glenn Kasten29441ff2012-02-03 10:32:24 -08007332void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007333{
Glenn Kasten29441ff2012-02-03 10:32:24 -08007334 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Eric Laurent65b65452010-06-01 23:49:17 -07007335 if (mEffect == 0) {
7336 return;
7337 }
Glenn Kasten29441ff2012-02-03 10:32:24 -08007338 mEffect->disconnect(this, unpinIfLast);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007339
Eric Laurent7fa1cee2011-10-19 11:44:54 -07007340 if (mHasControl && mEnabled) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007341 sp<ThreadBase> thread = mEffect->thread().promote();
7342 if (thread != 0) {
7343 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7344 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007345 }
7346
Eric Laurent65b65452010-06-01 23:49:17 -07007347 // release sp on module => module destructor can be called now
7348 mEffect.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07007349 if (mClient != 0) {
Glenn Kasten3694ec12012-01-27 16:47:15 -08007350 if (mCblk != NULL) {
Glenn Kastend9d68dc2012-02-03 10:24:48 -08007351 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007352 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7353 }
Glenn Kastenf31d0502012-01-25 15:27:15 -08007354 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten803a86a2012-01-25 14:28:29 -08007355 // Client destructor must run with AudioFlinger mutex locked
Eric Laurent65b65452010-06-01 23:49:17 -07007356 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7357 mClient.clear();
7358 }
7359}
7360
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007361status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7362 uint32_t cmdSize,
7363 void *pCmdData,
7364 uint32_t *replySize,
7365 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07007366{
Steve Block71f2cf12011-10-20 11:56:00 +01007367// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007368// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07007369
7370 // only get parameter command is permitted for applications not controlling the effect
7371 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7372 return INVALID_OPERATION;
7373 }
7374 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007375 if (mClient == 0) return INVALID_OPERATION;
Eric Laurent65b65452010-06-01 23:49:17 -07007376
7377 // handle commands that are not forwarded transparently to effect engine
7378 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7379 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7380 // no risk to block the whole media server process or mixer threads is we are stuck here
7381 Mutex::Autolock _l(mCblk->lock);
7382 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7383 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7384 mCblk->serverIndex = 0;
7385 mCblk->clientIndex = 0;
7386 return BAD_VALUE;
7387 }
7388 status_t status = NO_ERROR;
7389 while (mCblk->serverIndex < mCblk->clientIndex) {
7390 int reply;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007391 uint32_t rsize = sizeof(int);
Eric Laurent65b65452010-06-01 23:49:17 -07007392 int *p = (int *)(mBuffer + mCblk->serverIndex);
7393 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07007394 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block8564c8d2012-01-05 23:22:43 +00007395 ALOGW("command(): invalid parameter block size");
Eric Laurent53334cd2010-06-23 17:38:20 -07007396 break;
7397 }
Eric Laurent65b65452010-06-01 23:49:17 -07007398 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07007399 if (param->psize == 0 || param->vsize == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007400 ALOGW("command(): null parameter or value size");
Eric Laurent53334cd2010-06-23 17:38:20 -07007401 mCblk->serverIndex += size;
7402 continue;
7403 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007404 uint32_t psize = sizeof(effect_param_t) +
7405 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7406 param->vsize;
7407 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7408 psize,
7409 p,
7410 &rsize,
7411 &reply);
Eric Laurente65280c2010-09-02 11:56:55 -07007412 // stop at first error encountered
7413 if (ret != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07007414 status = ret;
Eric Laurente65280c2010-09-02 11:56:55 -07007415 *(int *)pReplyData = reply;
7416 break;
7417 } else if (reply != NO_ERROR) {
7418 *(int *)pReplyData = reply;
7419 break;
Eric Laurent65b65452010-06-01 23:49:17 -07007420 }
7421 mCblk->serverIndex += size;
7422 }
7423 mCblk->serverIndex = 0;
7424 mCblk->clientIndex = 0;
7425 return status;
7426 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07007427 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07007428 return enable();
7429 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07007430 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07007431 return disable();
7432 }
7433
7434 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7435}
7436
Eric Laurentf82fccd2011-07-27 19:49:51 -07007437void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Eric Laurent65b65452010-06-01 23:49:17 -07007438{
Steve Block71f2cf12011-10-20 11:56:00 +01007439 ALOGV("setControl %p control %d", this, hasControl);
Eric Laurent65b65452010-06-01 23:49:17 -07007440
7441 mHasControl = hasControl;
Eric Laurentf82fccd2011-07-27 19:49:51 -07007442 mEnabled = enabled;
7443
Eric Laurent65b65452010-06-01 23:49:17 -07007444 if (signal && mEffectClient != 0) {
7445 mEffectClient->controlStatusChanged(hasControl);
7446 }
7447}
7448
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007449void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7450 uint32_t cmdSize,
7451 void *pCmdData,
7452 uint32_t replySize,
7453 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07007454{
7455 if (mEffectClient != 0) {
7456 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7457 }
7458}
7459
7460
7461
7462void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7463{
7464 if (mEffectClient != 0) {
7465 mEffectClient->enableStatusChanged(enabled);
7466 }
7467}
7468
7469status_t AudioFlinger::EffectHandle::onTransact(
7470 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7471{
7472 return BnEffect::onTransact(code, data, reply, flags);
7473}
7474
7475
7476void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7477{
Glenn Kasten3694ec12012-01-27 16:47:15 -08007478 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Eric Laurent65b65452010-06-01 23:49:17 -07007479
7480 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten81211142012-02-05 18:09:08 -08007481 (mClient == 0) ? getpid_cached : mClient->pid(),
Eric Laurent65b65452010-06-01 23:49:17 -07007482 mPriority,
7483 mHasControl,
7484 !locked,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007485 mCblk ? mCblk->clientIndex : 0,
7486 mCblk ? mCblk->serverIndex : 0
Eric Laurent65b65452010-06-01 23:49:17 -07007487 );
7488
7489 if (locked) {
7490 mCblk->lock.unlock();
7491 }
7492}
7493
7494#undef LOG_TAG
7495#define LOG_TAG "AudioFlinger::EffectChain"
7496
Glenn Kasten685c9ce2012-01-20 13:32:16 -08007497AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Eric Laurent65b65452010-06-01 23:49:17 -07007498 int sessionId)
Glenn Kasten685c9ce2012-01-20 13:32:16 -08007499 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurent90681d62011-05-09 12:09:06 -07007500 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7501 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurent65b65452010-06-01 23:49:17 -07007502{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007503 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten685c9ce2012-01-20 13:32:16 -08007504 if (thread == NULL) {
Eric Laurentf9c361d2011-11-11 15:42:52 -08007505 return;
7506 }
7507 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7508 thread->frameCount();
Eric Laurent65b65452010-06-01 23:49:17 -07007509}
7510
7511AudioFlinger::EffectChain::~EffectChain()
7512{
7513 if (mOwnInBuffer) {
7514 delete mInBuffer;
7515 }
7516
7517}
7518
Eric Laurentf82fccd2011-07-27 19:49:51 -07007519// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007520sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07007521{
Eric Laurent65b65452010-06-01 23:49:17 -07007522 size_t size = mEffects.size();
7523
7524 for (size_t i = 0; i < size; i++) {
7525 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007526 return mEffects[i];
Eric Laurent65b65452010-06-01 23:49:17 -07007527 }
7528 }
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007529 return 0;
Eric Laurent65b65452010-06-01 23:49:17 -07007530}
7531
Eric Laurentf82fccd2011-07-27 19:49:51 -07007532// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007533sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07007534{
Eric Laurent65b65452010-06-01 23:49:17 -07007535 size_t size = mEffects.size();
7536
7537 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007538 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7539 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007540 return mEffects[i];
Eric Laurent65b65452010-06-01 23:49:17 -07007541 }
7542 }
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007543 return 0;
Eric Laurent65b65452010-06-01 23:49:17 -07007544}
7545
Eric Laurentf82fccd2011-07-27 19:49:51 -07007546// getEffectFromType_l() must be called with ThreadBase::mLock held
7547sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7548 const effect_uuid_t *type)
7549{
Eric Laurentf82fccd2011-07-27 19:49:51 -07007550 size_t size = mEffects.size();
7551
7552 for (size_t i = 0; i < size; i++) {
7553 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007554 return mEffects[i];
Eric Laurentf82fccd2011-07-27 19:49:51 -07007555 }
7556 }
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007557 return 0;
Eric Laurentf82fccd2011-07-27 19:49:51 -07007558}
7559
Eric Laurent65b65452010-06-01 23:49:17 -07007560// Must be called with EffectChain::mLock locked
7561void AudioFlinger::EffectChain::process_l()
7562{
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007563 sp<ThreadBase> thread = mThread.promote();
7564 if (thread == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007565 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007566 return;
7567 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007568 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7569 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007570 // always process effects unless no more tracks are on the session and the effect tail
7571 // has been rendered
7572 bool doProcess = true;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007573 if (!isGlobalSession) {
Eric Laurentf9c361d2011-11-11 15:42:52 -08007574 bool tracksOnSession = (trackCnt() != 0);
Eric Laurent90681d62011-05-09 12:09:06 -07007575
Eric Laurentf9c361d2011-11-11 15:42:52 -08007576 if (!tracksOnSession && mTailBufferCount == 0) {
7577 doProcess = false;
7578 }
7579
7580 if (activeTrackCnt() == 0) {
7581 // if no track is active and the effect tail has not been rendered,
7582 // the input buffer must be cleared here as the mixer process will not do it
7583 if (tracksOnSession || mTailBufferCount > 0) {
7584 size_t numSamples = thread->frameCount() * thread->channelCount();
7585 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7586 if (mTailBufferCount > 0) {
7587 mTailBufferCount--;
7588 }
7589 }
7590 }
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007591 }
7592
Eric Laurent65b65452010-06-01 23:49:17 -07007593 size_t size = mEffects.size();
Eric Laurentf9c361d2011-11-11 15:42:52 -08007594 if (doProcess) {
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007595 for (size_t i = 0; i < size; i++) {
7596 mEffects[i]->process();
7597 }
Eric Laurent65b65452010-06-01 23:49:17 -07007598 }
Eric Laurent7d850f22010-07-09 13:34:17 -07007599 for (size_t i = 0; i < size; i++) {
7600 mEffects[i]->updateState();
7601 }
Eric Laurent65b65452010-06-01 23:49:17 -07007602}
7603
Eric Laurent76c40f72010-07-15 12:50:15 -07007604// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007605status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007606{
7607 effect_descriptor_t desc = effect->desc();
7608 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7609
7610 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007611 effect->setChain(this);
7612 sp<ThreadBase> thread = mThread.promote();
7613 if (thread == 0) {
7614 return NO_INIT;
7615 }
7616 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07007617
7618 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7619 // Auxiliary effects are inserted at the beginning of mEffects vector as
7620 // they are processed first and accumulated in chain input buffer
7621 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007622
Eric Laurent65b65452010-06-01 23:49:17 -07007623 // the input buffer for auxiliary effect contains mono samples in
7624 // 32 bit format. This is to avoid saturation in AudoMixer
7625 // accumulation stage. Saturation is done in EffectModule::process() before
7626 // calling the process in effect engine
7627 size_t numSamples = thread->frameCount();
7628 int32_t *buffer = new int32_t[numSamples];
7629 memset(buffer, 0, numSamples * sizeof(int32_t));
7630 effect->setInBuffer((int16_t *)buffer);
7631 // auxiliary effects output samples to chain input buffer for further processing
7632 // by insert effects
7633 effect->setOutBuffer(mInBuffer);
7634 } else {
7635 // Insert effects are inserted at the end of mEffects vector as they are processed
7636 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07007637 // Insert effect order as a function of indicated preference:
7638 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7639 // another effect is present
7640 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7641 // last effect claiming first position
7642 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7643 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07007644 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07007645 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7646 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07007647
Glenn Kasten150d2382012-02-08 14:04:28 -08007648 size_t size = mEffects.size();
7649 size_t idx_insert = size;
7650 ssize_t idx_insert_first = -1;
7651 ssize_t idx_insert_last = -1;
Eric Laurent65b65452010-06-01 23:49:17 -07007652
Glenn Kasten150d2382012-02-08 14:04:28 -08007653 for (size_t i = 0; i < size; i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07007654 effect_descriptor_t d = mEffects[i]->desc();
7655 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7656 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7657 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7658 // check invalid effect chaining combinations
7659 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07007660 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block8564c8d2012-01-05 23:22:43 +00007661 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07007662 return INVALID_OPERATION;
7663 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007664 // remember position of first insert effect and by default
7665 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07007666 if (idx_insert == size) {
7667 idx_insert = i;
7668 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007669 // remember position of last insert effect claiming
7670 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07007671 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7672 idx_insert_first = i;
7673 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007674 // remember position of first insert effect claiming
7675 // last position
7676 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7677 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07007678 idx_insert_last = i;
7679 }
7680 }
7681 }
7682
Eric Laurent53334cd2010-06-23 17:38:20 -07007683 // modify idx_insert from first position if needed
7684 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7685 if (idx_insert_last != -1) {
7686 idx_insert = idx_insert_last;
7687 } else {
7688 idx_insert = size;
7689 }
7690 } else {
7691 if (idx_insert_first != -1) {
7692 idx_insert = idx_insert_first + 1;
7693 }
Eric Laurent65b65452010-06-01 23:49:17 -07007694 }
7695
7696 // always read samples from chain input buffer
7697 effect->setInBuffer(mInBuffer);
7698
7699 // if last effect in the chain, output samples to chain
7700 // output buffer, otherwise to chain input buffer
7701 if (idx_insert == size) {
7702 if (idx_insert != 0) {
7703 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7704 mEffects[idx_insert-1]->configure();
7705 }
7706 effect->setOutBuffer(mOutBuffer);
7707 } else {
7708 effect->setOutBuffer(mInBuffer);
7709 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007710 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007711
Steve Block71f2cf12011-10-20 11:56:00 +01007712 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007713 }
7714 effect->configure();
7715 return NO_ERROR;
7716}
7717
Eric Laurent76c40f72010-07-15 12:50:15 -07007718// removeEffect_l() must be called with PlaybackThread::mLock held
7719size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007720{
7721 Mutex::Autolock _l(mLock);
Glenn Kasten150d2382012-02-08 14:04:28 -08007722 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07007723 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7724
Glenn Kasten150d2382012-02-08 14:04:28 -08007725 for (size_t i = 0; i < size; i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07007726 if (effect == mEffects[i]) {
Eric Laurent21b5c472011-07-26 20:54:46 -07007727 // calling stop here will remove pre-processing effect from the audio HAL.
7728 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7729 // the middle of a read from audio HAL
Eric Laurent6fccbd02011-10-05 17:42:25 -07007730 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7731 mEffects[i]->state() == EffectModule::STOPPING) {
7732 mEffects[i]->stop();
7733 }
Eric Laurent65b65452010-06-01 23:49:17 -07007734 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7735 delete[] effect->inBuffer();
7736 } else {
7737 if (i == size - 1 && i != 0) {
7738 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7739 mEffects[i - 1]->configure();
7740 }
7741 }
7742 mEffects.removeAt(i);
Steve Block71f2cf12011-10-20 11:56:00 +01007743 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07007744 break;
7745 }
7746 }
Eric Laurent65b65452010-06-01 23:49:17 -07007747
7748 return mEffects.size();
7749}
7750
Eric Laurent76c40f72010-07-15 12:50:15 -07007751// setDevice_l() must be called with PlaybackThread::mLock held
7752void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07007753{
7754 size_t size = mEffects.size();
7755 for (size_t i = 0; i < size; i++) {
7756 mEffects[i]->setDevice(device);
7757 }
7758}
7759
Eric Laurent76c40f72010-07-15 12:50:15 -07007760// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenaccb1142012-01-04 11:00:47 -08007761void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07007762{
7763 size_t size = mEffects.size();
7764 for (size_t i = 0; i < size; i++) {
7765 mEffects[i]->setMode(mode);
7766 }
7767}
7768
Eric Laurent76c40f72010-07-15 12:50:15 -07007769// setVolume_l() must be called with PlaybackThread::mLock held
7770bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07007771{
7772 uint32_t newLeft = *left;
7773 uint32_t newRight = *right;
7774 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07007775 int ctrlIdx = -1;
7776 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07007777
Eric Laurent76c40f72010-07-15 12:50:15 -07007778 // first update volume controller
7779 for (size_t i = size; i > 0; i--) {
Eric Laurenta92ebfa2010-08-31 13:50:07 -07007780 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurent76c40f72010-07-15 12:50:15 -07007781 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7782 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007783 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07007784 break;
7785 }
7786 }
7787
7788 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07007789 if (hasControl) {
7790 *left = mNewLeftVolume;
7791 *right = mNewRightVolume;
7792 }
7793 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07007794 }
7795
7796 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007797 mLeftVolume = newLeft;
7798 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007799
7800 // second get volume update from volume controller
7801 if (ctrlIdx >= 0) {
7802 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07007803 mNewLeftVolume = newLeft;
7804 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07007805 }
7806 // then indicate volume to all other effects in chain.
7807 // Pass altered volume to effects before volume controller
7808 // and requested volume to effects after controller
7809 uint32_t lVol = newLeft;
7810 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007811
Eric Laurent65b65452010-06-01 23:49:17 -07007812 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07007813 if ((int)i == ctrlIdx) continue;
7814 // this also works for ctrlIdx == -1 when there is no volume controller
7815 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07007816 lVol = *left;
7817 rVol = *right;
7818 }
7819 mEffects[i]->setVolume(&lVol, &rVol, false);
7820 }
7821 *left = newLeft;
7822 *right = newRight;
7823
7824 return hasControl;
7825}
7826
Eric Laurent65b65452010-06-01 23:49:17 -07007827status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7828{
7829 const size_t SIZE = 256;
7830 char buffer[SIZE];
7831 String8 result;
7832
7833 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7834 result.append(buffer);
7835
7836 bool locked = tryLock(mLock);
7837 // failed to lock - AudioFlinger is probably deadlocked
7838 if (!locked) {
7839 result.append("\tCould not lock mutex:\n");
7840 }
7841
Eric Laurent76c40f72010-07-15 12:50:15 -07007842 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7843 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07007844 mEffects.size(),
7845 (uint32_t)mInBuffer,
7846 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07007847 mActiveTrackCnt);
7848 result.append(buffer);
7849 write(fd, result.string(), result.size());
7850
7851 for (size_t i = 0; i < mEffects.size(); ++i) {
7852 sp<EffectModule> effect = mEffects[i];
7853 if (effect != 0) {
7854 effect->dump(fd, args);
7855 }
7856 }
7857
7858 if (locked) {
7859 mLock.unlock();
7860 }
7861
7862 return NO_ERROR;
7863}
7864
Eric Laurentf82fccd2011-07-27 19:49:51 -07007865// must be called with ThreadBase::mLock held
7866void AudioFlinger::EffectChain::setEffectSuspended_l(
7867 const effect_uuid_t *type, bool suspend)
7868{
7869 sp<SuspendedEffectDesc> desc;
7870 // use effect type UUID timelow as key as there is no real risk of identical
7871 // timeLow fields among effect type UUIDs.
Glenn Kasten150d2382012-02-08 14:04:28 -08007872 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007873 if (suspend) {
7874 if (index >= 0) {
7875 desc = mSuspendedEffects.valueAt(index);
7876 } else {
7877 desc = new SuspendedEffectDesc();
7878 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7879 mSuspendedEffects.add(type->timeLow, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007880 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007881 }
7882 if (desc->mRefCount++ == 0) {
7883 sp<EffectModule> effect = getEffectIfEnabled(type);
7884 if (effect != 0) {
7885 desc->mEffect = effect;
7886 effect->setSuspended(true);
7887 effect->setEnabled(false);
7888 }
7889 }
7890 } else {
7891 if (index < 0) {
7892 return;
7893 }
7894 desc = mSuspendedEffects.valueAt(index);
7895 if (desc->mRefCount <= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007896 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007897 desc->mRefCount = 1;
7898 }
7899 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01007900 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007901 if (desc->mEffect != 0) {
7902 sp<EffectModule> effect = desc->mEffect.promote();
7903 if (effect != 0) {
7904 effect->setSuspended(false);
7905 sp<EffectHandle> handle = effect->controlHandle();
7906 if (handle != 0) {
7907 effect->setEnabled(handle->enabled());
7908 }
7909 }
7910 desc->mEffect.clear();
7911 }
7912 mSuspendedEffects.removeItemsAt(index);
7913 }
7914 }
7915}
7916
7917// must be called with ThreadBase::mLock held
7918void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7919{
7920 sp<SuspendedEffectDesc> desc;
7921
Glenn Kasten150d2382012-02-08 14:04:28 -08007922 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007923 if (suspend) {
7924 if (index >= 0) {
7925 desc = mSuspendedEffects.valueAt(index);
7926 } else {
7927 desc = new SuspendedEffectDesc();
7928 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007929 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurentf82fccd2011-07-27 19:49:51 -07007930 }
7931 if (desc->mRefCount++ == 0) {
Glenn Kasten97040262012-01-30 12:56:03 -08007932 Vector< sp<EffectModule> > effects;
7933 getSuspendEligibleEffects(effects);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007934 for (size_t i = 0; i < effects.size(); i++) {
7935 setEffectSuspended_l(&effects[i]->desc().type, true);
7936 }
7937 }
7938 } else {
7939 if (index < 0) {
7940 return;
7941 }
7942 desc = mSuspendedEffects.valueAt(index);
7943 if (desc->mRefCount <= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007944 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007945 desc->mRefCount = 1;
7946 }
7947 if (--desc->mRefCount == 0) {
7948 Vector<const effect_uuid_t *> types;
7949 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7950 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7951 continue;
7952 }
7953 types.add(&mSuspendedEffects.valueAt(i)->mType);
7954 }
7955 for (size_t i = 0; i < types.size(); i++) {
7956 setEffectSuspended_l(types[i], false);
7957 }
Steve Block71f2cf12011-10-20 11:56:00 +01007958 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007959 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7960 }
7961 }
7962}
7963
Eric Laurent5e7acae2011-09-23 08:40:41 -07007964
7965// The volume effect is used for automated tests only
7966#ifndef OPENSL_ES_H_
7967static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7968 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7969const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7970#endif //OPENSL_ES_H_
7971
Eric Laurent6752ec82011-08-10 10:37:50 -07007972bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7973{
7974 // auxiliary effects and visualizer are never suspended on output mix
7975 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7976 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent5e7acae2011-09-23 08:40:41 -07007977 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7978 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007979 return false;
7980 }
7981 return true;
7982}
7983
Glenn Kasten97040262012-01-30 12:56:03 -08007984void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurentf82fccd2011-07-27 19:49:51 -07007985{
Glenn Kasten97040262012-01-30 12:56:03 -08007986 effects.clear();
Eric Laurentf82fccd2011-07-27 19:49:51 -07007987 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kasten97040262012-01-30 12:56:03 -08007988 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
7989 effects.add(mEffects[i]);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007990 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007991 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007992}
7993
7994sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7995 const effect_uuid_t *type)
7996{
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007997 sp<EffectModule> effect = getEffectFromType_l(type);
7998 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurentf82fccd2011-07-27 19:49:51 -07007999}
8000
8001void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8002 bool enabled)
8003{
Glenn Kasten150d2382012-02-08 14:04:28 -08008004 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentf82fccd2011-07-27 19:49:51 -07008005 if (enabled) {
8006 if (index < 0) {
8007 // if the effect is not suspend check if all effects are suspended
8008 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8009 if (index < 0) {
8010 return;
8011 }
Eric Laurent6752ec82011-08-10 10:37:50 -07008012 if (!isEffectEligibleForSuspend(effect->desc())) {
8013 return;
8014 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07008015 setEffectSuspended_l(&effect->desc().type, enabled);
8016 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent6752ec82011-08-10 10:37:50 -07008017 if (index < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00008018 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurent6752ec82011-08-10 10:37:50 -07008019 return;
8020 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07008021 }
Steve Block71f2cf12011-10-20 11:56:00 +01008022 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07008023 effect->desc().type.timeLow);
8024 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8025 // if effect is requested to suspended but was not yet enabled, supend it now.
8026 if (desc->mEffect == 0) {
8027 desc->mEffect = effect;
8028 effect->setEnabled(false);
8029 effect->setSuspended(true);
8030 }
8031 } else {
8032 if (index < 0) {
8033 return;
8034 }
Steve Block71f2cf12011-10-20 11:56:00 +01008035 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07008036 effect->desc().type.timeLow);
8037 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8038 desc->mEffect.clear();
8039 effect->setSuspended(false);
8040 }
8041}
8042
Eric Laurent65b65452010-06-01 23:49:17 -07008043#undef LOG_TAG
8044#define LOG_TAG "AudioFlinger"
8045
Eric Laurenta553c252009-07-17 12:17:14 -07008046// ----------------------------------------------------------------------------
8047
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07008048status_t AudioFlinger::onTransact(
8049 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8050{
8051 return BnAudioFlinger::onTransact(code, data, reply, flags);
8052}
8053
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07008054}; // namespace android