blob: 97a8f8bf664ad0e71f0b95c4fed5943f596fc00a [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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Zavin31f188892011-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 Laurenteb8f850d2010-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 Laurenteb8f850d2010-05-14 03:26:45 -07001170 mAudioFlinger->mLock.lock();
Glenn Kasten4b220f02011-12-13 11:50:00 -08001171 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Eric Laurenteb8f850d2010-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()),
Eric Laurent464d5b32011-06-17 21:29:58 -07001465 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466{
Glenn Kasten86e33622012-02-28 12:30:08 -08001467 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001468
Eric Laurenta553c252009-07-17 12:17:14 -07001469 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470
Glenn Kasten6e987a42012-01-06 08:40:01 -08001471 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001472 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1473 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1474 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten8b02b992012-01-09 09:40:36 -08001475 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1476 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Glenn Kasten6e987a42012-01-06 08:40:01 -08001477 // initialized by stream_type_t default constructor
1478 // mStreamTypes[stream].valid = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 }
Glenn Kasten8b02b992012-01-09 09:40:36 -08001480 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1481 // because mAudioFlinger doesn't have one to copy from
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482}
1483
Eric Laurenta553c252009-07-17 12:17:14 -07001484AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485{
1486 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487}
1488
Eric Laurenta553c252009-07-17 12:17:14 -07001489status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490{
1491 dumpInternals(fd, args);
1492 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001493 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 return NO_ERROR;
1495}
1496
Eric Laurenta553c252009-07-17 12:17:14 -07001497status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498{
1499 const size_t SIZE = 256;
1500 char buffer[SIZE];
1501 String8 result;
1502
Eric Laurenta553c252009-07-17 12:17:14 -07001503 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001505 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 -08001506 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001507 sp<Track> track = mTracks[i];
1508 if (track != 0) {
1509 track->dump(buffer, SIZE);
1510 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 }
1512 }
1513
Eric Laurenta553c252009-07-17 12:17:14 -07001514 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001516 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 -08001517 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kastene4787422012-01-25 14:27:41 -08001518 sp<Track> track = mActiveTracks[i].promote();
1519 if (track != 0) {
1520 track->dump(buffer, SIZE);
1521 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 }
1523 }
1524 write(fd, result.string(), result.size());
1525 return NO_ERROR;
1526}
1527
Eric Laurenta553c252009-07-17 12:17:14 -07001528status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529{
1530 const size_t SIZE = 256;
1531 char buffer[SIZE];
1532 String8 result;
1533
Eric Laurent3fdb1262009-11-07 00:01:32 -08001534 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 result.append(buffer);
1536 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1537 result.append(buffer);
1538 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1539 result.append(buffer);
1540 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1541 result.append(buffer);
1542 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1543 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001544 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1545 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001546 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1547 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001549
1550 dumpBase(fd, args);
1551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 return NO_ERROR;
1553}
1554
1555// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001556status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557{
Eric Laurent828b9772011-08-07 16:32:26 -07001558 status_t status = initCheck();
1559 if (status == NO_ERROR) {
Steve Block6215d3f2012-01-04 20:05:49 +00001560 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurent828b9772011-08-07 16:32:26 -07001561 } else {
Steve Block3762c312012-01-06 19:20:56 +00001562 ALOGE("No working audio driver found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 }
Eric Laurent828b9772011-08-07 16:32:26 -07001564 return status;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565}
1566
Eric Laurenta553c252009-07-17 12:17:14 -07001567void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001569 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570}
1571
Eric Laurenta553c252009-07-17 12:17:14 -07001572// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1573sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 const sp<AudioFlinger::Client>& client,
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001575 audio_stream_type_t streamType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08001577 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001578 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 int frameCount,
1580 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001581 int sessionId,
John Grossmand8cf2962012-02-08 16:37:41 -08001582 bool isTimed,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 status_t *status)
1584{
1585 sp<Track> track;
1586 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001587
1588 if (mType == DIRECT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001589 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1590 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block3762c312012-01-06 19:20:56 +00001591 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001592 "for output %p with format %d",
1593 sampleRate, format, channelMask, mOutput, mFormat);
1594 lStatus = BAD_VALUE;
1595 goto Exit;
1596 }
Eric Laurenta553c252009-07-17 12:17:14 -07001597 }
1598 } else {
1599 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1600 if (sampleRate > mSampleRate*2) {
Steve Block3762c312012-01-06 19:20:56 +00001601 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Eric Laurenta553c252009-07-17 12:17:14 -07001602 lStatus = BAD_VALUE;
1603 goto Exit;
1604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 }
1606
Eric Laurent464d5b32011-06-17 21:29:58 -07001607 lStatus = initCheck();
1608 if (lStatus != NO_ERROR) {
Steve Block3762c312012-01-06 19:20:56 +00001609 ALOGE("Audio driver not initialized.");
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001610 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 }
1612
Eric Laurenta553c252009-07-17 12:17:14 -07001613 { // scope for mLock
1614 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001615
1616 // all tracks in same audio session must share the same routing strategy otherwise
1617 // conflicts will happen when tracks are moved from one output to another by audio policy
1618 // manager
Glenn Kastenaae26c82012-02-08 12:35:35 -08001619 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001620 for (size_t i = 0; i < mTracks.size(); ++i) {
1621 sp<Track> t = mTracks[i];
1622 if (t != 0) {
Glenn Kastenaae26c82012-02-08 12:35:35 -08001623 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kasten9818a9d2011-10-28 10:31:42 -07001624 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block3762c312012-01-06 19:20:56 +00001625 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kasten9818a9d2011-10-28 10:31:42 -07001626 strategy, actual);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001627 lStatus = BAD_VALUE;
1628 goto Exit;
1629 }
1630 }
1631 }
1632
John Grossmand8cf2962012-02-08 16:37:41 -08001633 if (!isTimed) {
1634 track = new Track(this, client, streamType, sampleRate, format,
1635 channelMask, frameCount, sharedBuffer, sessionId);
1636 } else {
1637 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1638 channelMask, frameCount, sharedBuffer, sessionId);
1639 }
1640 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001641 lStatus = NO_MEMORY;
1642 goto Exit;
1643 }
1644 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001645
1646 sp<EffectChain> chain = getEffectChain_l(sessionId);
1647 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001648 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Eric Laurent65b65452010-06-01 23:49:17 -07001649 track->setMainBuffer(chain->inBuffer());
Glenn Kastenaae26c82012-02-08 12:35:35 -08001650 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurent90681d62011-05-09 12:09:06 -07001651 chain->incTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001652 }
Eric Laurent05ce0942011-08-30 10:18:54 -07001653
1654 // invalidate track immediately if the stream type was moved to another thread since
1655 // createTrack() was called by the client process.
1656 if (!mStreamTypes[streamType].valid) {
Steve Block8564c8d2012-01-05 23:22:43 +00001657 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent05ce0942011-08-30 10:18:54 -07001658 this, streamType);
1659 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1660 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001661 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001662 lStatus = NO_ERROR;
1663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664Exit:
1665 if(status) {
1666 *status = lStatus;
1667 }
1668 return track;
1669}
1670
Eric Laurenta553c252009-07-17 12:17:14 -07001671uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672{
Eric Laurent828b9772011-08-07 16:32:26 -07001673 Mutex::Autolock _l(mLock);
1674 if (initCheck() == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07001675 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurent828b9772011-08-07 16:32:26 -07001676 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 return 0;
1678 }
1679}
1680
Glenn Kasten8b02b992012-01-09 09:40:36 -08001681void AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682{
Glenn Kasten8b02b992012-01-09 09:40:36 -08001683 Mutex::Autolock _l(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 mMasterVolume = value;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685}
1686
Glenn Kasten8b02b992012-01-09 09:40:36 -08001687void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688{
Glenn Kasten8b02b992012-01-09 09:40:36 -08001689 Mutex::Autolock _l(mLock);
1690 setMasterMute_l(muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691}
1692
Glenn Kasten8b02b992012-01-09 09:40:36 -08001693void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694{
Glenn Kasten8b02b992012-01-09 09:40:36 -08001695 Mutex::Autolock _l(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 mStreamTypes[stream].volume = value;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697}
1698
Glenn Kasten8b02b992012-01-09 09:40:36 -08001699void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700{
Glenn Kasten8b02b992012-01-09 09:40:36 -08001701 Mutex::Autolock _l(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702 mStreamTypes[stream].mute = muted;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703}
1704
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001705float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706{
Glenn Kasten8b02b992012-01-09 09:40:36 -08001707 Mutex::Autolock _l(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 return mStreamTypes[stream].volume;
1709}
1710
Eric Laurenta553c252009-07-17 12:17:14 -07001711// addTrack_l() must be called with ThreadBase::mLock held
1712status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713{
1714 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001715
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001716 // set retry count for buffer fill
1717 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001718 if (mActiveTracks.indexOf(track) < 0) {
1719 // the track is newly added, make sure it fills up all its
1720 // buffers before playing. This is to ensure the client will
1721 // effectively get the latency it requested.
1722 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001723 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001724 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001725 if (track->mainBuffer() != mMixBuffer) {
1726 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1727 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001728 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07001729 chain->incActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001730 }
1731 }
1732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001734 }
Eric Laurenta553c252009-07-17 12:17:14 -07001735
Steve Block71f2cf12011-10-20 11:56:00 +01001736 ALOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001737 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738
1739 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001740}
1741
Eric Laurenta553c252009-07-17 12:17:14 -07001742// destroyTrack_l() must be called with ThreadBase::mLock held
1743void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001744{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001745 track->mState = TrackBase::TERMINATED;
1746 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent90681d62011-05-09 12:09:06 -07001747 removeTrack_l(track);
1748 }
1749}
1750
1751void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1752{
1753 mTracks.remove(track);
1754 deleteTrackName_l(track->name());
1755 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1756 if (chain != 0) {
1757 chain->decTrackCnt();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001758 }
1759}
1760
Eric Laurenta553c252009-07-17 12:17:14 -07001761String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001762{
Eric Laurent828b9772011-08-07 16:32:26 -07001763 String8 out_s8 = String8("");
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001764 char *s;
1765
Eric Laurent828b9772011-08-07 16:32:26 -07001766 Mutex::Autolock _l(mLock);
1767 if (initCheck() != NO_ERROR) {
1768 return out_s8;
1769 }
1770
Dima Zavin31f188892011-04-18 16:57:27 -07001771 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001772 out_s8 = String8(s);
1773 free(s);
1774 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07001775}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001776
Eric Laurent828b9772011-08-07 16:32:26 -07001777// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001778void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001779 AudioSystem::OutputDescriptor desc;
Glenn Kasten3694ec12012-01-27 16:47:15 -08001780 void *param2 = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07001781
Steve Block71f2cf12011-10-20 11:56:00 +01001782 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001783
1784 switch (event) {
1785 case AudioSystem::OUTPUT_OPENED:
1786 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001787 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07001788 desc.samplingRate = mSampleRate;
1789 desc.format = mFormat;
1790 desc.frameCount = mFrameCount;
1791 desc.latency = latency();
1792 param2 = &desc;
1793 break;
1794
1795 case AudioSystem::STREAM_CONFIG_CHANGED:
1796 param2 = &param;
1797 case AudioSystem::OUTPUT_CLOSED:
1798 default:
1799 break;
1800 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001801 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001802}
1803
1804void AudioFlinger::PlaybackThread::readOutputParameters()
1805{
Dima Zavin31f188892011-04-18 16:57:27 -07001806 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001807 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1808 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07001809 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenfaf354d2012-01-11 09:48:27 -08001810 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin31f188892011-04-18 16:57:27 -07001811 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001812
Eric Laurenta553c252009-07-17 12:17:14 -07001813 // FIXME - Current mixer implementation only supports stereo output: Always
1814 // Allocate a stereo buffer even if HW output is mono.
Glenn Kasten2589cf92012-01-27 18:08:45 -08001815 delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001816 mMixBuffer = new int16_t[mFrameCount * 2];
1817 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001818
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001819 // force reconfiguration of effect chains and engines to take new buffer size and audio
1820 // parameters into account
1821 // Note that mLock is not held when readOutputParameters() is called from the constructor
1822 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1823 // matter.
1824 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1825 Vector< sp<EffectChain> > effectChains = mEffectChains;
1826 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent493941b2010-07-28 01:32:47 -07001827 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001828 }
Eric Laurenta553c252009-07-17 12:17:14 -07001829}
1830
Eric Laurent0986e792010-01-19 17:37:09 -08001831status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1832{
Glenn Kasten3694ec12012-01-27 16:47:15 -08001833 if (halFrames == NULL || dspFrames == NULL) {
Eric Laurent0986e792010-01-19 17:37:09 -08001834 return BAD_VALUE;
1835 }
Eric Laurent828b9772011-08-07 16:32:26 -07001836 Mutex::Autolock _l(mLock);
Eric Laurent464d5b32011-06-17 21:29:58 -07001837 if (initCheck() != NO_ERROR) {
Eric Laurent0986e792010-01-19 17:37:09 -08001838 return INVALID_OPERATION;
1839 }
Dima Zavin31f188892011-04-18 16:57:27 -07001840 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Eric Laurent0986e792010-01-19 17:37:09 -08001841
Dima Zavin31f188892011-04-18 16:57:27 -07001842 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Eric Laurent0986e792010-01-19 17:37:09 -08001843}
1844
Eric Laurent493941b2010-07-28 01:32:47 -07001845uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Eric Laurent65b65452010-06-01 23:49:17 -07001846{
1847 Mutex::Autolock _l(mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07001848 uint32_t result = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001849 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent493941b2010-07-28 01:32:47 -07001850 result = EFFECT_SESSION;
Eric Laurent65b65452010-06-01 23:49:17 -07001851 }
1852
1853 for (size_t i = 0; i < mTracks.size(); ++i) {
1854 sp<Track> track = mTracks[i];
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001855 if (sessionId == track->sessionId() &&
1856 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent493941b2010-07-28 01:32:47 -07001857 result |= TRACK_SESSION;
1858 break;
Eric Laurent65b65452010-06-01 23:49:17 -07001859 }
1860 }
1861
Eric Laurent493941b2010-07-28 01:32:47 -07001862 return result;
Eric Laurent65b65452010-06-01 23:49:17 -07001863}
1864
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001865uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1866{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001867 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001868 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001869 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1870 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001871 }
1872 for (size_t i = 0; i < mTracks.size(); i++) {
1873 sp<Track> track = mTracks[i];
1874 if (sessionId == track->sessionId() &&
1875 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kastenaae26c82012-02-08 12:35:35 -08001876 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001877 }
1878 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001879 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001880}
1881
Eric Laurent53334cd2010-06-23 17:38:20 -07001882
Glenn Kasten5b0135e2012-01-26 09:46:34 -08001883AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent828b9772011-08-07 16:32:26 -07001884{
1885 Mutex::Autolock _l(mLock);
1886 return mOutput;
1887}
1888
1889AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1890{
1891 Mutex::Autolock _l(mLock);
1892 AudioStreamOut *output = mOutput;
1893 mOutput = NULL;
1894 return output;
1895}
1896
1897// this method must always be called either with ThreadBase mLock held or inside the thread loop
1898audio_stream_t* AudioFlinger::PlaybackThread::stream()
1899{
1900 if (mOutput == NULL) {
1901 return NULL;
1902 }
1903 return &mOutput->stream->common;
1904}
1905
Eric Laurent44331692011-12-05 09:47:19 -08001906uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1907{
1908 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1909 // decoding and transfer time. So sleeping for half of the latency would likely cause
1910 // underruns
1911 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1912 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1913 } else {
1914 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1915 }
1916}
1917
Eric Laurenta553c252009-07-17 12:17:14 -07001918// ----------------------------------------------------------------------------
1919
Glenn Kastenefd511a2012-01-26 10:38:26 -08001920AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten39d00cb2012-01-17 11:09:42 -08001921 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten67cb3122012-03-01 17:10:56 -08001922 : PlaybackThread(audioFlinger, output, id, device, type)
Eric Laurenta553c252009-07-17 12:17:14 -07001923{
Glenn Kasten67cb3122012-03-01 17:10:56 -08001924 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1925 mPrevMixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001926 // FIXME - Current mixer implementation only supports stereo output
1927 if (mChannelCount == 1) {
Steve Block3762c312012-01-06 19:20:56 +00001928 ALOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001930}
1931
Eric Laurenta553c252009-07-17 12:17:14 -07001932AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001933{
Eric Laurenta553c252009-07-17 12:17:14 -07001934 delete mAudioMixer;
1935}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936
Glenn Kasten6ec27552012-02-24 07:21:32 -08001937class CpuStats {
1938public:
1939 void sample();
1940#ifdef DEBUG_CPU_USAGE
1941private:
1942 ThreadCpuUsage mCpu;
1943#endif
1944};
1945
1946void CpuStats::sample() {
1947#ifdef DEBUG_CPU_USAGE
1948 const CentralTendencyStatistics& stats = mCpu.statistics();
1949 mCpu.sampleAndEnable();
1950 unsigned n = stats.n();
1951 // mCpu.elapsed() is expensive, so don't call it every loop
1952 if ((n & 127) == 1) {
1953 long long elapsed = mCpu.elapsed();
1954 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1955 double perLoop = elapsed / (double) n;
1956 double perLoop100 = perLoop * 0.01;
1957 double mean = stats.mean();
1958 double stddev = stats.stddev();
1959 double minimum = stats.minimum();
1960 double maximum = stats.maximum();
1961 mCpu.resetStatistics();
1962 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",
1963 elapsed * .000000001, n, perLoop * .000001,
1964 mean * .001,
1965 stddev * .001,
1966 minimum * .001,
1967 maximum * .001,
1968 mean / perLoop100,
1969 stddev / perLoop100,
1970 minimum / perLoop100,
1971 maximum / perLoop100);
1972 }
1973 }
1974#endif
1975};
1976
Glenn Kasten2521a012012-02-24 07:21:48 -08001977void AudioFlinger::PlaybackThread::checkSilentMode_l()
1978{
1979 if (!mMasterMute) {
1980 char value[PROPERTY_VALUE_MAX];
1981 if (property_get("ro.audio.silent", value, "0") > 0) {
1982 char *endptr;
1983 unsigned long ul = strtoul(value, &endptr, 0);
1984 if (*endptr == '\0' && ul != 0) {
1985 ALOGD("Silence is golden");
1986 // The setprop command will not allow a property to be changed after
1987 // the first time it is set, so we don't have to worry about un-muting.
1988 setMasterMute_l(true);
1989 }
1990 }
1991 }
1992}
1993
Glenn Kasten67cb3122012-03-01 17:10:56 -08001994bool AudioFlinger::PlaybackThread::threadLoop()
Eric Laurenta553c252009-07-17 12:17:14 -07001995{
Glenn Kasten67cb3122012-03-01 17:10:56 -08001996 // MIXER || DUPLICATING
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 // DIRECT
2000 sp<Track> trackToRemove;
2001
2002 standbyTime = systemTime();
2003 mixBufferSize = mFrameCount * mFrameSize;
2004
2005 // MIXER
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002006 // FIXME: Relaxed timing because of a certain device that can't meet latency
2007 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07002008 // increase threshold again due to low power audio mode. The way this warning threshold is
2009 // calculated and its usefulness should be reconsidered anyway.
2010 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002011 nsecs_t lastWarning = 0;
Glenn Kasten67cb3122012-03-01 17:10:56 -08002012if (mType == MIXER) {
2013 longStandbyExit = false;
2014}
Glenn Kastenbea6b952012-02-29 07:57:06 -08002015
Glenn Kasten67cb3122012-03-01 17:10:56 -08002016 // DUPLICATING
2017 // FIXME could this be made local to while loop?
2018 writeFrames = 0;
Glenn Kastenbea6b952012-02-29 07:57:06 -08002019
Glenn Kasten67cb3122012-03-01 17:10:56 -08002020 activeSleepTime = activeSleepTimeUs();
2021 idleSleepTime = idleSleepTimeUs();
2022 sleepTime = idleSleepTime;
2023
2024if (mType == MIXER) {
2025 sleepTimeShift = 0;
2026}
2027
2028 // MIXER
Glenn Kasten6ec27552012-02-24 07:21:32 -08002029 CpuStats cpuStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030
Glenn Kasten67cb3122012-03-01 17:10:56 -08002031 // DIRECT
2032if (mType == DIRECT) {
2033 // use shorter standby delay as on normal output to release
2034 // hardware resources as soon as possible
2035 standbyDelay = microseconds(activeSleepTime*2);
2036}
Glenn Kastenbea6b952012-02-29 07:57:06 -08002037
Eric Laurent6dbdc402011-07-22 09:04:31 -07002038 acquireWakeLock();
2039
Eric Laurenta553c252009-07-17 12:17:14 -07002040 while (!exitPending())
2041 {
Glenn Kasten67cb3122012-03-01 17:10:56 -08002042if (mType == MIXER) {
Glenn Kasten6ec27552012-02-24 07:21:32 -08002043 cpuStats.sample();
Glenn Kasten67cb3122012-03-01 17:10:56 -08002044}
Glenn Kastenbea6b952012-02-29 07:57:06 -08002045
Glenn Kasten3c4f0dc2012-02-29 07:56:15 -08002046 Vector< sp<EffectChain> > effectChains;
2047
Eric Laurenta553c252009-07-17 12:17:14 -07002048 processConfigEvents();
2049
Glenn Kasten67cb3122012-03-01 17:10:56 -08002050if (mType == DIRECT) {
2051 activeTrack.clear();
2052}
2053
2054 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002055 { // scope for mLock
2056
2057 Mutex::Autolock _l(mLock);
2058
2059 if (checkForNewParameters_l()) {
2060 mixBufferSize = mFrameCount * mFrameSize;
Glenn Kastenbea6b952012-02-29 07:57:06 -08002061
Glenn Kasten67cb3122012-03-01 17:10:56 -08002062if (mType == MIXER) {
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002063 // FIXME: Relaxed timing because of a certain device that can't meet latency
2064 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07002065 // increase threshold again due to low power audio mode. The way this warning
2066 // threshold is calculated and its usefulness should be reconsidered anyway.
2067 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Glenn Kasten67cb3122012-03-01 17:10:56 -08002068}
2069
Glenn Kasten2bad67f2012-03-06 11:24:48 -08002070 updateWaitTime_l();
Glenn Kastenbea6b952012-02-29 07:57:06 -08002071
Eric Laurent059b4be2009-11-09 23:32:22 -08002072 activeSleepTime = activeSleepTimeUs();
2073 idleSleepTime = idleSleepTimeUs();
Glenn Kasten67cb3122012-03-01 17:10:56 -08002074
2075if (mType == DIRECT) {
2076 standbyDelay = microseconds(activeSleepTime*2);
2077}
2078
Eric Laurenta553c252009-07-17 12:17:14 -07002079 }
2080
Glenn Kasten67cb3122012-03-01 17:10:56 -08002081if (mType == DUPLICATING) {
2082#if 0 // see earlier FIXME
2083 // Now that this is a field instead of local variable,
2084 // clear it so it is empty the first time through the loop,
2085 // and later an assignment could combine the clear with the loop below
2086 outputTracks.clear();
2087#endif
2088 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2089 outputTracks.add(mOutputTracks[i]);
2090 }
2091}
2092
Eric Laurenta553c252009-07-17 12:17:14 -07002093 // put audio hardware into standby after short delay
Glenn Kastend9cccfa2012-02-28 18:40:35 -08002094 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastene70583e2012-02-29 07:07:30 -08002095 mSuspended > 0)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002096 if (!mStandby) {
Glenn Kasten67cb3122012-03-01 17:10:56 -08002097
2098 threadLoop_standby();
2099
Eric Laurenta553c252009-07-17 12:17:14 -07002100 mStandby = true;
2101 mBytesWritten = 0;
2102 }
2103
Glenn Kastend9cccfa2012-02-28 18:40:35 -08002104 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002105 // we're about to wait, flush the binder command buffer
2106 IPCThreadState::self()->flushCommands();
2107
Glenn Kasten67cb3122012-03-01 17:10:56 -08002108if (mType == DUPLICATING) {
2109 outputTracks.clear();
2110}
2111
Eric Laurenta553c252009-07-17 12:17:14 -07002112 if (exitPending()) break;
2113
Eric Laurent6dbdc402011-07-22 09:04:31 -07002114 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002115 // wait until we have something to do...
Glenn Kasten3be2bc02012-02-24 11:18:09 -08002116 ALOGV("Thread %p type %d TID %d going to sleep", this, mType, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07002117 mWaitWorkCV.wait(mLock);
Glenn Kasten3be2bc02012-02-24 11:18:09 -08002118 ALOGV("Thread %p type %d TID %d waking up", this, mType, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07002119 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002120
Glenn Kasten67cb3122012-03-01 17:10:56 -08002121if (mType == MIXER || mType == DUPLICATING) {
Eric Laurent71c44962012-01-17 19:20:12 -08002122 mPrevMixerStatus = MIXER_IDLE;
Glenn Kasten67cb3122012-03-01 17:10:56 -08002123}
2124
Glenn Kasten2521a012012-02-24 07:21:48 -08002125 checkSilentMode_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002126
Glenn Kasten67cb3122012-03-01 17:10:56 -08002127if (mType == MIXER || mType == DUPLICATING) {
John Grossmand8cf2962012-02-08 16:37:41 -08002128 standbyTime = systemTime() + mStandbyTimeInNsecs;
Glenn Kasten67cb3122012-03-01 17:10:56 -08002129}
2130
2131if (mType == DIRECT) {
2132 standbyTime = systemTime() + standbyDelay;
2133}
2134
Eric Laurent059b4be2009-11-09 23:32:22 -08002135 sleepTime = idleSleepTime;
Glenn Kasten67cb3122012-03-01 17:10:56 -08002136
2137if (mType == MIXER) {
Eric Laurentf1f5fc82011-11-22 18:50:29 -08002138 sleepTimeShift = 0;
Glenn Kasten67cb3122012-03-01 17:10:56 -08002139}
2140
Eric Laurenta553c252009-07-17 12:17:14 -07002141 continue;
2142 }
2143 }
2144
Glenn Kasten67cb3122012-03-01 17:10:56 -08002145// FIXME merge these
2146if (mType == MIXER || mType == DUPLICATING) {
Glenn Kastend9cccfa2012-02-28 18:40:35 -08002147 mixerStatus = prepareTracks_l(&tracksToRemove);
Glenn Kasten67cb3122012-03-01 17:10:56 -08002148}
2149if (mType == DIRECT) {
2150 mixerStatus = threadLoop_prepareTracks_l(trackToRemove);
2151 // see FIXME in AudioFlinger.h
2152 if (mixerStatus == MIXER_CONTINUE) {
2153 continue;
2154 }
2155}
Eric Laurent65b65452010-06-01 23:49:17 -07002156
2157 // prevent any changes in effect chain list and in each effect chain
2158 // during mixing and effect process as the audio buffers could be deleted
2159 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002160 lockEffectChains_l(effectChains);
Glenn Kastenfb2ab9e2011-12-12 09:05:55 -08002161 }
Eric Laurenta553c252009-07-17 12:17:14 -07002162
Glenn Kasten67cb3122012-03-01 17:10:56 -08002163if (mType == DIRECT) {
2164 // For DirectOutputThread, this test is equivalent to "activeTrack != 0"
2165}
2166
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002167 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten67cb3122012-03-01 17:10:56 -08002168 threadLoop_mix();
2169 } else {
2170 threadLoop_sleepTime();
2171 }
2172
2173 if (mSuspended > 0) {
2174 sleepTime = suspendSleepTimeUs();
2175 }
2176
2177 // only process effects if we're going to write
2178 if (sleepTime == 0) {
2179
2180 if (mixerStatus == MIXER_TRACKS_READY) {
2181
2182 // Non-trivial for DIRECT only
2183 applyVolume();
2184
2185 }
2186
2187 for (size_t i = 0; i < effectChains.size(); i ++) {
2188 effectChains[i]->process_l();
2189 }
2190 }
2191
2192 // enable changes in effect chain
2193 unlockEffectChains(effectChains);
2194
2195 // sleepTime == 0 means we must write to audio hardware
2196 if (sleepTime == 0) {
2197
2198 threadLoop_write();
2199
2200if (mType == MIXER) {
2201 // write blocked detection
2202 nsecs_t now = systemTime();
2203 nsecs_t delta = now - mLastWriteTime;
2204 if (!mStandby && delta > maxPeriod) {
2205 mNumDelayedWrites++;
2206 if ((now - lastWarning) > kWarningThrottleNs) {
2207 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2208 ns2ms(delta), mNumDelayedWrites, this);
2209 lastWarning = now;
2210 }
2211 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2212 // a different threshold. Or completely removed for what it is worth anyway...
2213 if (mStandby) {
2214 longStandbyExit = true;
2215 }
2216 }
2217}
2218
2219 mStandby = false;
2220 } else {
2221 usleep(sleepTime);
2222 }
2223
2224 // finally let go of removed track(s), without the lock held
2225 // since we can't guarantee the destructors won't acquire that
2226 // same lock.
2227
2228// FIXME merge these
2229if (mType == MIXER) {
2230 tracksToRemove.clear();
2231}
2232if (mType == DIRECT) {
2233 trackToRemove.clear();
2234 activeTrack.clear();
2235}
2236if (mType == DUPLICATING) {
2237 tracksToRemove.clear();
2238 outputTracks.clear();
2239}
2240
2241 // Effect chains will be actually deleted here if they were removed from
2242 // mEffectChains list during mixing or effects processing
2243 effectChains.clear();
2244
2245 // FIXME Note that the above .clear() is no longer necessary since effectChains
2246 // is now local to this block, but will keep it for now (at least until merge done).
2247 }
2248
2249if (mType == MIXER || mType == DIRECT) {
2250 // put output stream into standby mode
2251 if (!mStandby) {
2252 mOutput->stream->common.standby(&mOutput->stream->common);
2253 }
2254}
2255if (mType == DUPLICATING) {
2256 // for DuplicatingThread, standby mode is handled by the outputTracks
2257}
2258
2259 releaseWakeLock();
2260
2261 ALOGV("Thread %p type %d exiting", this, mType);
2262 return false;
2263}
2264
2265// shared by MIXER and DIRECT, overridden by DUPLICATING
2266void AudioFlinger::PlaybackThread::threadLoop_write()
2267{
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002268 // FIXME rewrite to reduce number of system calls
2269 mLastWriteTime = systemTime();
2270 mInWrite = true;
2271 mBytesWritten += mixBufferSize;
2272 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2273 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2274 mNumWrites++;
2275 mInWrite = false;
Glenn Kasten67cb3122012-03-01 17:10:56 -08002276}
2277
2278// shared by MIXER and DIRECT, overridden by DUPLICATING
2279void AudioFlinger::PlaybackThread::threadLoop_standby()
2280{
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002281 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2282 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten67cb3122012-03-01 17:10:56 -08002283}
2284
2285void AudioFlinger::MixerThread::threadLoop_mix()
2286{
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002287 // obtain the presentation timestamp of the next output buffer
2288 int64_t pts;
2289 status_t status = INVALID_OPERATION;
John Grossmand8cf2962012-02-08 16:37:41 -08002290
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002291 if (NULL != mOutput->stream->get_next_write_timestamp) {
2292 status = mOutput->stream->get_next_write_timestamp(
2293 mOutput->stream, &pts);
2294 }
John Grossmand8cf2962012-02-08 16:37:41 -08002295
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002296 if (status != NO_ERROR) {
2297 pts = AudioBufferProvider::kInvalidPTS;
2298 }
John Grossmand8cf2962012-02-08 16:37:41 -08002299
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002300 // mix buffers...
2301 mAudioMixer->process(pts);
2302 // increase sleep time progressively when application underrun condition clears.
2303 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2304 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2305 // such that we would underrun the audio HAL.
2306 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2307 sleepTimeShift--;
2308 }
2309 sleepTime = 0;
2310 standbyTime = systemTime() + mStandbyTimeInNsecs;
2311 //TODO: delay standby when effects have a tail
Glenn Kasten67cb3122012-03-01 17:10:56 -08002312}
2313
2314void AudioFlinger::MixerThread::threadLoop_sleepTime()
2315{
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002316 // If no tracks are ready, sleep once for the duration of an output
2317 // buffer size, then write 0s to the output
2318 if (sleepTime == 0) {
2319 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2320 sleepTime = activeSleepTime >> sleepTimeShift;
2321 if (sleepTime < kMinThreadSleepTimeUs) {
2322 sleepTime = kMinThreadSleepTimeUs;
Eric Laurent96c08a62009-09-07 08:38:38 -07002323 }
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002324 // reduce sleep time in case of consecutive application underruns to avoid
2325 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2326 // duration we would end up writing less data than needed by the audio HAL if
2327 // the condition persists.
2328 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2329 sleepTimeShift++;
2330 }
2331 } else {
2332 sleepTime = idleSleepTime;
2333 }
2334 } else if (mBytesWritten != 0 ||
2335 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2336 memset (mMixBuffer, 0, mixBufferSize);
2337 sleepTime = 0;
2338 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
2339 }
2340 // TODO add standby time extension fct of effect tail
Eric Laurenta553c252009-07-17 12:17:14 -07002341}
2342
2343// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten789fef12012-01-26 13:37:52 -08002344AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kastend9cccfa2012-02-28 18:40:35 -08002345 Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07002346{
2347
Glenn Kasten789fef12012-01-26 13:37:52 -08002348 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002349 // find out which tracks need to be processed
Glenn Kastend9cccfa2012-02-28 18:40:35 -08002350 size_t count = mActiveTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07002351 size_t mixedTracks = 0;
2352 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002353
2354 float masterVolume = mMasterVolume;
2355 bool masterMute = mMasterMute;
2356
Eric Laurent8cc93b92010-08-11 05:20:11 -07002357 if (masterMute) {
2358 masterVolume = 0;
2359 }
Eric Laurent65b65452010-06-01 23:49:17 -07002360 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002361 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07002362 if (chain != 0) {
Eric Laurent8cc93b92010-08-11 05:20:11 -07002363 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07002364 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07002365 masterVolume = (float)((v + (1 << 23)) >> 24);
2366 chain.clear();
2367 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08002368
Eric Laurenta553c252009-07-17 12:17:14 -07002369 for (size_t i=0 ; i<count ; i++) {
Glenn Kastend9cccfa2012-02-28 18:40:35 -08002370 sp<Track> t = mActiveTracks[i].promote();
Eric Laurenta553c252009-07-17 12:17:14 -07002371 if (t == 0) continue;
2372
Glenn Kasten68deb152011-12-19 15:06:39 -08002373 // this const just means the local variable doesn't change
Eric Laurenta553c252009-07-17 12:17:14 -07002374 Track* const track = t.get();
2375 audio_track_cblk_t* cblk = track->cblk();
2376
2377 // The first time a track is added we wait
2378 // for all its buffers to be filled before processing it
Glenn Kasten68deb152011-12-19 15:06:39 -08002379 int name = track->name();
Eric Laurent8a04fe02011-11-08 18:10:16 -08002380 // make sure that we have enough frames to mix one full buffer.
2381 // enforce this condition only once to enable draining the buffer in case the client
2382 // app does not call stop() and relies on underrun to stop:
Eric Laurent71c44962012-01-17 19:20:12 -08002383 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurent8a04fe02011-11-08 18:10:16 -08002384 // during last round
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002385 uint32_t minFrames = 1;
Eric Laurent8a04fe02011-11-08 18:10:16 -08002386 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent71c44962012-01-17 19:20:12 -08002387 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002388 if (t->sampleRate() == (int)mSampleRate) {
2389 minFrames = mFrameCount;
2390 } else {
Eric Laurent72dafb22011-12-22 16:08:41 -08002391 // +1 for rounding and +1 for additional sample needed for interpolation
2392 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2393 // add frames already consumed but not yet released by the resampler
2394 // because cblk->framesReady() will include these frames
2395 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2396 // the minimum track buffer size is normally twice the number of frames necessary
2397 // to fill one buffer and the resampler should not leave more than one buffer worth
2398 // of unreleased frames after each pass, but just in case...
Steve Blockec193de2012-01-09 18:35:44 +00002399 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002400 }
2401 }
John Grossmand8cf2962012-02-08 16:37:41 -08002402 if ((track->framesReady() >= minFrames) && track->isReady() &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07002403 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002404 {
Glenn Kasten68deb152011-12-19 15:06:39 -08002405 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002406
Eric Laurent65b65452010-06-01 23:49:17 -07002407 mixedTracks++;
2408
2409 // track->mainBuffer() != mMixBuffer means there is an effect chain
2410 // connected to the track
2411 chain.clear();
2412 if (track->mainBuffer() != mMixBuffer) {
2413 chain = getEffectChain_l(track->sessionId());
2414 // Delegate volume control to effect in track effect chain if needed
2415 if (chain != 0) {
2416 tracksWithEffect++;
2417 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00002418 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten68deb152011-12-19 15:06:39 -08002419 name, track->sessionId());
Eric Laurent65b65452010-06-01 23:49:17 -07002420 }
2421 }
2422
2423
2424 int param = AudioMixer::VOLUME;
2425 if (track->mFillingUpStatus == Track::FS_FILLED) {
2426 // no ramp for the first volume setting
2427 track->mFillingUpStatus = Track::FS_ACTIVE;
2428 if (track->mState == TrackBase::RESUMING) {
2429 track->mState = TrackBase::ACTIVE;
2430 param = AudioMixer::RAMP_VOLUME;
2431 }
Glenn Kasten68deb152011-12-19 15:06:39 -08002432 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent65b65452010-06-01 23:49:17 -07002433 } else if (cblk->server != 0) {
2434 // If the track is stopped before the first frame was mixed,
2435 // do not apply ramp
2436 param = AudioMixer::RAMP_VOLUME;
2437 }
2438
Eric Laurenta553c252009-07-17 12:17:14 -07002439 // compute volume for this track
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002440 uint32_t vl, vr, va;
Eric Laurent2a6b80b2010-07-29 23:43:43 -07002441 if (track->isMuted() || track->isPausing() ||
Glenn Kastenaae26c82012-02-08 12:35:35 -08002442 mStreamTypes[track->streamType()].mute) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002443 vl = vr = va = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07002444 if (track->isPausing()) {
2445 track->setPaused();
2446 }
2447 } else {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002448
Glenn Kasten871c16c2010-03-05 12:18:01 -08002449 // read original volumes with volume control
Glenn Kastenaae26c82012-02-08 12:35:35 -08002450 float typeVolume = mStreamTypes[track->streamType()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002451 float v = masterVolume * typeVolume;
Glenn Kastenbc4de882012-01-17 14:39:34 -08002452 uint32_t vlr = cblk->getVolumeLR();
Glenn Kasten0632bad2012-01-17 12:20:54 -08002453 vl = vlr & 0xFFFF;
2454 vr = vlr >> 16;
2455 // track volumes come from shared memory, so can't be trusted and must be clamped
2456 if (vl > MAX_GAIN_INT) {
2457 ALOGV("Track left volume out of range: %04X", vl);
2458 vl = MAX_GAIN_INT;
2459 }
2460 if (vr > MAX_GAIN_INT) {
2461 ALOGV("Track right volume out of range: %04X", vr);
2462 vr = MAX_GAIN_INT;
2463 }
2464 // now apply the master volume and stream type volume
2465 vl = (uint32_t)(v * vl) << 12;
2466 vr = (uint32_t)(v * vr) << 12;
2467 // assuming master volume and stream type volume each go up to 1.0,
2468 // vl and vr are now in 8.24 format
Eric Laurenta553c252009-07-17 12:17:14 -07002469
Glenn Kasten4790bd82012-01-03 14:22:33 -08002470 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2471 // send level comes from shared memory and so may be corrupt
Glenn Kasten4f22c052012-01-27 15:26:23 -08002472 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten4790bd82012-01-03 14:22:33 -08002473 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kasten0632bad2012-01-17 12:20:54 -08002474 sendLevel = MAX_GAIN_INT;
Glenn Kasten4790bd82012-01-03 14:22:33 -08002475 }
2476 va = (uint32_t)(v * sendLevel);
Eric Laurenta553c252009-07-17 12:17:14 -07002477 }
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002478 // Delegate volume control to effect in track effect chain if needed
2479 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2480 // Do not ramp volume if volume is controlled by effect
2481 param = AudioMixer::VOLUME;
2482 track->mHasVolumeController = true;
2483 } else {
2484 // force no volume ramp when volume controller was just disabled or removed
2485 // from effect chain to avoid volume spike
2486 if (track->mHasVolumeController) {
2487 param = AudioMixer::VOLUME;
2488 }
2489 track->mHasVolumeController = false;
2490 }
2491
2492 // Convert volumes from 8.24 to 4.12 format
Glenn Kasten0632bad2012-01-17 12:20:54 -08002493 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten4f22c052012-01-27 15:26:23 -08002494 vl = (vl + (1 << 11)) >> 12;
2495 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2496 vr = (vr + (1 << 11)) >> 12;
2497 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002498
Glenn Kasten4f22c052012-01-27 15:26:23 -08002499 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 -07002500
Eric Laurent65b65452010-06-01 23:49:17 -07002501 // XXX: these things DON'T need to be done each time
Glenn Kasten68deb152011-12-19 15:06:39 -08002502 mAudioMixer->setBufferProvider(name, track);
2503 mAudioMixer->enable(name);
Eric Laurent65b65452010-06-01 23:49:17 -07002504
Glenn Kasten4f22c052012-01-27 15:26:23 -08002505 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2506 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2507 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Eric Laurenta553c252009-07-17 12:17:14 -07002508 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002509 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002510 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07002511 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07002512 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002513 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002514 AudioMixer::TRACK,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002515 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Eric Laurenta553c252009-07-17 12:17:14 -07002516 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002517 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002518 AudioMixer::RESAMPLE,
2519 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07002520 (void *)(cblk->sampleRate));
2521 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002522 name,
Eric Laurent65b65452010-06-01 23:49:17 -07002523 AudioMixer::TRACK,
2524 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2525 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002526 name,
Eric Laurent65b65452010-06-01 23:49:17 -07002527 AudioMixer::TRACK,
2528 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07002529
2530 // reset retry count
2531 track->mRetryCount = kMaxTrackRetries;
Eric Laurent71c44962012-01-17 19:20:12 -08002532 // If one track is ready, set the mixer ready if:
2533 // - the mixer was not ready during previous round OR
2534 // - no other track is not ready
2535 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2536 mixerStatus != MIXER_TRACKS_ENABLED) {
2537 mixerStatus = MIXER_TRACKS_READY;
2538 }
Eric Laurenta553c252009-07-17 12:17:14 -07002539 } else {
Glenn Kasten68deb152011-12-19 15:06:39 -08002540 //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 -07002541 if (track->isStopped()) {
2542 track->reset();
2543 }
2544 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2545 // We have consumed all the buffers of this track.
2546 // Remove it from the list of active tracks.
2547 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002548 } else {
2549 // No buffers for this track. Give it a few chances to
2550 // fill a buffer, then remove it from active list.
2551 if (--(track->mRetryCount) <= 0) {
Glenn Kasten68deb152011-12-19 15:06:39 -08002552 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002553 tracksToRemove->add(track);
Eric Laurent4712baa2010-09-30 16:12:31 -07002554 // indicate to client process that the track was disabled because of underrun
Eric Laurentae29b762011-03-28 18:37:07 -07002555 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent71c44962012-01-17 19:20:12 -08002556 // If one track is not ready, mark the mixer also not ready if:
2557 // - the mixer was ready during previous round OR
2558 // - no other track is ready
2559 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2560 mixerStatus != MIXER_TRACKS_READY) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002561 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002562 }
Eric Laurenta553c252009-07-17 12:17:14 -07002563 }
Glenn Kasten68deb152011-12-19 15:06:39 -08002564 mAudioMixer->disable(name);
Eric Laurenta553c252009-07-17 12:17:14 -07002565 }
2566 }
2567
2568 // remove all the tracks that need to be...
2569 count = tracksToRemove->size();
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002570 if (CC_UNLIKELY(count)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002571 for (size_t i=0 ; i<count ; i++) {
2572 const sp<Track>& track = tracksToRemove->itemAt(i);
2573 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07002574 if (track->mainBuffer() != mMixBuffer) {
2575 chain = getEffectChain_l(track->sessionId());
2576 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002577 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002578 chain->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002579 }
2580 }
Eric Laurenta553c252009-07-17 12:17:14 -07002581 if (track->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002582 removeTrack_l(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002583 }
2584 }
2585 }
2586
Eric Laurent65b65452010-06-01 23:49:17 -07002587 // mix buffer must be cleared if all tracks are connected to an
2588 // effect chain as in this case the mixer will not write to
2589 // mix buffer and track effects will accumulate into it
2590 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2591 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2592 }
2593
Eric Laurent71c44962012-01-17 19:20:12 -08002594 mPrevMixerStatus = mixerStatus;
Eric Laurent059b4be2009-11-09 23:32:22 -08002595 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07002596}
2597
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08002598void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07002599{
Steve Block71f2cf12011-10-20 11:56:00 +01002600 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002601 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07002602 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002603
Eric Laurenta553c252009-07-17 12:17:14 -07002604 size_t size = mTracks.size();
2605 for (size_t i = 0; i < size; i++) {
2606 sp<Track> t = mTracks[i];
Glenn Kastenaae26c82012-02-08 12:35:35 -08002607 if (t->streamType() == streamType) {
Eric Laurentae29b762011-03-28 18:37:07 -07002608 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002609 t->mCblk->cv.signal();
Eric Laurenta553c252009-07-17 12:17:14 -07002610 }
Eric Laurent53334cd2010-06-23 17:38:20 -07002611 }
2612}
Eric Laurenta553c252009-07-17 12:17:14 -07002613
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08002614void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent05ce0942011-08-30 10:18:54 -07002615{
Steve Block71f2cf12011-10-20 11:56:00 +01002616 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent05ce0942011-08-30 10:18:54 -07002617 this, streamType, valid);
2618 Mutex::Autolock _l(mLock);
2619
2620 mStreamTypes[streamType].valid = valid;
2621}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002622
Eric Laurenta553c252009-07-17 12:17:14 -07002623// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002624int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625{
2626 return mAudioMixer->getTrackName();
2627}
2628
Eric Laurenta553c252009-07-17 12:17:14 -07002629// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002630void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002631{
Steve Block71f2cf12011-10-20 11:56:00 +01002632 ALOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002633 mAudioMixer->deleteTrackName(name);
2634}
2635
Eric Laurenta553c252009-07-17 12:17:14 -07002636// checkForNewParameters_l() must be called with ThreadBase::mLock held
2637bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002638{
Eric Laurenta553c252009-07-17 12:17:14 -07002639 bool reconfig = false;
2640
Eric Laurent8fce46a2009-08-04 09:45:33 -07002641 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002642 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002643 String8 keyValuePair = mNewParameters[0];
2644 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002645 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002646
Eric Laurenta553c252009-07-17 12:17:14 -07002647 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2648 reconfig = true;
2649 }
2650 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten0a204ed2012-01-12 12:27:51 -08002651 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07002652 status = BAD_VALUE;
2653 } else {
2654 reconfig = true;
2655 }
2656 }
2657 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002658 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurenta553c252009-07-17 12:17:14 -07002659 status = BAD_VALUE;
2660 } else {
2661 reconfig = true;
2662 }
2663 }
2664 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2665 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kastene5fb2632011-12-14 10:28:06 -08002666 // size depends on frame count and correct behavior would not be guaranteed
Eric Laurenta553c252009-07-17 12:17:14 -07002667 // if frame count is changed after track creation
2668 if (!mTracks.isEmpty()) {
2669 status = INVALID_OPERATION;
2670 } else {
2671 reconfig = true;
2672 }
2673 }
Eric Laurent65b65452010-06-01 23:49:17 -07002674 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002675 // when changing the audio output device, call addBatteryData to notify
2676 // the change
Eric Laurent90681d62011-05-09 12:09:06 -07002677 if ((int)mDevice != value) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002678 uint32_t params = 0;
2679 // check whether speaker is on
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002680 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002681 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2682 }
2683
2684 int deviceWithoutSpeaker
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002685 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9b3f1522011-02-24 14:51:45 -08002686 // check if any other device (except speaker) is on
2687 if (value & deviceWithoutSpeaker ) {
2688 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2689 }
2690
2691 if (params != 0) {
2692 addBatteryData(params);
2693 }
2694 }
2695
Eric Laurent65b65452010-06-01 23:49:17 -07002696 // forward device change to effects that have requested to be
2697 // aware of attached audio device.
2698 mDevice = (uint32_t)value;
2699 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07002700 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07002701 }
2702 }
2703
Eric Laurenta553c252009-07-17 12:17:14 -07002704 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002705 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002706 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002707 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002708 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002709 mStandby = true;
2710 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002711 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002712 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002713 }
2714 if (status == NO_ERROR && reconfig) {
2715 delete mAudioMixer;
Glenn Kasten2589cf92012-01-27 18:08:45 -08002716 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2717 mAudioMixer = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07002718 readOutputParameters();
2719 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2720 for (size_t i = 0; i < mTracks.size() ; i++) {
2721 int name = getTrackName_l();
2722 if (name < 0) break;
2723 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07002724 // limit track sample rate to 2 x new output sample rate
2725 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2726 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2727 }
Eric Laurenta553c252009-07-17 12:17:14 -07002728 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07002729 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002730 }
2731 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002732
2733 mNewParameters.removeAt(0);
2734
Eric Laurenta553c252009-07-17 12:17:14 -07002735 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002736 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002737 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2738 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002739 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07002740 }
2741 return reconfig;
2742}
2743
2744status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2745{
2746 const size_t SIZE = 256;
2747 char buffer[SIZE];
2748 String8 result;
2749
2750 PlaybackThread::dumpInternals(fd, args);
2751
2752 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2753 result.append(buffer);
2754 write(fd, result.string(), result.size());
2755 return NO_ERROR;
2756}
2757
Eric Laurent059b4be2009-11-09 23:32:22 -08002758uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2759{
Eric Laurenta54d7d32010-07-29 06:50:24 -07002760 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002761}
2762
Eric Laurent8448a792010-08-18 18:13:17 -07002763uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2764{
2765 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2766}
2767
Eric Laurenta553c252009-07-17 12:17:14 -07002768// ----------------------------------------------------------------------------
Glenn Kasten39d00cb2012-01-17 11:09:42 -08002769AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2770 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kastenefd511a2012-01-26 10:38:26 -08002771 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kastendc3ac852012-01-25 15:28:08 -08002772 // mLeftVolFloat, mRightVolFloat
2773 // mLeftVolShort, mRightVolShort
Eric Laurenta553c252009-07-17 12:17:14 -07002774{
Eric Laurenta553c252009-07-17 12:17:14 -07002775}
2776
2777AudioFlinger::DirectOutputThread::~DirectOutputThread()
2778{
2779}
2780
Glenn Kasten67cb3122012-03-01 17:10:56 -08002781void AudioFlinger::DirectOutputThread::applyVolume()
Eric Laurent65b65452010-06-01 23:49:17 -07002782{
2783 // Do not apply volume on compressed audio
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002784 if (!audio_is_linear_pcm(mFormat)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002785 return;
2786 }
2787
2788 // convert to signed 16 bit before volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002789 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002790 size_t count = mFrameCount * mChannelCount;
2791 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2792 int16_t *dst = mMixBuffer + count-1;
2793 while(count--) {
2794 *dst-- = (int16_t)(*src--^0x80) << 8;
2795 }
2796 }
2797
2798 size_t frameCount = mFrameCount;
2799 int16_t *out = mMixBuffer;
Glenn Kasten67cb3122012-03-01 17:10:56 -08002800 if (rampVolume) {
Eric Laurent65b65452010-06-01 23:49:17 -07002801 if (mChannelCount == 1) {
2802 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2803 int32_t vlInc = d / (int32_t)frameCount;
2804 int32_t vl = ((int32_t)mLeftVolShort << 16);
2805 do {
2806 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2807 out++;
2808 vl += vlInc;
2809 } while (--frameCount);
2810
2811 } else {
2812 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2813 int32_t vlInc = d / (int32_t)frameCount;
2814 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2815 int32_t vrInc = d / (int32_t)frameCount;
2816 int32_t vl = ((int32_t)mLeftVolShort << 16);
2817 int32_t vr = ((int32_t)mRightVolShort << 16);
2818 do {
2819 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2820 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2821 out += 2;
2822 vl += vlInc;
2823 vr += vrInc;
2824 } while (--frameCount);
2825 }
2826 } else {
2827 if (mChannelCount == 1) {
2828 do {
2829 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2830 out++;
2831 } while (--frameCount);
2832 } else {
2833 do {
2834 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2835 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2836 out += 2;
2837 } while (--frameCount);
2838 }
2839 }
2840
2841 // convert back to unsigned 8 bit after volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002842 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002843 size_t count = mFrameCount * mChannelCount;
2844 int16_t *src = mMixBuffer;
2845 uint8_t *dst = (uint8_t *)mMixBuffer;
2846 while(count--) {
2847 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2848 }
2849 }
2850
2851 mLeftVolShort = leftVol;
2852 mRightVolShort = rightVol;
2853}
2854
Glenn Kasten67cb3122012-03-01 17:10:56 -08002855AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::threadLoop_prepareTracks_l(
2856 sp<Track>& trackToRemove
2857)
Eric Laurenta553c252009-07-17 12:17:14 -07002858{
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002859 // FIXME Temporarily renamed to avoid confusion with the member "mixerStatus"
2860 mixer_state mixerStatus_ = MIXER_IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07002861
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002862 // find out which tracks need to be processed
2863 if (mActiveTracks.size() != 0) {
2864 sp<Track> t = mActiveTracks[0].promote();
2865 // see FIXME in AudioFlinger.h, return MIXER_IDLE might also work
2866 if (t == 0) return MIXER_CONTINUE;
2867 //if (t == 0) continue;
Eric Laurenta553c252009-07-17 12:17:14 -07002868
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002869 Track* const track = t.get();
2870 audio_track_cblk_t* cblk = track->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07002871
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002872 // The first time a track is added we wait
2873 // for all its buffers to be filled before processing it
2874 if (cblk->framesReady() && track->isReady() &&
2875 !track->isPaused() && !track->isTerminated())
2876 {
2877 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002878
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002879 if (track->mFillingUpStatus == Track::FS_FILLED) {
2880 track->mFillingUpStatus = Track::FS_ACTIVE;
2881 mLeftVolFloat = mRightVolFloat = 0;
2882 mLeftVolShort = mRightVolShort = 0;
2883 if (track->mState == TrackBase::RESUMING) {
2884 track->mState = TrackBase::ACTIVE;
2885 rampVolume = true;
2886 }
2887 } else if (cblk->server != 0) {
2888 // If the track is stopped before the first frame was mixed,
2889 // do not apply ramp
2890 rampVolume = true;
2891 }
2892 // compute volume for this track
2893 float left, right;
2894 if (track->isMuted() || mMasterMute || track->isPausing() ||
2895 mStreamTypes[track->streamType()].mute) {
2896 left = right = 0;
2897 if (track->isPausing()) {
2898 track->setPaused();
2899 }
2900 } else {
2901 float typeVolume = mStreamTypes[track->streamType()].volume;
2902 float v = mMasterVolume * typeVolume;
2903 uint32_t vlr = cblk->getVolumeLR();
2904 float v_clamped = v * (vlr & 0xFFFF);
2905 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2906 left = v_clamped/MAX_GAIN;
2907 v_clamped = v * (vlr >> 16);
2908 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2909 right = v_clamped/MAX_GAIN;
2910 }
Eric Laurenta553c252009-07-17 12:17:14 -07002911
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002912 if (left != mLeftVolFloat || right != mRightVolFloat) {
2913 mLeftVolFloat = left;
2914 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002915
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002916 // If audio HAL implements volume control,
2917 // force software volume to nominal value
2918 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
2919 left = 1.0f;
2920 right = 1.0f;
2921 }
Eric Laurent65b65452010-06-01 23:49:17 -07002922
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002923 // Convert volumes from float to 8.24
2924 uint32_t vl = (uint32_t)(left * (1 << 24));
2925 uint32_t vr = (uint32_t)(right * (1 << 24));
Eric Laurent65b65452010-06-01 23:49:17 -07002926
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002927 // Delegate volume control to effect in track effect chain if needed
2928 // only one effect chain can be present on DirectOutputThread, so if
2929 // there is one, the track is connected to it
2930 if (!mEffectChains.isEmpty()) {
2931 // Do not ramp volume if volume is controlled by effect
2932 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002933 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002934 }
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002935 }
Eric Laurenta553c252009-07-17 12:17:14 -07002936
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002937 // Convert volumes from 8.24 to 4.12 format
2938 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2939 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2940 leftVol = (uint16_t)v_clamped;
2941 v_clamped = (vr + (1 << 11)) >> 12;
2942 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2943 rightVol = (uint16_t)v_clamped;
2944 } else {
2945 leftVol = mLeftVolShort;
2946 rightVol = mRightVolShort;
2947 rampVolume = false;
2948 }
2949
2950 // reset retry count
2951 track->mRetryCount = kMaxTrackRetriesDirect;
2952 activeTrack = t;
2953 mixerStatus_ = MIXER_TRACKS_READY;
2954 } else {
2955 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2956 if (track->isStopped()) {
2957 track->reset();
2958 }
2959 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2960 // We have consumed all the buffers of this track.
2961 // Remove it from the list of active tracks.
2962 trackToRemove = track;
2963 } else {
2964 // No buffers for this track. Give it a few chances to
2965 // fill a buffer, then remove it from active list.
2966 if (--(track->mRetryCount) <= 0) {
2967 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2968 trackToRemove = track;
Eric Laurenta553c252009-07-17 12:17:14 -07002969 } else {
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002970 mixerStatus_ = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002971 }
2972 }
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002973 }
2974 }
Eric Laurenta553c252009-07-17 12:17:14 -07002975
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002976 // remove all the tracks that need to be...
2977 if (CC_UNLIKELY(trackToRemove != 0)) {
2978 mActiveTracks.remove(trackToRemove);
2979 if (!mEffectChains.isEmpty()) {
2980 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2981 trackToRemove->sessionId());
2982 mEffectChains[0]->decActiveTrackCnt();
2983 }
2984 if (trackToRemove->isTerminated()) {
2985 removeTrack_l(trackToRemove);
2986 }
2987 }
Eric Laurent65b65452010-06-01 23:49:17 -07002988
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002989 return mixerStatus_;
Glenn Kasten67cb3122012-03-01 17:10:56 -08002990}
Eric Laurenta553c252009-07-17 12:17:14 -07002991
Glenn Kasten67cb3122012-03-01 17:10:56 -08002992void AudioFlinger::DirectOutputThread::threadLoop_mix()
2993{
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08002994 AudioBufferProvider::Buffer buffer;
2995 size_t frameCount = mFrameCount;
2996 int8_t *curBuf = (int8_t *)mMixBuffer;
2997 // output audio to hardware
2998 while (frameCount) {
2999 buffer.frameCount = frameCount;
3000 activeTrack->getNextBuffer(&buffer);
3001 if (CC_UNLIKELY(buffer.raw == NULL)) {
3002 memset(curBuf, 0, frameCount * mFrameSize);
3003 break;
3004 }
3005 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3006 frameCount -= buffer.frameCount;
3007 curBuf += buffer.frameCount * mFrameSize;
3008 activeTrack->releaseBuffer(&buffer);
3009 }
3010 sleepTime = 0;
3011 standbyTime = systemTime() + standbyDelay;
Glenn Kasten67cb3122012-03-01 17:10:56 -08003012}
3013
3014void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3015{
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08003016 if (sleepTime == 0) {
3017 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3018 sleepTime = activeSleepTime;
3019 } else {
3020 sleepTime = idleSleepTime;
3021 }
3022 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3023 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
3024 sleepTime = 0;
3025 }
Eric Laurenta553c252009-07-17 12:17:14 -07003026}
3027
3028// getTrackName_l() must be called with ThreadBase::mLock held
3029int AudioFlinger::DirectOutputThread::getTrackName_l()
3030{
3031 return 0;
3032}
3033
3034// deleteTrackName_l() must be called with ThreadBase::mLock held
3035void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3036{
3037}
3038
3039// checkForNewParameters_l() must be called with ThreadBase::mLock held
3040bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3041{
3042 bool reconfig = false;
3043
Eric Laurent8fce46a2009-08-04 09:45:33 -07003044 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07003045 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07003046 String8 keyValuePair = mNewParameters[0];
3047 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07003048 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07003049
Eric Laurenta553c252009-07-17 12:17:14 -07003050 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3051 // do not accept frame count changes if tracks are open as the track buffer
3052 // size depends on frame count and correct behavior would not be garantied
3053 // if frame count is changed after track creation
3054 if (!mTracks.isEmpty()) {
3055 status = INVALID_OPERATION;
3056 } else {
3057 reconfig = true;
3058 }
3059 }
3060 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07003061 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003062 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07003063 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07003064 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07003065 mStandby = true;
3066 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07003067 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003068 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07003069 }
3070 if (status == NO_ERROR && reconfig) {
3071 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07003072 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07003073 }
3074 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08003075
3076 mNewParameters.removeAt(0);
3077
Eric Laurenta553c252009-07-17 12:17:14 -07003078 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07003079 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07003080 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3081 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08003082 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07003083 }
3084 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08003085}
3086
Eric Laurent059b4be2009-11-09 23:32:22 -08003087uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07003088{
3089 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003090 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent44331692011-12-05 09:47:19 -08003091 time = PlaybackThread::activeSleepTimeUs();
Eric Laurent059b4be2009-11-09 23:32:22 -08003092 } else {
3093 time = 10000;
3094 }
3095 return time;
3096}
3097
3098uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
3099{
3100 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003101 if (audio_is_linear_pcm(mFormat)) {
Eric Laurenta54d7d32010-07-29 06:50:24 -07003102 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07003103 } else {
3104 time = 10000;
3105 }
3106 return time;
3107}
3108
Eric Laurent8448a792010-08-18 18:13:17 -07003109uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
3110{
3111 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003112 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent8448a792010-08-18 18:13:17 -07003113 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3114 } else {
3115 time = 10000;
3116 }
3117 return time;
3118}
3119
3120
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003121// ----------------------------------------------------------------------------
3122
Glenn Kastenefd511a2012-01-26 10:38:26 -08003123AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten39d00cb2012-01-17 11:09:42 -08003124 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kastenefd511a2012-01-26 10:38:26 -08003125 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3126 mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07003127{
Eric Laurenta553c252009-07-17 12:17:14 -07003128 addOutputTrack(mainThread);
3129}
3130
3131AudioFlinger::DuplicatingThread::~DuplicatingThread()
3132{
Eric Laurent0a080292009-12-07 10:53:10 -08003133 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3134 mOutputTracks[i]->destroy();
3135 }
Eric Laurenta553c252009-07-17 12:17:14 -07003136}
3137
Glenn Kasten67cb3122012-03-01 17:10:56 -08003138void AudioFlinger::DuplicatingThread::threadLoop_mix()
Eric Laurenta553c252009-07-17 12:17:14 -07003139{
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08003140 // mix buffers...
3141 if (outputsReady(outputTracks)) {
3142 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3143 } else {
3144 memset(mMixBuffer, 0, mixBufferSize);
3145 }
3146 sleepTime = 0;
3147 writeFrames = mFrameCount;
Glenn Kasten67cb3122012-03-01 17:10:56 -08003148}
3149
3150void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3151{
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08003152 if (sleepTime == 0) {
3153 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3154 sleepTime = activeSleepTime;
3155 } else {
3156 sleepTime = idleSleepTime;
3157 }
3158 } else if (mBytesWritten != 0) {
3159 // flush remaining overflow buffers in output tracks
3160 for (size_t i = 0; i < outputTracks.size(); i++) {
3161 if (outputTracks[i]->isActive()) {
3162 sleepTime = 0;
3163 writeFrames = 0;
3164 memset(mMixBuffer, 0, mixBufferSize);
3165 break;
Eric Laurenta553c252009-07-17 12:17:14 -07003166 }
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08003167 }
3168 }
Glenn Kasten67cb3122012-03-01 17:10:56 -08003169}
Eric Laurentf69a3f82009-09-22 00:35:48 -07003170
Glenn Kasten67cb3122012-03-01 17:10:56 -08003171void AudioFlinger::DuplicatingThread::threadLoop_write()
3172{
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08003173 standbyTime = systemTime() + mStandbyTimeInNsecs;
3174 for (size_t i = 0; i < outputTracks.size(); i++) {
3175 outputTracks[i]->write(mMixBuffer, writeFrames);
3176 }
3177 mBytesWritten += mixBufferSize;
Glenn Kasten67cb3122012-03-01 17:10:56 -08003178}
Glenn Kastenbea6b952012-02-29 07:57:06 -08003179
Glenn Kasten67cb3122012-03-01 17:10:56 -08003180void AudioFlinger::DuplicatingThread::threadLoop_standby()
3181{
Glenn Kasten26bbc5c2012-03-06 11:30:57 -08003182 // DuplicatingThread implements standby by stopping all tracks
3183 for (size_t i = 0; i < outputTracks.size(); i++) {
3184 outputTracks[i]->stop();
3185 }
Eric Laurenta553c252009-07-17 12:17:14 -07003186}
3187
3188void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3189{
Glenn Kasten91540ae2012-02-24 14:12:20 -08003190 Mutex::Autolock _l(mLock);
Glenn Kastenb3db2132012-01-19 08:59:58 -08003191 // FIXME explain this formula
Eric Laurenta553c252009-07-17 12:17:14 -07003192 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten685c9ce2012-01-20 13:32:16 -08003193 OutputTrack *outputTrack = new OutputTrack(thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003194 this,
Eric Laurenta553c252009-07-17 12:17:14 -07003195 mSampleRate,
3196 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003197 mChannelMask,
Eric Laurenta553c252009-07-17 12:17:14 -07003198 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07003199 if (outputTrack->cblk() != NULL) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003200 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Eric Laurent6c30a712009-08-10 23:22:32 -07003201 mOutputTracks.add(outputTrack);
Steve Block71f2cf12011-10-20 11:56:00 +01003202 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten2bad67f2012-03-06 11:24:48 -08003203 updateWaitTime_l();
Eric Laurent6c30a712009-08-10 23:22:32 -07003204 }
Eric Laurenta553c252009-07-17 12:17:14 -07003205}
3206
3207void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3208{
3209 Mutex::Autolock _l(mLock);
3210 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kasten7d3be3a2012-01-26 10:53:32 -08003211 if (mOutputTracks[i]->thread() == thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07003212 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07003213 mOutputTracks.removeAt(i);
Glenn Kasten2bad67f2012-03-06 11:24:48 -08003214 updateWaitTime_l();
Eric Laurenta553c252009-07-17 12:17:14 -07003215 return;
3216 }
3217 }
Steve Block71f2cf12011-10-20 11:56:00 +01003218 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Eric Laurenta553c252009-07-17 12:17:14 -07003219}
3220
Glenn Kasten2bad67f2012-03-06 11:24:48 -08003221// caller must hold mLock
3222void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003223{
3224 mWaitTimeMs = UINT_MAX;
3225 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3226 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten706b6182012-01-20 13:44:40 -08003227 if (strong != 0) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003228 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3229 if (waitTimeMs < mWaitTimeMs) {
3230 mWaitTimeMs = waitTimeMs;
3231 }
3232 }
3233 }
3234}
3235
3236
Glenn Kasten0fccd352012-02-24 15:42:17 -08003237bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003238{
3239 for (size_t i = 0; i < outputTracks.size(); i++) {
3240 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3241 if (thread == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003242 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003243 return false;
3244 }
3245 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3246 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block71f2cf12011-10-20 11:56:00 +01003247 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003248 return false;
3249 }
3250 }
3251 return true;
3252}
3253
3254uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3255{
3256 return (mWaitTimeMs * 1000) / 2;
3257}
3258
Eric Laurenta553c252009-07-17 12:17:14 -07003259// ----------------------------------------------------------------------------
3260
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003261// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003262AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten685c9ce2012-01-20 13:32:16 -08003263 ThreadBase *thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003264 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003265 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08003266 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003267 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003268 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003269 const sp<IMemory>& sharedBuffer,
3270 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003271 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07003272 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003273 mClient(client),
Glenn Kastendc3ac852012-01-25 15:28:08 -08003274 mCblk(NULL),
3275 // mBuffer
3276 // mBufferEnd
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003277 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003278 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003279 mFormat(format),
Glenn Kasten35269822012-02-21 10:35:56 -08003280 mStepServerFailed(false),
Eric Laurent65b65452010-06-01 23:49:17 -07003281 mSessionId(sessionId)
Glenn Kastendc3ac852012-01-25 15:28:08 -08003282 // mChannelCount
3283 // mChannelMask
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003284{
Steve Block71f2cf12011-10-20 11:56:00 +01003285 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003286
Steve Block5baa3a62011-12-20 16:23:08 +00003287 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003288 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003289 uint8_t channelCount = popcount(channelMask);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003290 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3291 if (sharedBuffer == 0) {
3292 size += bufferSize;
3293 }
3294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003295 if (client != NULL) {
3296 mCblkMemory = client->heap()->allocate(size);
3297 if (mCblkMemory != 0) {
3298 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kasten3694ec12012-01-27 16:47:15 -08003299 if (mCblk != NULL) { // construct the shared structure in-place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 new(mCblk) audio_track_cblk_t();
3301 // clear all buffers
3302 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003303 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003304 mChannelCount = channelCount;
3305 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306 if (sharedBuffer == 0) {
3307 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3308 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3309 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003310 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003311 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 } else {
3313 mBuffer = sharedBuffer->pointer();
3314 }
3315 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317 } else {
Steve Block3762c312012-01-06 19:20:56 +00003318 ALOGE("not enough memory for AudioTrack size=%u", size);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 client->heap()->dump("AudioTrack");
3320 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003321 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003322 } else {
3323 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenc95ca2c2012-01-06 15:03:11 -08003324 // construct the shared structure in-place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 new(mCblk) audio_track_cblk_t();
3326 // clear all buffers
3327 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003328 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003329 mChannelCount = channelCount;
3330 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003331 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3332 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3333 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003334 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003335 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003336 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003337 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003338}
3339
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003340AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003341{
Glenn Kasten3694ec12012-01-27 16:47:15 -08003342 if (mCblk != NULL) {
Glenn Kastend9d68dc2012-02-03 10:24:48 -08003343 if (mClient == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003344 delete mCblk;
Glenn Kastend9d68dc2012-02-03 10:24:48 -08003345 } else {
3346 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Eric Laurenta553c252009-07-17 12:17:14 -07003347 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003348 }
Glenn Kastenf31d0502012-01-25 15:27:15 -08003349 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten706b6182012-01-20 13:44:40 -08003350 if (mClient != 0) {
Glenn Kastendc3ac852012-01-25 15:28:08 -08003351 // Client destructor must run with AudioFlinger mutex locked
Eric Laurentb9481d82009-09-17 05:12:56 -07003352 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten706b6182012-01-20 13:44:40 -08003353 // If the client's reference count drops to zero, the associated destructor
3354 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3355 // relying on the automatic clear() at end of scope.
Eric Laurentb9481d82009-09-17 05:12:56 -07003356 mClient.clear();
3357 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003358}
3359
Glenn Kastenc2db1192012-02-22 10:47:35 -08003360// AudioBufferProvider interface
3361// getNextBuffer() = 0;
3362// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003363void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003364{
Glenn Kastenc434c902011-12-13 11:53:26 -08003365 buffer->raw = NULL;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003366 mFrameCount = buffer->frameCount;
Glenn Kastenc2db1192012-02-22 10:47:35 -08003367 (void) step(); // ignore return value of step()
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003368 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003369}
3370
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003371bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003372 bool result;
3373 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003374
3375 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003376 if (!result) {
Steve Block71f2cf12011-10-20 11:56:00 +01003377 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten35269822012-02-21 10:35:56 -08003378 mStepServerFailed = true;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003379 }
3380 return result;
3381}
3382
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003383void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003384 audio_track_cblk_t* cblk = this->cblk();
3385
3386 cblk->user = 0;
3387 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003388 cblk->userBase = 0;
3389 cblk->serverBase = 0;
Glenn Kasten35269822012-02-21 10:35:56 -08003390 mStepServerFailed = false;
Steve Block71f2cf12011-10-20 11:56:00 +01003391 ALOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003392}
3393
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003394int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07003395 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003396}
3397
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003398void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003399 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenfaf354d2012-01-11 09:48:27 -08003400 size_t frameSize = cblk->frameSize;
3401 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3402 int8_t *bufferEnd = bufferStart + frames * frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003403
3404 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07003405 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenfaf354d2012-01-11 09:48:27 -08003406 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block3762c312012-01-06 19:20:56 +00003407 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 -07003408 server %d, serverBase %d, user %d, userBase %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003409 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003410 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kasten3694ec12012-01-27 16:47:15 -08003411 return NULL;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003412 }
3413
3414 return bufferStart;
3415}
3416
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003417// ----------------------------------------------------------------------------
3418
Eric Laurenta553c252009-07-17 12:17:14 -07003419// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3420AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten685c9ce2012-01-20 13:32:16 -08003421 PlaybackThread *thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003422 const sp<Client>& client,
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08003423 audio_stream_type_t streamType,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003424 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08003425 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003426 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003427 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003428 const sp<IMemory>& sharedBuffer,
3429 int sessionId)
Glenn Kasten35269822012-02-21 10:35:56 -08003430 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Eric Laurenta92ebfa2010-08-31 13:50:07 -07003431 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3432 mAuxEffectId(0), mHasVolumeController(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003433{
Eric Laurent8a77a992009-09-09 05:16:08 -07003434 if (mCblk != NULL) {
Glenn Kasten685c9ce2012-01-20 13:32:16 -08003435 if (thread != NULL) {
3436 mName = thread->getTrackName_l();
3437 mMainBuffer = thread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07003438 }
Glenn Kasten7ed4f0c2012-02-03 11:10:00 -08003439 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurent8a77a992009-09-09 05:16:08 -07003440 if (mName < 0) {
Steve Block3762c312012-01-06 19:20:56 +00003441 ALOGE("no more track names available");
Eric Laurent8a77a992009-09-09 05:16:08 -07003442 }
Eric Laurent8a77a992009-09-09 05:16:08 -07003443 mStreamType = streamType;
3444 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3445 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurent09508612011-07-21 19:35:01 -07003446 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07003447 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003448}
3449
Eric Laurenta553c252009-07-17 12:17:14 -07003450AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003451{
Steve Block71f2cf12011-10-20 11:56:00 +01003452 ALOGV("PlaybackThread::Track destructor");
Eric Laurenta553c252009-07-17 12:17:14 -07003453 sp<ThreadBase> thread = mThread.promote();
3454 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003455 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003456 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003457 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003458}
3459
Eric Laurenta553c252009-07-17 12:17:14 -07003460void AudioFlinger::PlaybackThread::Track::destroy()
3461{
3462 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3463 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kastenb3db2132012-01-19 08:59:58 -08003464 // destructor is called. As the destructor needs to lock mLock,
Eric Laurenta553c252009-07-17 12:17:14 -07003465 // we must acquire a strong reference on this Track before locking mLock
3466 // here so that the destructor is called only when exiting this function.
3467 // On the other hand, as long as Track::destroy() is only called by
3468 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3469 // this Track with its member mTrack.
3470 sp<Track> keep(this);
3471 { // scope for mLock
3472 sp<ThreadBase> thread = mThread.promote();
3473 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003474 if (!isOutputTrack()) {
3475 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kastenaae26c82012-02-08 12:35:35 -08003476 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9b3f1522011-02-24 14:51:45 -08003477
3478 // to track the speaker usage
3479 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurentac196e12009-12-01 02:17:41 -08003480 }
3481 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08003482 }
Eric Laurenta553c252009-07-17 12:17:14 -07003483 Mutex::Autolock _l(thread->mLock);
3484 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3485 playbackThread->destroyTrack_l(this);
3486 }
3487 }
3488}
3489
3490void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003491{
Glenn Kastenbc4de882012-01-17 14:39:34 -08003492 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003493 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 -07003494 mName - AudioMixer::TRACK0,
Glenn Kasten81211142012-02-05 18:09:08 -08003495 (mClient == 0) ? getpid_cached : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003496 mStreamType,
3497 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003498 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003499 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003500 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003501 mState,
3502 mMute,
3503 mFillingUpStatus,
3504 mCblk->sampleRate,
Glenn Kasten0632bad2012-01-17 12:20:54 -08003505 vlr & 0xFFFF,
3506 vlr >> 16,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003507 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07003508 mCblk->user,
3509 (int)mMainBuffer,
3510 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003511}
3512
Glenn Kastenc2db1192012-02-22 10:47:35 -08003513// AudioBufferProvider interface
John Grossmand8cf2962012-02-08 16:37:41 -08003514status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
3515 AudioBufferProvider::Buffer* buffer, int64_t pts)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003516{
3517 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003518 uint32_t framesReady;
3519 uint32_t framesReq = buffer->frameCount;
3520
3521 // Check if last stepServer failed, try to step now
Glenn Kasten35269822012-02-21 10:35:56 -08003522 if (mStepServerFailed) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003523 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003524 ALOGV("stepServer recovered");
Glenn Kasten35269822012-02-21 10:35:56 -08003525 mStepServerFailed = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003526 }
3527
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003528 framesReady = cblk->framesReady();
3529
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003530 if (CC_LIKELY(framesReady)) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003531 uint32_t s = cblk->server;
3532 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3533
3534 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3535 if (framesReq > framesReady) {
3536 framesReq = framesReady;
3537 }
3538 if (s + framesReq > bufferEnd) {
3539 framesReq = bufferEnd - s;
3540 }
3541
3542 buffer->raw = getBuffer(s, framesReq);
Glenn Kastenc434c902011-12-13 11:53:26 -08003543 if (buffer->raw == NULL) goto getNextBuffer_exit;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003544
3545 buffer->frameCount = framesReq;
3546 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003547 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003548
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003549getNextBuffer_exit:
Glenn Kastenc434c902011-12-13 11:53:26 -08003550 buffer->raw = NULL;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003551 buffer->frameCount = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01003552 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 -07003553 return NOT_ENOUGH_DATA;
3554}
3555
John Grossmand8cf2962012-02-08 16:37:41 -08003556uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const{
3557 return mCblk->framesReady();
3558}
3559
Eric Laurenta553c252009-07-17 12:17:14 -07003560bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurent9a30fc12010-10-05 14:41:42 -07003561 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003562
John Grossmand8cf2962012-02-08 16:37:41 -08003563 if (framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003564 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003565 mFillingUpStatus = FS_FILLED;
Eric Laurentae29b762011-03-28 18:37:07 -07003566 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003567 return true;
3568 }
3569 return false;
3570}
3571
Glenn Kasten6a20b262012-02-02 10:56:47 -08003572status_t AudioFlinger::PlaybackThread::Track::start(pid_t tid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003573{
Eric Laurent49f02be2009-11-19 09:00:56 -08003574 status_t status = NO_ERROR;
Glenn Kasten6a20b262012-02-02 10:56:47 -08003575 ALOGV("start(%d), calling pid %d session %d tid %d",
3576 mName, IPCThreadState::self()->getCallingPid(), mSessionId, tid);
Eric Laurenta553c252009-07-17 12:17:14 -07003577 sp<ThreadBase> thread = mThread.promote();
3578 if (thread != 0) {
3579 Mutex::Autolock _l(thread->mLock);
Glenn Kasten56356202012-01-26 13:39:18 -08003580 track_state state = mState;
Eric Laurent49f02be2009-11-19 09:00:56 -08003581 // here the track could be either new, or restarted
3582 // in both cases "unstop" the track
3583 if (mState == PAUSED) {
3584 mState = TrackBase::RESUMING;
Steve Block71f2cf12011-10-20 11:56:00 +01003585 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003586 } else {
3587 mState = TrackBase::ACTIVE;
Steve Block71f2cf12011-10-20 11:56:00 +01003588 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003589 }
3590
3591 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3592 thread->mLock.unlock();
Glenn Kastenaae26c82012-02-08 12:35:35 -08003593 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003594 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003595
3596 // to track the speaker usage
3597 if (status == NO_ERROR) {
3598 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3599 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003600 }
3601 if (status == NO_ERROR) {
3602 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3603 playbackThread->addTrack_l(this);
3604 } else {
3605 mState = state;
3606 }
3607 } else {
3608 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003609 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003610 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003611}
3612
Eric Laurenta553c252009-07-17 12:17:14 -07003613void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003614{
Glenn Kasten7ed4f0c2012-02-03 11:10:00 -08003615 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003616 sp<ThreadBase> thread = mThread.promote();
3617 if (thread != 0) {
3618 Mutex::Autolock _l(thread->mLock);
Glenn Kasten56356202012-01-26 13:39:18 -08003619 track_state state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07003620 if (mState > STOPPED) {
3621 mState = STOPPED;
3622 // If the track is not active (PAUSED and buffers full), flush buffers
3623 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3624 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3625 reset();
3626 }
Steve Block71f2cf12011-10-20 11:56:00 +01003627 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003628 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003629 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3630 thread->mLock.unlock();
Glenn Kastenaae26c82012-02-08 12:35:35 -08003631 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003632 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003633
3634 // to track the speaker usage
3635 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003636 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003637 }
3638}
3639
Eric Laurenta553c252009-07-17 12:17:14 -07003640void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003641{
Glenn Kasten7ed4f0c2012-02-03 11:10:00 -08003642 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003643 sp<ThreadBase> thread = mThread.promote();
3644 if (thread != 0) {
3645 Mutex::Autolock _l(thread->mLock);
3646 if (mState == ACTIVE || mState == RESUMING) {
3647 mState = PAUSING;
Steve Block71f2cf12011-10-20 11:56:00 +01003648 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003649 if (!isOutputTrack()) {
3650 thread->mLock.unlock();
Glenn Kastenaae26c82012-02-08 12:35:35 -08003651 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003652 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003653
3654 // to track the speaker usage
3655 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003656 }
Eric Laurenta553c252009-07-17 12:17:14 -07003657 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003658 }
3659}
3660
Eric Laurenta553c252009-07-17 12:17:14 -07003661void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003662{
Steve Block71f2cf12011-10-20 11:56:00 +01003663 ALOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003664 sp<ThreadBase> thread = mThread.promote();
3665 if (thread != 0) {
3666 Mutex::Autolock _l(thread->mLock);
3667 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3668 return;
3669 }
3670 // No point remaining in PAUSED state after a flush => go to
3671 // STOPPED state
3672 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003673
Eric Laurentae29b762011-03-28 18:37:07 -07003674 // do not reset the track if it is still in the process of being stopped or paused.
3675 // this will be done by prepareTracks_l() when the track is stopped.
3676 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3677 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3678 reset();
3679 }
Eric Laurenta553c252009-07-17 12:17:14 -07003680 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003681}
3682
Eric Laurenta553c252009-07-17 12:17:14 -07003683void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003684{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003685 // Do not reset twice to avoid discarding data written just after a flush and before
3686 // the audioflinger thread detects the track is stopped.
3687 if (!mResetDone) {
3688 TrackBase::reset();
3689 // Force underrun condition to avoid false underrun callback until first data is
3690 // written to buffer
Eric Laurentae29b762011-03-28 18:37:07 -07003691 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3692 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003693 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003694 mResetDone = true;
3695 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003696}
3697
Eric Laurenta553c252009-07-17 12:17:14 -07003698void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003699{
3700 mMute = muted;
3701}
3702
Eric Laurent65b65452010-06-01 23:49:17 -07003703status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3704{
3705 status_t status = DEAD_OBJECT;
3706 sp<ThreadBase> thread = mThread.promote();
3707 if (thread != 0) {
3708 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3709 status = playbackThread->attachAuxEffect(this, EffectId);
3710 }
3711 return status;
3712}
3713
3714void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3715{
3716 mAuxEffectId = EffectId;
3717 mAuxBuffer = buffer;
3718}
3719
John Grossmand8cf2962012-02-08 16:37:41 -08003720// timed audio tracks
3721
3722sp<AudioFlinger::PlaybackThread::TimedTrack>
3723AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten685c9ce2012-01-20 13:32:16 -08003724 PlaybackThread *thread,
John Grossmand8cf2962012-02-08 16:37:41 -08003725 const sp<Client>& client,
3726 audio_stream_type_t streamType,
3727 uint32_t sampleRate,
3728 audio_format_t format,
3729 uint32_t channelMask,
3730 int frameCount,
3731 const sp<IMemory>& sharedBuffer,
3732 int sessionId) {
3733 if (!client->reserveTimedTrack())
3734 return NULL;
3735
3736 sp<TimedTrack> track = new TimedTrack(
3737 thread, client, streamType, sampleRate, format, channelMask, frameCount,
3738 sharedBuffer, sessionId);
3739
3740 if (track == NULL) {
3741 client->releaseTimedTrack();
3742 return NULL;
3743 }
3744
3745 return track;
3746}
3747
3748AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten685c9ce2012-01-20 13:32:16 -08003749 PlaybackThread *thread,
John Grossmand8cf2962012-02-08 16:37:41 -08003750 const sp<Client>& client,
3751 audio_stream_type_t streamType,
3752 uint32_t sampleRate,
3753 audio_format_t format,
3754 uint32_t channelMask,
3755 int frameCount,
3756 const sp<IMemory>& sharedBuffer,
3757 int sessionId)
3758 : Track(thread, client, streamType, sampleRate, format, channelMask,
3759 frameCount, sharedBuffer, sessionId),
3760 mTimedSilenceBuffer(NULL),
3761 mTimedSilenceBufferSize(0),
3762 mTimedAudioOutputOnTime(false),
3763 mMediaTimeTransformValid(false)
3764{
3765 LocalClock lc;
3766 mLocalTimeFreq = lc.getLocalFreq();
3767
3768 mLocalTimeToSampleTransform.a_zero = 0;
3769 mLocalTimeToSampleTransform.b_zero = 0;
3770 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3771 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3772 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3773 &mLocalTimeToSampleTransform.a_to_b_denom);
3774}
3775
3776AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3777 mClient->releaseTimedTrack();
3778 delete [] mTimedSilenceBuffer;
3779}
3780
3781status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3782 size_t size, sp<IMemory>* buffer) {
3783
3784 Mutex::Autolock _l(mTimedBufferQueueLock);
3785
3786 trimTimedBufferQueue_l();
3787
3788 // lazily initialize the shared memory heap for timed buffers
3789 if (mTimedMemoryDealer == NULL) {
3790 const int kTimedBufferHeapSize = 512 << 10;
3791
3792 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3793 "AudioFlingerTimed");
3794 if (mTimedMemoryDealer == NULL)
3795 return NO_MEMORY;
3796 }
3797
3798 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3799 if (newBuffer == NULL) {
3800 newBuffer = mTimedMemoryDealer->allocate(size);
3801 if (newBuffer == NULL)
3802 return NO_MEMORY;
3803 }
3804
3805 *buffer = newBuffer;
3806 return NO_ERROR;
3807}
3808
3809// caller must hold mTimedBufferQueueLock
3810void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
3811 int64_t mediaTimeNow;
3812 {
3813 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3814 if (!mMediaTimeTransformValid)
3815 return;
3816
3817 int64_t targetTimeNow;
3818 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
3819 ? mCCHelper.getCommonTime(&targetTimeNow)
3820 : mCCHelper.getLocalTime(&targetTimeNow);
3821
3822 if (OK != res)
3823 return;
3824
3825 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
3826 &mediaTimeNow)) {
3827 return;
3828 }
3829 }
3830
3831 size_t trimIndex;
3832 for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
3833 if (mTimedBufferQueue[trimIndex].pts() > mediaTimeNow)
3834 break;
3835 }
3836
3837 if (trimIndex) {
3838 mTimedBufferQueue.removeItemsAt(0, trimIndex);
3839 }
3840}
3841
3842status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
3843 const sp<IMemory>& buffer, int64_t pts) {
3844
3845 {
3846 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3847 if (!mMediaTimeTransformValid)
3848 return INVALID_OPERATION;
3849 }
3850
3851 Mutex::Autolock _l(mTimedBufferQueueLock);
3852
3853 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
3854
3855 return NO_ERROR;
3856}
3857
3858status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
3859 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
3860
3861 ALOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
3862 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
3863 target);
3864
3865 if (!(target == TimedAudioTrack::LOCAL_TIME ||
3866 target == TimedAudioTrack::COMMON_TIME)) {
3867 return BAD_VALUE;
3868 }
3869
3870 Mutex::Autolock lock(mMediaTimeTransformLock);
3871 mMediaTimeTransform = xform;
3872 mMediaTimeTransformTarget = target;
3873 mMediaTimeTransformValid = true;
3874
3875 return NO_ERROR;
3876}
3877
3878#define min(a, b) ((a) < (b) ? (a) : (b))
3879
3880// implementation of getNextBuffer for tracks whose buffers have timestamps
3881status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
3882 AudioBufferProvider::Buffer* buffer, int64_t pts)
3883{
3884 if (pts == AudioBufferProvider::kInvalidPTS) {
3885 buffer->raw = 0;
3886 buffer->frameCount = 0;
3887 return INVALID_OPERATION;
3888 }
3889
John Grossmand8cf2962012-02-08 16:37:41 -08003890 Mutex::Autolock _l(mTimedBufferQueueLock);
3891
3892 while (true) {
3893
3894 // if we have no timed buffers, then fail
3895 if (mTimedBufferQueue.isEmpty()) {
3896 buffer->raw = 0;
3897 buffer->frameCount = 0;
3898 return NOT_ENOUGH_DATA;
3899 }
3900
3901 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
3902
3903 // calculate the PTS of the head of the timed buffer queue expressed in
3904 // local time
3905 int64_t headLocalPTS;
3906 {
3907 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3908
3909 assert(mMediaTimeTransformValid);
3910
3911 if (mMediaTimeTransform.a_to_b_denom == 0) {
3912 // the transform represents a pause, so yield silence
3913 timedYieldSilence(buffer->frameCount, buffer);
3914 return NO_ERROR;
3915 }
3916
3917 int64_t transformedPTS;
3918 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
3919 &transformedPTS)) {
3920 // the transform failed. this shouldn't happen, but if it does
3921 // then just drop this buffer
3922 ALOGW("timedGetNextBuffer transform failed");
3923 buffer->raw = 0;
3924 buffer->frameCount = 0;
3925 mTimedBufferQueue.removeAt(0);
3926 return NO_ERROR;
3927 }
3928
3929 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
3930 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
3931 &headLocalPTS)) {
3932 buffer->raw = 0;
3933 buffer->frameCount = 0;
3934 return INVALID_OPERATION;
3935 }
3936 } else {
3937 headLocalPTS = transformedPTS;
3938 }
3939 }
3940
3941 // adjust the head buffer's PTS to reflect the portion of the head buffer
3942 // that has already been consumed
3943 int64_t effectivePTS = headLocalPTS +
3944 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
3945
3946 // Calculate the delta in samples between the head of the input buffer
3947 // queue and the start of the next output buffer that will be written.
3948 // If the transformation fails because of over or underflow, it means
3949 // that the sample's position in the output stream is so far out of
3950 // whack that it should just be dropped.
3951 int64_t sampleDelta;
3952 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
3953 ALOGV("*** head buffer is too far from PTS: dropped buffer");
3954 mTimedBufferQueue.removeAt(0);
3955 continue;
3956 }
3957 if (!mLocalTimeToSampleTransform.doForwardTransform(
3958 (effectivePTS - pts) << 32, &sampleDelta)) {
3959 ALOGV("*** too late during sample rate transform: dropped buffer");
3960 mTimedBufferQueue.removeAt(0);
3961 continue;
3962 }
3963
3964 ALOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
3965 __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
3966 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
3967 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
3968
3969 // if the delta between the ideal placement for the next input sample and
3970 // the current output position is within this threshold, then we will
3971 // concatenate the next input samples to the previous output
3972 const int64_t kSampleContinuityThreshold =
3973 (static_cast<int64_t>(sampleRate()) << 32) / 10;
3974
3975 // if this is the first buffer of audio that we're emitting from this track
3976 // then it should be almost exactly on time.
3977 const int64_t kSampleStartupThreshold = 1LL << 32;
3978
3979 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
3980 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
3981 // the next input is close enough to being on time, so concatenate it
3982 // with the last output
3983 timedYieldSamples(buffer);
3984
3985 ALOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
3986 return NO_ERROR;
3987 } else if (sampleDelta > 0) {
3988 // the gap between the current output position and the proper start of
3989 // the next input sample is too big, so fill it with silence
3990 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
3991
3992 timedYieldSilence(framesUntilNextInput, buffer);
3993 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
3994 return NO_ERROR;
3995 } else {
3996 // the next input sample is late
3997 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
3998 size_t onTimeSamplePosition =
3999 head.position() + lateFrames * mCblk->frameSize;
4000
4001 if (onTimeSamplePosition > head.buffer()->size()) {
4002 // all the remaining samples in the head are too late, so
4003 // drop it and move on
4004 ALOGV("*** too late: dropped buffer");
4005 mTimedBufferQueue.removeAt(0);
4006 continue;
4007 } else {
4008 // skip over the late samples
4009 head.setPosition(onTimeSamplePosition);
4010
4011 // yield the available samples
4012 timedYieldSamples(buffer);
4013
4014 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4015 return NO_ERROR;
4016 }
4017 }
4018 }
4019}
4020
4021// Yield samples from the timed buffer queue head up to the given output
4022// buffer's capacity.
4023//
4024// Caller must hold mTimedBufferQueueLock
4025void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples(
4026 AudioBufferProvider::Buffer* buffer) {
4027
4028 const TimedBuffer& head = mTimedBufferQueue[0];
4029
4030 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4031 head.position());
4032
4033 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4034 mCblk->frameSize);
4035 size_t framesRequested = buffer->frameCount;
4036 buffer->frameCount = min(framesLeftInHead, framesRequested);
4037
4038 mTimedAudioOutputOnTime = true;
4039}
4040
4041// Yield samples of silence up to the given output buffer's capacity
4042//
4043// Caller must hold mTimedBufferQueueLock
4044void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence(
4045 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4046
4047 // lazily allocate a buffer filled with silence
4048 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4049 delete [] mTimedSilenceBuffer;
4050 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4051 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4052 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4053 }
4054
4055 buffer->raw = mTimedSilenceBuffer;
4056 size_t framesRequested = buffer->frameCount;
4057 buffer->frameCount = min(numFrames, framesRequested);
4058
4059 mTimedAudioOutputOnTime = false;
4060}
4061
Glenn Kastenc2db1192012-02-22 10:47:35 -08004062// AudioBufferProvider interface
John Grossmand8cf2962012-02-08 16:37:41 -08004063void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4064 AudioBufferProvider::Buffer* buffer) {
4065
4066 Mutex::Autolock _l(mTimedBufferQueueLock);
4067
John Grossman8c010612012-02-12 17:51:21 -08004068 // If the buffer which was just released is part of the buffer at the head
4069 // of the queue, be sure to update the amt of the buffer which has been
4070 // consumed. If the buffer being returned is not part of the head of the
4071 // queue, its either because the buffer is part of the silence buffer, or
4072 // because the head of the timed queue was trimmed after the mixer called
4073 // getNextBuffer but before the mixer called releaseBuffer.
4074 if ((buffer->raw != mTimedSilenceBuffer) && mTimedBufferQueue.size()) {
John Grossmand8cf2962012-02-08 16:37:41 -08004075 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossman8c010612012-02-12 17:51:21 -08004076
4077 void* start = head.buffer()->pointer();
Glenn Kasten175b2be2012-02-17 16:24:10 -08004078 void* end = (char *) head.buffer()->pointer() + head.buffer()->size();
John Grossman8c010612012-02-12 17:51:21 -08004079
4080 if ((buffer->raw >= start) && (buffer->raw <= end)) {
4081 head.setPosition(head.position() +
4082 (buffer->frameCount * mCblk->frameSize));
4083 if (static_cast<size_t>(head.position()) >= head.buffer()->size()) {
4084 mTimedBufferQueue.removeAt(0);
4085 }
John Grossmand8cf2962012-02-08 16:37:41 -08004086 }
4087 }
4088
4089 buffer->raw = 0;
4090 buffer->frameCount = 0;
4091}
4092
4093uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4094 Mutex::Autolock _l(mTimedBufferQueueLock);
4095
4096 uint32_t frames = 0;
4097 for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4098 const TimedBuffer& tb = mTimedBufferQueue[i];
4099 frames += (tb.buffer()->size() - tb.position()) / mCblk->frameSize;
4100 }
4101
4102 return frames;
4103}
4104
4105AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4106 : mPTS(0), mPosition(0) {}
4107
4108AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4109 const sp<IMemory>& buffer, int64_t pts)
4110 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4111
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004112// ----------------------------------------------------------------------------
4113
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004114// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07004115AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten685c9ce2012-01-20 13:32:16 -08004116 RecordThread *thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004117 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004118 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004119 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004120 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004121 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07004122 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07004123 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten35269822012-02-21 10:35:56 -08004124 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07004125 mOverflow(false)
4126{
Eric Laurent8a77a992009-09-09 05:16:08 -07004127 if (mCblk != NULL) {
Steve Block71f2cf12011-10-20 11:56:00 +01004128 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004129 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004130 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004131 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004132 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Eric Laurent8a77a992009-09-09 05:16:08 -07004133 } else {
4134 mCblk->frameSize = sizeof(int8_t);
4135 }
4136 }
Eric Laurenta553c252009-07-17 12:17:14 -07004137}
4138
4139AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004140{
Eric Laurent49f02be2009-11-19 09:00:56 -08004141 sp<ThreadBase> thread = mThread.promote();
4142 if (thread != 0) {
4143 AudioSystem::releaseInput(thread->id());
4144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145}
4146
Glenn Kastenc2db1192012-02-22 10:47:35 -08004147// AudioBufferProvider interface
John Grossmand8cf2962012-02-08 16:37:41 -08004148status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004149{
4150 audio_track_cblk_t* cblk = this->cblk();
4151 uint32_t framesAvail;
4152 uint32_t framesReq = buffer->frameCount;
4153
4154 // Check if last stepServer failed, try to step now
Glenn Kasten35269822012-02-21 10:35:56 -08004155 if (mStepServerFailed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004156 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01004157 ALOGV("stepServer recovered");
Glenn Kasten35269822012-02-21 10:35:56 -08004158 mStepServerFailed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004159 }
4160
4161 framesAvail = cblk->framesAvailable_l();
4162
Glenn Kastene80a4cc2011-12-15 09:51:17 -08004163 if (CC_LIKELY(framesAvail)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 uint32_t s = cblk->server;
4165 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4166
4167 if (framesReq > framesAvail) {
4168 framesReq = framesAvail;
4169 }
4170 if (s + framesReq > bufferEnd) {
4171 framesReq = bufferEnd - s;
4172 }
4173
4174 buffer->raw = getBuffer(s, framesReq);
Glenn Kastenc434c902011-12-13 11:53:26 -08004175 if (buffer->raw == NULL) goto getNextBuffer_exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004176
4177 buffer->frameCount = framesReq;
4178 return NO_ERROR;
4179 }
4180
4181getNextBuffer_exit:
Glenn Kastenc434c902011-12-13 11:53:26 -08004182 buffer->raw = NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004183 buffer->frameCount = 0;
4184 return NOT_ENOUGH_DATA;
4185}
4186
Glenn Kasten6a20b262012-02-02 10:56:47 -08004187status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004188{
Eric Laurenta553c252009-07-17 12:17:14 -07004189 sp<ThreadBase> thread = mThread.promote();
4190 if (thread != 0) {
4191 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten6a20b262012-02-02 10:56:47 -08004192 return recordThread->start(this, tid);
Eric Laurent49f02be2009-11-19 09:00:56 -08004193 } else {
4194 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07004195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004196}
4197
Eric Laurenta553c252009-07-17 12:17:14 -07004198void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199{
Eric Laurenta553c252009-07-17 12:17:14 -07004200 sp<ThreadBase> thread = mThread.promote();
4201 if (thread != 0) {
4202 RecordThread *recordThread = (RecordThread *)thread.get();
4203 recordThread->stop(this);
Eric Laurentae29b762011-03-28 18:37:07 -07004204 TrackBase::reset();
4205 // Force overerrun condition to avoid false overrun callback until first data is
4206 // read from buffer
4207 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07004208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004209}
4210
Eric Laurent3fdb1262009-11-07 00:01:32 -08004211void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4212{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004213 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten81211142012-02-05 18:09:08 -08004214 (mClient == 0) ? getpid_cached : mClient->pid(),
Eric Laurent3fdb1262009-11-07 00:01:32 -08004215 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004216 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07004217 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08004218 mFrameCount,
4219 mState,
4220 mCblk->sampleRate,
4221 mCblk->server,
4222 mCblk->user);
4223}
4224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004225
4226// ----------------------------------------------------------------------------
4227
Eric Laurenta553c252009-07-17 12:17:14 -07004228AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten685c9ce2012-01-20 13:32:16 -08004229 PlaybackThread *playbackThread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08004230 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004231 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004232 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004233 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004234 int frameCount)
Glenn Kasten685c9ce2012-01-20 13:32:16 -08004235 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08004236 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004237{
Eric Laurenta553c252009-07-17 12:17:14 -07004238
Eric Laurent6c30a712009-08-10 23:22:32 -07004239 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004240 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07004241 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Eric Laurent6c30a712009-08-10 23:22:32 -07004242 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07004243 playbackThread->mTracks.add(this);
Steve Block71f2cf12011-10-20 11:56:00 +01004244 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004245 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4246 mCblk, mBuffer, mCblk->buffers,
4247 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07004248 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00004249 ALOGW("Error creating output track on thread %p", playbackThread);
Eric Laurent6c30a712009-08-10 23:22:32 -07004250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004251}
4252
Eric Laurenta553c252009-07-17 12:17:14 -07004253AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004254{
Eric Laurent6c30a712009-08-10 23:22:32 -07004255 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004256}
4257
Glenn Kasten6a20b262012-02-02 10:56:47 -08004258status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259{
Glenn Kasten6a20b262012-02-02 10:56:47 -08004260 status_t status = Track::start(tid);
Eric Laurenta553c252009-07-17 12:17:14 -07004261 if (status != NO_ERROR) {
4262 return status;
4263 }
4264
4265 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004266 mRetryCount = 127;
4267 return status;
4268}
4269
Eric Laurenta553c252009-07-17 12:17:14 -07004270void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004271{
4272 Track::stop();
4273 clearBufferQueue();
4274 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004275 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276}
4277
Eric Laurenta553c252009-07-17 12:17:14 -07004278bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004279{
4280 Buffer *pInBuffer;
4281 Buffer inBuffer;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004282 uint32_t channelCount = mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07004283 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004284 inBuffer.frameCount = frames;
4285 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07004286
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08004287 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07004288
Eric Laurent62443f52009-10-05 20:29:18 -07004289 if (!mActive && frames != 0) {
Glenn Kasten6a20b262012-02-02 10:56:47 -08004290 start(0);
Eric Laurenta553c252009-07-17 12:17:14 -07004291 sp<ThreadBase> thread = mThread.promote();
4292 if (thread != 0) {
4293 MixerThread *mixerThread = (MixerThread *)thread.get();
4294 if (mCblk->frameCount > frames){
4295 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4296 uint32_t startFrames = (mCblk->frameCount - frames);
4297 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07004298 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07004299 pInBuffer->frameCount = startFrames;
4300 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07004301 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07004302 mBufferQueue.add(pInBuffer);
4303 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00004304 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurenta553c252009-07-17 12:17:14 -07004305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004306 }
Eric Laurenta553c252009-07-17 12:17:14 -07004307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004308 }
4309
Eric Laurenta553c252009-07-17 12:17:14 -07004310 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004311 // First write pending buffers, then new data
4312 if (mBufferQueue.size()) {
4313 pInBuffer = mBufferQueue.itemAt(0);
4314 } else {
4315 pInBuffer = &inBuffer;
4316 }
Eric Laurenta553c252009-07-17 12:17:14 -07004317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004318 if (pInBuffer->frameCount == 0) {
4319 break;
4320 }
Eric Laurenta553c252009-07-17 12:17:14 -07004321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004322 if (mOutBuffer.frameCount == 0) {
4323 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07004324 nsecs_t startTime = systemTime();
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08004325 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block71f2cf12011-10-20 11:56:00 +01004326 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07004327 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004328 break;
4329 }
Eric Laurenta553c252009-07-17 12:17:14 -07004330 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07004331 if (waitTimeLeftMs >= waitTimeMs) {
4332 waitTimeLeftMs -= waitTimeMs;
4333 } else {
4334 waitTimeLeftMs = 0;
4335 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004336 }
Eric Laurenta553c252009-07-17 12:17:14 -07004337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004338 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07004339 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004340 mCblk->stepUser(outFrames);
4341 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07004342 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004343 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07004344 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07004345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004346 if (pInBuffer->frameCount == 0) {
4347 if (mBufferQueue.size()) {
4348 mBufferQueue.removeAt(0);
4349 delete [] pInBuffer->mBuffer;
4350 delete pInBuffer;
Steve Block71f2cf12011-10-20 11:56:00 +01004351 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 -08004352 } else {
4353 break;
4354 }
4355 }
4356 }
Eric Laurenta553c252009-07-17 12:17:14 -07004357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004358 // If we could not write all frames, allocate a buffer and queue it for next time.
4359 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08004360 sp<ThreadBase> thread = mThread.promote();
4361 if (thread != 0 && !thread->standby()) {
4362 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4363 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07004364 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08004365 pInBuffer->frameCount = inBuffer.frameCount;
4366 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07004367 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08004368 mBufferQueue.add(pInBuffer);
Steve Block71f2cf12011-10-20 11:56:00 +01004369 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08004370 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00004371 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08004372 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004373 }
4374 }
Eric Laurenta553c252009-07-17 12:17:14 -07004375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004376 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07004377 // 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 -08004378 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07004379 if (frames == 0 && mBufferQueue.size() == 0) {
4380 if (mCblk->user < mCblk->frameCount) {
4381 frames = mCblk->frameCount - mCblk->user;
4382 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07004383 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07004384 pInBuffer->frameCount = frames;
4385 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07004386 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07004387 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07004388 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07004389 stop();
4390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004391 }
4392
Eric Laurenta553c252009-07-17 12:17:14 -07004393 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004394}
4395
Eric Laurenta553c252009-07-17 12:17:14 -07004396status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004397{
4398 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004399 status_t result;
4400 audio_track_cblk_t* cblk = mCblk;
4401 uint32_t framesReq = buffer->frameCount;
4402
Steve Block71f2cf12011-10-20 11:56:00 +01004403// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004404 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004406 uint32_t framesAvail = cblk->framesAvailable();
4407
Eric Laurenta553c252009-07-17 12:17:14 -07004408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004409 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004410 Mutex::Autolock _l(cblk->lock);
4411 goto start_loop_here;
4412 while (framesAvail == 0) {
4413 active = mActive;
Glenn Kastene80a4cc2011-12-15 09:51:17 -08004414 if (CC_UNLIKELY(!active)) {
Steve Block71f2cf12011-10-20 11:56:00 +01004415 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08004416 return NO_MORE_BUFFERS;
Eric Laurenta553c252009-07-17 12:17:14 -07004417 }
4418 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4419 if (result != NO_ERROR) {
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08004420 return NO_MORE_BUFFERS;
Eric Laurenta553c252009-07-17 12:17:14 -07004421 }
4422 // read the server count again
4423 start_loop_here:
4424 framesAvail = cblk->framesAvailable_l();
4425 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004426 }
4427
Eric Laurenta553c252009-07-17 12:17:14 -07004428// if (framesAvail < framesReq) {
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08004429// return NO_MORE_BUFFERS;
Eric Laurenta553c252009-07-17 12:17:14 -07004430// }
4431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004432 if (framesReq > framesAvail) {
4433 framesReq = framesAvail;
4434 }
4435
4436 uint32_t u = cblk->user;
4437 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4438
4439 if (u + framesReq > bufferEnd) {
4440 framesReq = bufferEnd - u;
4441 }
4442
4443 buffer->frameCount = framesReq;
4444 buffer->raw = (void *)cblk->buffer(u);
4445 return NO_ERROR;
4446}
4447
4448
Eric Laurenta553c252009-07-17 12:17:14 -07004449void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004450{
4451 size_t size = mBufferQueue.size();
Eric Laurenta553c252009-07-17 12:17:14 -07004452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004453 for (size_t i = 0; i < size; i++) {
Glenn Kasten7d3be3a2012-01-26 10:53:32 -08004454 Buffer *pBuffer = mBufferQueue.itemAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004455 delete [] pBuffer->mBuffer;
4456 delete pBuffer;
4457 }
4458 mBufferQueue.clear();
4459}
4460
4461// ----------------------------------------------------------------------------
4462
4463AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4464 : RefBase(),
4465 mAudioFlinger(audioFlinger),
Glenn Kastenb3db2132012-01-19 08:59:58 -08004466 // 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 -08004467 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossmand8cf2962012-02-08 16:37:41 -08004468 mPid(pid),
4469 mTimedTrackCount(0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004470{
4471 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4472}
4473
Eric Laurentb9481d82009-09-17 05:12:56 -07004474// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004475AudioFlinger::Client::~Client()
4476{
Eric Laurentb9481d82009-09-17 05:12:56 -07004477 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004478}
4479
Glenn Kasten1f812f72012-01-30 10:15:48 -08004480sp<MemoryDealer> AudioFlinger::Client::heap() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004481{
4482 return mMemoryDealer;
4483}
4484
John Grossmand8cf2962012-02-08 16:37:41 -08004485// Reserve one of the limited slots for a timed audio track associated
4486// with this client
4487bool AudioFlinger::Client::reserveTimedTrack()
4488{
4489 const int kMaxTimedTracksPerClient = 4;
4490
4491 Mutex::Autolock _l(mTimedTrackLock);
4492
4493 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4494 ALOGW("can not create timed track - pid %d has exceeded the limit",
4495 mPid);
4496 return false;
4497 }
4498
4499 mTimedTrackCount++;
4500 return true;
4501}
4502
4503// Release a slot for a timed audio track
4504void AudioFlinger::Client::releaseTimedTrack()
4505{
4506 Mutex::Autolock _l(mTimedTrackLock);
4507 mTimedTrackCount--;
4508}
4509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004510// ----------------------------------------------------------------------------
4511
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004512AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4513 const sp<IAudioFlingerClient>& client,
4514 pid_t pid)
Glenn Kastendc3ac852012-01-25 15:28:08 -08004515 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004516{
4517}
4518
4519AudioFlinger::NotificationClient::~NotificationClient()
4520{
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004521}
4522
4523void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4524{
4525 sp<NotificationClient> keep(this);
Glenn Kasten7d3be3a2012-01-26 10:53:32 -08004526 mAudioFlinger->removeNotificationClient(mPid);
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004527}
4528
4529// ----------------------------------------------------------------------------
4530
Eric Laurenta553c252009-07-17 12:17:14 -07004531AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004532 : BnAudioTrack(),
4533 mTrack(track)
4534{
4535}
4536
4537AudioFlinger::TrackHandle::~TrackHandle() {
4538 // just stop the track on deletion, associated resources
4539 // will be freed from the main thread once all pending buffers have
4540 // been played. Unless it's not in the active track list, in which
4541 // case we free everything now...
4542 mTrack->destroy();
4543}
4544
Glenn Kasten0ae4d972012-01-26 13:40:12 -08004545sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4546 return mTrack->getCblk();
4547}
4548
Glenn Kasten6a20b262012-02-02 10:56:47 -08004549status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4550 return mTrack->start(tid);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004551}
4552
4553void AudioFlinger::TrackHandle::stop() {
4554 mTrack->stop();
4555}
4556
4557void AudioFlinger::TrackHandle::flush() {
4558 mTrack->flush();
4559}
4560
4561void AudioFlinger::TrackHandle::mute(bool e) {
4562 mTrack->mute(e);
4563}
4564
4565void AudioFlinger::TrackHandle::pause() {
4566 mTrack->pause();
4567}
4568
Eric Laurent65b65452010-06-01 23:49:17 -07004569status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4570{
4571 return mTrack->attachAuxEffect(EffectId);
4572}
4573
John Grossmand8cf2962012-02-08 16:37:41 -08004574status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4575 sp<IMemory>* buffer) {
4576 if (!mTrack->isTimedTrack())
4577 return INVALID_OPERATION;
4578
4579 PlaybackThread::TimedTrack* tt =
4580 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4581 return tt->allocateTimedBuffer(size, buffer);
4582}
4583
4584status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4585 int64_t pts) {
4586 if (!mTrack->isTimedTrack())
4587 return INVALID_OPERATION;
4588
4589 PlaybackThread::TimedTrack* tt =
4590 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4591 return tt->queueTimedBuffer(buffer, pts);
4592}
4593
4594status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4595 const LinearTransform& xform, int target) {
4596
4597 if (!mTrack->isTimedTrack())
4598 return INVALID_OPERATION;
4599
4600 PlaybackThread::TimedTrack* tt =
4601 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4602 return tt->setMediaTimeTransform(
4603 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4604}
4605
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004606status_t AudioFlinger::TrackHandle::onTransact(
4607 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4608{
4609 return BnAudioTrack::onTransact(code, data, reply, flags);
4610}
4611
4612// ----------------------------------------------------------------------------
4613
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004614sp<IAudioRecord> AudioFlinger::openRecord(
4615 pid_t pid,
Glenn Kasten39d00cb2012-01-17 11:09:42 -08004616 audio_io_handle_t input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004617 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004618 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004619 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004620 int frameCount,
Glenn Kasten35269822012-02-21 10:35:56 -08004621 // FIXME dead, remove from IAudioFlinger
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004622 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07004623 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004624 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004625{
Eric Laurenta553c252009-07-17 12:17:14 -07004626 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004627 sp<RecordHandle> recordHandle;
4628 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004629 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07004630 RecordThread *thread;
4631 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07004632 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004633
4634 // check calling permissions
4635 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004636 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004637 goto Exit;
4638 }
4639
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004640 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004641 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004642 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004643 thread = checkRecordThread_l(input);
4644 if (thread == NULL) {
4645 lStatus = BAD_VALUE;
4646 goto Exit;
4647 }
4648
Glenn Kasten803a86a2012-01-25 14:28:29 -08004649 client = registerPid_l(pid);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004650
Eric Laurent65b65452010-06-01 23:49:17 -07004651 // If no audio session id is provided, create one here
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004652 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07004653 lSessionId = *sessionId;
4654 } else {
Eric Laurent464d5b32011-06-17 21:29:58 -07004655 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004656 if (sessionId != NULL) {
4657 *sessionId = lSessionId;
4658 }
4659 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004660 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent464d5b32011-06-17 21:29:58 -07004661 recordTrack = thread->createRecordTrack_l(client,
4662 sampleRate,
4663 format,
4664 channelMask,
4665 frameCount,
Eric Laurent464d5b32011-06-17 21:29:58 -07004666 lSessionId,
4667 &lStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004668 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004669 if (lStatus != NO_ERROR) {
Eric Laurentb9481d82009-09-17 05:12:56 -07004670 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4671 // destructor is called by the TrackBase destructor with mLock held
4672 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004673 recordTrack.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004674 goto Exit;
4675 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004676
4677 // return to handle to client
4678 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004679 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004680
4681Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004682 if (status) {
4683 *status = lStatus;
4684 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004685 return recordHandle;
4686}
4687
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004688// ----------------------------------------------------------------------------
4689
Eric Laurenta553c252009-07-17 12:17:14 -07004690AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004691 : BnAudioRecord(),
4692 mRecordTrack(recordTrack)
4693{
4694}
4695
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004696AudioFlinger::RecordHandle::~RecordHandle() {
4697 stop();
4698}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004699
Glenn Kasten0ae4d972012-01-26 13:40:12 -08004700sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4701 return mRecordTrack->getCblk();
4702}
4703
Glenn Kasten6a20b262012-02-02 10:56:47 -08004704status_t AudioFlinger::RecordHandle::start(pid_t tid) {
Steve Block71f2cf12011-10-20 11:56:00 +01004705 ALOGV("RecordHandle::start()");
Glenn Kasten6a20b262012-02-02 10:56:47 -08004706 return mRecordTrack->start(tid);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004707}
4708
4709void AudioFlinger::RecordHandle::stop() {
Steve Block71f2cf12011-10-20 11:56:00 +01004710 ALOGV("RecordHandle::stop()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004711 mRecordTrack->stop();
4712}
4713
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004714status_t AudioFlinger::RecordHandle::onTransact(
4715 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4716{
4717 return BnAudioRecord::onTransact(code, data, reply, flags);
4718}
4719
4720// ----------------------------------------------------------------------------
4721
Eric Laurent464d5b32011-06-17 21:29:58 -07004722AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4723 AudioStreamIn *input,
4724 uint32_t sampleRate,
4725 uint32_t channels,
Glenn Kasten39d00cb2012-01-17 11:09:42 -08004726 audio_io_handle_t id,
Eric Laurent464d5b32011-06-17 21:29:58 -07004727 uint32_t device) :
Glenn Kastenefd511a2012-01-26 10:38:26 -08004728 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kastendc3ac852012-01-25 15:28:08 -08004729 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4730 // mRsmpInIndex and mInputBytes set by readInputParameters()
4731 mReqChannelCount(popcount(channels)),
4732 mReqSampleRate(sampleRate)
4733 // mBytesRead is only meaningful while active, and so is cleared in start()
4734 // (but might be better to also clear here for dump?)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004735{
Glenn Kasten86e33622012-02-28 12:30:08 -08004736 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurent6dbdc402011-07-22 09:04:31 -07004737
Eric Laurenta553c252009-07-17 12:17:14 -07004738 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004739}
4740
Eric Laurenta553c252009-07-17 12:17:14 -07004741
4742AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004743{
Eric Laurenta553c252009-07-17 12:17:14 -07004744 delete[] mRsmpInBuffer;
Glenn Kasten2589cf92012-01-27 18:08:45 -08004745 delete mResampler;
4746 delete[] mRsmpOutBuffer;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004747}
4748
Eric Laurenta553c252009-07-17 12:17:14 -07004749void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004750{
Eric Laurent6dbdc402011-07-22 09:04:31 -07004751 run(mName, PRIORITY_URGENT_AUDIO);
Eric Laurenta553c252009-07-17 12:17:14 -07004752}
Eric Laurent49f02be2009-11-19 09:00:56 -08004753
Eric Laurent828b9772011-08-07 16:32:26 -07004754status_t AudioFlinger::RecordThread::readyToRun()
4755{
4756 status_t status = initCheck();
Steve Block8564c8d2012-01-05 23:22:43 +00004757 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurent828b9772011-08-07 16:32:26 -07004758 return status;
4759}
4760
Eric Laurenta553c252009-07-17 12:17:14 -07004761bool AudioFlinger::RecordThread::threadLoop()
4762{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004763 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004764 sp<RecordTrack> activeTrack;
Eric Laurent464d5b32011-06-17 21:29:58 -07004765 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004766
Eric Laurent4712baa2010-09-30 16:12:31 -07004767 nsecs_t lastWarning = 0;
4768
Eric Laurent6dbdc402011-07-22 09:04:31 -07004769 acquireWakeLock();
4770
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004771 // start recording
4772 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004773
Eric Laurenta553c252009-07-17 12:17:14 -07004774 processConfigEvents();
4775
4776 { // scope for mLock
4777 Mutex::Autolock _l(mLock);
4778 checkForNewParameters_l();
4779 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4780 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004781 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004782 mStandby = true;
4783 }
4784
4785 if (exitPending()) break;
4786
Eric Laurent6dbdc402011-07-22 09:04:31 -07004787 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01004788 ALOGV("RecordThread: loop stopping");
Eric Laurenta553c252009-07-17 12:17:14 -07004789 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004790 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01004791 ALOGV("RecordThread: loop starting");
Eric Laurent6dbdc402011-07-22 09:04:31 -07004792 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004793 continue;
4794 }
4795 if (mActiveTrack != 0) {
4796 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004797 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004798 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004799 mStandby = true;
4800 }
Eric Laurenta553c252009-07-17 12:17:14 -07004801 mActiveTrack.clear();
4802 mStartStopCond.broadcast();
4803 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07004804 if (mReqChannelCount != mActiveTrack->channelCount()) {
4805 mActiveTrack.clear();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004806 mStartStopCond.broadcast();
4807 } else if (mBytesRead != 0) {
4808 // record start succeeds only if first read from audio input
4809 // succeeds
4810 if (mBytesRead > 0) {
4811 mActiveTrack->mState = TrackBase::ACTIVE;
4812 } else {
4813 mActiveTrack.clear();
4814 }
4815 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07004816 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004817 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07004818 }
Eric Laurenta553c252009-07-17 12:17:14 -07004819 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004820 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07004821 }
4822
4823 if (mActiveTrack != 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004824 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4825 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004826 unlockEffectChains(effectChains);
4827 usleep(kRecordThreadSleepUs);
Eric Laurent49f02be2009-11-19 09:00:56 -08004828 continue;
4829 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004830 for (size_t i = 0; i < effectChains.size(); i ++) {
4831 effectChains[i]->process_l();
4832 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004833
Eric Laurenta553c252009-07-17 12:17:14 -07004834 buffer.frameCount = mFrameCount;
Glenn Kastenc2db1192012-02-22 10:47:35 -08004835 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004836 size_t framesOut = buffer.frameCount;
Glenn Kastenc434c902011-12-13 11:53:26 -08004837 if (mResampler == NULL) {
Eric Laurenta553c252009-07-17 12:17:14 -07004838 // no resampling
4839 while (framesOut) {
4840 size_t framesIn = mFrameCount - mRsmpInIndex;
4841 if (framesIn) {
4842 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4843 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4844 if (framesIn > framesOut)
4845 framesIn = framesOut;
4846 mRsmpInIndex += framesIn;
4847 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07004848 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004849 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07004850 memcpy(dst, src, framesIn * mFrameSize);
4851 } else {
4852 int16_t *src16 = (int16_t *)src;
4853 int16_t *dst16 = (int16_t *)dst;
4854 if (mChannelCount == 1) {
4855 while (framesIn--) {
4856 *dst16++ = *src16;
4857 *dst16++ = *src16++;
4858 }
4859 } else {
4860 while (framesIn--) {
4861 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4862 src16 += 2;
4863 }
4864 }
4865 }
4866 }
4867 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07004868 if (framesOut == mFrameCount &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004869 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin31f188892011-04-18 16:57:27 -07004870 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004871 framesOut = 0;
4872 } else {
Dima Zavin31f188892011-04-18 16:57:27 -07004873 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004874 mRsmpInIndex = 0;
4875 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004876 if (mBytesRead < 0) {
Steve Block3762c312012-01-06 19:20:56 +00004877 ALOGE("Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004878 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004879 // Force input into standby so that it tries to
4880 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004881 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004882 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004883 }
Eric Laurenta553c252009-07-17 12:17:14 -07004884 mRsmpInIndex = mFrameCount;
4885 framesOut = 0;
4886 buffer.frameCount = 0;
4887 }
4888 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004889 }
4890 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07004891 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004892
Eric Laurenta553c252009-07-17 12:17:14 -07004893 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4894 // alter output frame count as if we were expecting stereo samples
4895 if (mChannelCount == 1 && mReqChannelCount == 1) {
4896 framesOut >>= 1;
4897 }
4898 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4899 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4900 // are 32 bit aligned which should be always true.
4901 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten490909d2011-12-15 09:52:39 -08004902 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Eric Laurenta553c252009-07-17 12:17:14 -07004903 // the resampler always outputs stereo samples: do post stereo to mono conversion
4904 int16_t *src = (int16_t *)mRsmpOutBuffer;
4905 int16_t *dst = buffer.i16;
4906 while (framesOut--) {
4907 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4908 src += 2;
4909 }
4910 } else {
Glenn Kasten490909d2011-12-15 09:52:39 -08004911 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Eric Laurenta553c252009-07-17 12:17:14 -07004912 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004913
Eric Laurenta553c252009-07-17 12:17:14 -07004914 }
4915 mActiveTrack->releaseBuffer(&buffer);
4916 mActiveTrack->overflow();
4917 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004918 // client isn't retrieving buffers fast enough
4919 else {
Eric Laurent4712baa2010-09-30 16:12:31 -07004920 if (!mActiveTrack->setOverflow()) {
4921 nsecs_t now = systemTime();
Glenn Kastencbfe2e12011-12-13 11:04:14 -08004922 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block8564c8d2012-01-05 23:22:43 +00004923 ALOGW("RecordThread: buffer overflow");
Eric Laurent4712baa2010-09-30 16:12:31 -07004924 lastWarning = now;
4925 }
4926 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004927 // Release the processor for a while before asking for a new buffer.
4928 // This will give the application more chance to read from the buffer and
4929 // clear the overflow.
Eric Laurent464d5b32011-06-17 21:29:58 -07004930 usleep(kRecordThreadSleepUs);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004931 }
4932 }
Eric Laurent21b5c472011-07-26 20:54:46 -07004933 // enable changes in effect chain
4934 unlockEffectChains(effectChains);
Eric Laurent464d5b32011-06-17 21:29:58 -07004935 effectChains.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004936 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004937
Eric Laurenta553c252009-07-17 12:17:14 -07004938 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004939 mInput->stream->common.standby(&mInput->stream->common);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004940 }
Eric Laurenta553c252009-07-17 12:17:14 -07004941 mActiveTrack.clear();
4942
Eric Laurent49f02be2009-11-19 09:00:56 -08004943 mStartStopCond.broadcast();
4944
Eric Laurent6dbdc402011-07-22 09:04:31 -07004945 releaseWakeLock();
4946
Steve Block71f2cf12011-10-20 11:56:00 +01004947 ALOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004948 return false;
4949}
4950
Eric Laurent464d5b32011-06-17 21:29:58 -07004951
4952sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4953 const sp<AudioFlinger::Client>& client,
4954 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004955 audio_format_t format,
Eric Laurent464d5b32011-06-17 21:29:58 -07004956 int channelMask,
4957 int frameCount,
Eric Laurent464d5b32011-06-17 21:29:58 -07004958 int sessionId,
4959 status_t *status)
4960{
4961 sp<RecordTrack> track;
4962 status_t lStatus;
4963
4964 lStatus = initCheck();
4965 if (lStatus != NO_ERROR) {
Steve Block3762c312012-01-06 19:20:56 +00004966 ALOGE("Audio driver not initialized.");
Eric Laurent464d5b32011-06-17 21:29:58 -07004967 goto Exit;
4968 }
4969
4970 { // scope for mLock
4971 Mutex::Autolock _l(mLock);
4972
4973 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten35269822012-02-21 10:35:56 -08004974 format, channelMask, frameCount, sessionId);
Eric Laurent464d5b32011-06-17 21:29:58 -07004975
Glenn Kasten706b6182012-01-20 13:44:40 -08004976 if (track->getCblk() == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004977 lStatus = NO_MEMORY;
4978 goto Exit;
4979 }
4980
4981 mTrack = track.get();
Eric Laurent6639b552011-08-01 09:52:20 -07004982 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4983 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004984 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004985 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4986 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent464d5b32011-06-17 21:29:58 -07004987 }
4988 lStatus = NO_ERROR;
4989
4990Exit:
4991 if (status) {
4992 *status = lStatus;
4993 }
4994 return track;
4995}
4996
Glenn Kasten6a20b262012-02-02 10:56:47 -08004997status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, pid_t tid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004998{
Glenn Kasten6a20b262012-02-02 10:56:47 -08004999 ALOGV("RecordThread::start tid=%d", tid);
Eric Laurent49f02be2009-11-19 09:00:56 -08005000 sp <ThreadBase> strongMe = this;
5001 status_t status = NO_ERROR;
5002 {
Glenn Kasten325ee1c2012-01-05 15:41:56 -08005003 AutoMutex lock(mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08005004 if (mActiveTrack != 0) {
5005 if (recordTrack != mActiveTrack.get()) {
5006 status = -EBUSY;
5007 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08005008 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08005009 }
5010 return status;
5011 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07005012
Eric Laurent49f02be2009-11-19 09:00:56 -08005013 recordTrack->mState = TrackBase::IDLE;
5014 mActiveTrack = recordTrack;
5015 mLock.unlock();
5016 status_t status = AudioSystem::startInput(mId);
5017 mLock.lock();
5018 if (status != NO_ERROR) {
5019 mActiveTrack.clear();
5020 return status;
5021 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08005022 mRsmpInIndex = mFrameCount;
5023 mBytesRead = 0;
Eric Laurent4bb21c42011-02-28 16:52:51 -08005024 if (mResampler != NULL) {
5025 mResampler->reset();
5026 }
5027 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent49f02be2009-11-19 09:00:56 -08005028 // signal thread to start
Steve Block71f2cf12011-10-20 11:56:00 +01005029 ALOGV("Signal record thread");
Eric Laurent49f02be2009-11-19 09:00:56 -08005030 mWaitWorkCV.signal();
5031 // do not wait for mStartStopCond if exiting
Glenn Kasten761286f2012-01-06 08:39:38 -08005032 if (exitPending()) {
Eric Laurent49f02be2009-11-19 09:00:56 -08005033 mActiveTrack.clear();
5034 status = INVALID_OPERATION;
5035 goto startError;
5036 }
5037 mStartStopCond.wait(mLock);
5038 if (mActiveTrack == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01005039 ALOGV("Record failed to start");
Eric Laurent49f02be2009-11-19 09:00:56 -08005040 status = BAD_VALUE;
5041 goto startError;
5042 }
Steve Block71f2cf12011-10-20 11:56:00 +01005043 ALOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08005044 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07005045 }
Eric Laurent49f02be2009-11-19 09:00:56 -08005046startError:
5047 AudioSystem::stopInput(mId);
5048 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07005049}
5050
Eric Laurenta553c252009-07-17 12:17:14 -07005051void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block71f2cf12011-10-20 11:56:00 +01005052 ALOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08005053 sp <ThreadBase> strongMe = this;
5054 {
Glenn Kasten325ee1c2012-01-05 15:41:56 -08005055 AutoMutex lock(mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08005056 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5057 mActiveTrack->mState = TrackBase::PAUSING;
5058 // do not wait for mStartStopCond if exiting
Glenn Kasten761286f2012-01-06 08:39:38 -08005059 if (exitPending()) {
Eric Laurent49f02be2009-11-19 09:00:56 -08005060 return;
5061 }
5062 mStartStopCond.wait(mLock);
5063 // if we have been restarted, recordTrack == mActiveTrack.get() here
5064 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5065 mLock.unlock();
5066 AudioSystem::stopInput(mId);
5067 mLock.lock();
Steve Block71f2cf12011-10-20 11:56:00 +01005068 ALOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08005069 }
5070 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07005071 }
5072}
5073
Eric Laurenta553c252009-07-17 12:17:14 -07005074status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005075{
5076 const size_t SIZE = 256;
5077 char buffer[SIZE];
5078 String8 result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005079
Eric Laurent3fdb1262009-11-07 00:01:32 -08005080 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5081 result.append(buffer);
5082
5083 if (mActiveTrack != 0) {
5084 result.append("Active Track:\n");
Jean-Michel Trivi54392232011-05-24 15:53:33 -07005085 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08005086 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005087 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08005088
5089 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5090 result.append(buffer);
5091 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5092 result.append(buffer);
Glenn Kastenc434c902011-12-13 11:53:26 -08005093 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Eric Laurent3fdb1262009-11-07 00:01:32 -08005094 result.append(buffer);
5095 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5096 result.append(buffer);
5097 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5098 result.append(buffer);
5099
5100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005101 } else {
5102 result.append("No record client\n");
5103 }
5104 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08005105
5106 dumpBase(fd, args);
Eric Laurent1345d332011-07-24 17:49:51 -07005107 dumpEffectChains(fd, args);
Eric Laurent3fdb1262009-11-07 00:01:32 -08005108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005109 return NO_ERROR;
5110}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07005111
Glenn Kastenc2db1192012-02-22 10:47:35 -08005112// AudioBufferProvider interface
John Grossmand8cf2962012-02-08 16:37:41 -08005113status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Eric Laurenta553c252009-07-17 12:17:14 -07005114{
5115 size_t framesReq = buffer->frameCount;
5116 size_t framesReady = mFrameCount - mRsmpInIndex;
5117 int channelCount;
5118
5119 if (framesReady == 0) {
Dima Zavin31f188892011-04-18 16:57:27 -07005120 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurent9cc489a22009-12-05 05:20:01 -08005121 if (mBytesRead < 0) {
Steve Block3762c312012-01-06 19:20:56 +00005122 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08005123 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08005124 // Force input into standby so that it tries to
5125 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07005126 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07005127 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a22009-12-05 05:20:01 -08005128 }
Glenn Kastenc434c902011-12-13 11:53:26 -08005129 buffer->raw = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07005130 buffer->frameCount = 0;
5131 return NOT_ENOUGH_DATA;
5132 }
5133 mRsmpInIndex = 0;
5134 framesReady = mFrameCount;
5135 }
5136
5137 if (framesReq > framesReady) {
5138 framesReq = framesReady;
5139 }
5140
5141 if (mChannelCount == 1 && mReqChannelCount == 2) {
5142 channelCount = 1;
5143 } else {
5144 channelCount = 2;
5145 }
5146 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5147 buffer->frameCount = framesReq;
5148 return NO_ERROR;
5149}
5150
Glenn Kastenc2db1192012-02-22 10:47:35 -08005151// AudioBufferProvider interface
Eric Laurenta553c252009-07-17 12:17:14 -07005152void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5153{
5154 mRsmpInIndex += buffer->frameCount;
5155 buffer->frameCount = 0;
5156}
5157
5158bool AudioFlinger::RecordThread::checkForNewParameters_l()
5159{
5160 bool reconfig = false;
5161
Eric Laurent8fce46a2009-08-04 09:45:33 -07005162 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07005163 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07005164 String8 keyValuePair = mNewParameters[0];
5165 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07005166 int value;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005167 audio_format_t reqFormat = mFormat;
Eric Laurenta553c252009-07-17 12:17:14 -07005168 int reqSamplingRate = mReqSampleRate;
5169 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07005170
Eric Laurenta553c252009-07-17 12:17:14 -07005171 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5172 reqSamplingRate = value;
5173 reconfig = true;
5174 }
5175 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005176 reqFormat = (audio_format_t) value;
Eric Laurenta553c252009-07-17 12:17:14 -07005177 reconfig = true;
5178 }
5179 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005180 reqChannelCount = popcount(value);
Eric Laurenta553c252009-07-17 12:17:14 -07005181 reconfig = true;
5182 }
5183 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5184 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kastenb3db2132012-01-19 08:59:58 -08005185 // size depends on frame count and correct behavior would not be guaranteed
Eric Laurenta553c252009-07-17 12:17:14 -07005186 // if frame count is changed after track creation
5187 if (mActiveTrack != 0) {
5188 status = INVALID_OPERATION;
5189 } else {
5190 reconfig = true;
5191 }
5192 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005193 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5194 // forward device change to effects that have requested to be
5195 // aware of attached audio device.
5196 for (size_t i = 0; i < mEffectChains.size(); i++) {
5197 mEffectChains[i]->setDevice_l(value);
5198 }
5199 // store input device and output device but do not forward output device to audio HAL.
5200 // Note that status is ignored by the caller for output device
5201 // (see AudioFlinger::setParameters()
5202 if (value & AUDIO_DEVICE_OUT_ALL) {
5203 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5204 status = BAD_VALUE;
5205 } else {
5206 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent6639b552011-08-01 09:52:20 -07005207 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5208 if (mTrack != NULL) {
5209 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07005210 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07005211 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5212 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5213 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005214 }
5215 mDevice |= (uint32_t)value;
5216 }
Eric Laurenta553c252009-07-17 12:17:14 -07005217 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07005218 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07005219 if (status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07005220 mInput->stream->common.standby(&mInput->stream->common);
5221 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07005222 }
5223 if (reconfig) {
5224 if (status == BAD_VALUE &&
Dima Zavin31f188892011-04-18 16:57:27 -07005225 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005226 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin31f188892011-04-18 16:57:27 -07005227 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
5228 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005229 (reqChannelCount < 3)) {
Eric Laurenta553c252009-07-17 12:17:14 -07005230 status = NO_ERROR;
5231 }
5232 if (status == NO_ERROR) {
5233 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07005234 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07005235 }
5236 }
5237 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08005238
5239 mNewParameters.removeAt(0);
5240
Eric Laurenta553c252009-07-17 12:17:14 -07005241 mParamStatus = status;
5242 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07005243 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5244 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08005245 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07005246 }
5247 return reconfig;
5248}
5249
5250String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5251{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005252 char *s;
Eric Laurent828b9772011-08-07 16:32:26 -07005253 String8 out_s8 = String8();
5254
5255 Mutex::Autolock _l(mLock);
5256 if (initCheck() != NO_ERROR) {
5257 return out_s8;
5258 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005259
Dima Zavin31f188892011-04-18 16:57:27 -07005260 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005261 out_s8 = String8(s);
5262 free(s);
5263 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07005264}
5265
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005266void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07005267 AudioSystem::OutputDescriptor desc;
Glenn Kasten3694ec12012-01-27 16:47:15 -08005268 void *param2 = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07005269
5270 switch (event) {
5271 case AudioSystem::INPUT_OPENED:
5272 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07005273 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07005274 desc.samplingRate = mSampleRate;
5275 desc.format = mFormat;
5276 desc.frameCount = mFrameCount;
5277 desc.latency = 0;
5278 param2 = &desc;
5279 break;
5280
5281 case AudioSystem::INPUT_CLOSED:
5282 default:
5283 break;
5284 }
Eric Laurent49f02be2009-11-19 09:00:56 -08005285 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07005286}
5287
5288void AudioFlinger::RecordThread::readInputParameters()
5289{
Glenn Kasten2589cf92012-01-27 18:08:45 -08005290 delete mRsmpInBuffer;
5291 // mRsmpInBuffer is always assigned a new[] below
5292 delete mRsmpOutBuffer;
5293 mRsmpOutBuffer = NULL;
5294 delete mResampler;
Glenn Kastenc434c902011-12-13 11:53:26 -08005295 mResampler = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07005296
Dima Zavin31f188892011-04-18 16:57:27 -07005297 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07005298 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5299 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07005300 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenfaf354d2012-01-11 09:48:27 -08005301 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin31f188892011-04-18 16:57:27 -07005302 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07005303 mFrameCount = mInputBytes / mFrameSize;
5304 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5305
5306 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
5307 {
5308 int channelCount;
5309 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5310 // stereo to mono post process as the resampler always outputs stereo.
5311 if (mChannelCount == 1 && mReqChannelCount == 2) {
5312 channelCount = 1;
5313 } else {
5314 channelCount = 2;
5315 }
5316 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5317 mResampler->setSampleRate(mSampleRate);
5318 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5319 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5320
5321 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5322 if (mChannelCount == 1 && mReqChannelCount == 1) {
5323 mFrameCount >>= 1;
5324 }
5325
5326 }
5327 mRsmpInIndex = mFrameCount;
5328}
5329
Eric Laurent47d0a922010-02-26 02:47:27 -08005330unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5331{
Eric Laurent828b9772011-08-07 16:32:26 -07005332 Mutex::Autolock _l(mLock);
5333 if (initCheck() != NO_ERROR) {
5334 return 0;
5335 }
5336
Dima Zavin31f188892011-04-18 16:57:27 -07005337 return mInput->stream->get_input_frames_lost(mInput->stream);
Eric Laurent47d0a922010-02-26 02:47:27 -08005338}
5339
Eric Laurent464d5b32011-06-17 21:29:58 -07005340uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5341{
5342 Mutex::Autolock _l(mLock);
5343 uint32_t result = 0;
5344 if (getEffectChain_l(sessionId) != 0) {
5345 result = EFFECT_SESSION;
5346 }
5347
5348 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5349 result |= TRACK_SESSION;
5350 }
5351
5352 return result;
5353}
5354
Eric Laurent6639b552011-08-01 09:52:20 -07005355AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5356{
5357 Mutex::Autolock _l(mLock);
5358 return mTrack;
5359}
5360
Glenn Kasten5b0135e2012-01-26 09:46:34 -08005361AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurent828b9772011-08-07 16:32:26 -07005362{
5363 Mutex::Autolock _l(mLock);
5364 return mInput;
5365}
5366
5367AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5368{
5369 Mutex::Autolock _l(mLock);
5370 AudioStreamIn *input = mInput;
5371 mInput = NULL;
5372 return input;
5373}
5374
5375// this method must always be called either with ThreadBase mLock held or inside the thread loop
5376audio_stream_t* AudioFlinger::RecordThread::stream()
5377{
5378 if (mInput == NULL) {
5379 return NULL;
5380 }
5381 return &mInput->stream->common;
5382}
5383
5384
Eric Laurenta553c252009-07-17 12:17:14 -07005385// ----------------------------------------------------------------------------
5386
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005387audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07005388 uint32_t *pSamplingRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005389 audio_format_t *pFormat,
Eric Laurenta553c252009-07-17 12:17:14 -07005390 uint32_t *pChannels,
5391 uint32_t *pLatencyMs,
5392 uint32_t flags)
5393{
5394 status_t status;
5395 PlaybackThread *thread = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07005396 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005397 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Eric Laurenta553c252009-07-17 12:17:14 -07005398 uint32_t channels = pChannels ? *pChannels : 0;
5399 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin31f188892011-04-18 16:57:27 -07005400 audio_stream_out_t *outStream;
5401 audio_hw_device_t *outHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07005402
Steve Block71f2cf12011-10-20 11:56:00 +01005403 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Eric Laurenta553c252009-07-17 12:17:14 -07005404 pDevices ? *pDevices : 0,
5405 samplingRate,
5406 format,
5407 channels,
5408 flags);
5409
5410 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005411 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005412 }
Dima Zavin31f188892011-04-18 16:57:27 -07005413
Eric Laurenta553c252009-07-17 12:17:14 -07005414 Mutex::Autolock _l(mLock);
5415
Dima Zavin31f188892011-04-18 16:57:27 -07005416 outHwDev = findSuitableHwDev_l(*pDevices);
5417 if (outHwDev == NULL)
5418 return 0;
5419
Glenn Kasten23c9c742012-02-02 14:16:03 -08005420 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005421 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin31f188892011-04-18 16:57:27 -07005422 &channels, &samplingRate, &outStream);
Glenn Kasten23c9c742012-02-02 14:16:03 -08005423 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block71f2cf12011-10-20 11:56:00 +01005424 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07005425 outStream,
Eric Laurenta553c252009-07-17 12:17:14 -07005426 samplingRate,
5427 format,
5428 channels,
5429 status);
5430
Dima Zavin31f188892011-04-18 16:57:27 -07005431 if (outStream != NULL) {
5432 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005433 audio_io_handle_t id = nextUniqueId();
Dima Zavin31f188892011-04-18 16:57:27 -07005434
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005435 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5436 (format != AUDIO_FORMAT_PCM_16_BIT) ||
5437 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07005438 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01005439 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07005440 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07005441 thread = new MixerThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01005442 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07005443 }
Eric Laurent65b65452010-06-01 23:49:17 -07005444 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07005445
Glenn Kasten3694ec12012-01-27 16:47:15 -08005446 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5447 if (pFormat != NULL) *pFormat = format;
5448 if (pChannels != NULL) *pChannels = channels;
5449 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Eric Laurent9cc489a22009-12-05 05:20:01 -08005450
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005451 // notify client processes of the new output creation
5452 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07005453 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07005454 }
5455
Eric Laurent9cc489a22009-12-05 05:20:01 -08005456 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005457}
5458
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005459audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
5460 audio_io_handle_t output2)
Eric Laurenta553c252009-07-17 12:17:14 -07005461{
5462 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07005463 MixerThread *thread1 = checkMixerThread_l(output1);
5464 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07005465
Eric Laurentddb78e72009-07-28 08:44:33 -07005466 if (thread1 == NULL || thread2 == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005467 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005468 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005469 }
5470
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005471 audio_io_handle_t id = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07005472 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07005473 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07005474 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005475 // notify client processes of the new output creation
5476 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07005477 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07005478}
5479
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005480status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Eric Laurenta553c252009-07-17 12:17:14 -07005481{
Eric Laurent49018a52009-08-04 08:37:05 -07005482 // keep strong reference on the playback thread so that
5483 // it is not destroyed while exit() is executed
5484 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07005485 {
5486 Mutex::Autolock _l(mLock);
5487 thread = checkPlaybackThread_l(output);
5488 if (thread == NULL) {
5489 return BAD_VALUE;
5490 }
5491
Steve Block71f2cf12011-10-20 11:56:00 +01005492 ALOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005493
Eric Laurent464d5b32011-06-17 21:29:58 -07005494 if (thread->type() == ThreadBase::MIXER) {
Eric Laurenta553c252009-07-17 12:17:14 -07005495 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005496 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005497 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07005498 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07005499 }
5500 }
5501 }
Glenn Kasten7d3be3a2012-01-26 10:53:32 -08005502 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Eric Laurentddb78e72009-07-28 08:44:33 -07005503 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07005504 }
5505 thread->exit();
Glenn Kasten761286f2012-01-06 08:39:38 -08005506 // The thread entity (active unit of execution) is no longer running here,
5507 // but the ThreadBase container still exists.
Eric Laurenta553c252009-07-17 12:17:14 -07005508
Eric Laurent464d5b32011-06-17 21:29:58 -07005509 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurent828b9772011-08-07 16:32:26 -07005510 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5b0135e2012-01-26 09:46:34 -08005511 assert(out != NULL);
Eric Laurent828b9772011-08-07 16:32:26 -07005512 // from now on thread->mOutput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005513 out->hwDev->close_output_stream(out->hwDev, out->stream);
5514 delete out;
Eric Laurent49018a52009-08-04 08:37:05 -07005515 }
Eric Laurenta553c252009-07-17 12:17:14 -07005516 return NO_ERROR;
5517}
5518
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005519status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Eric Laurenta553c252009-07-17 12:17:14 -07005520{
5521 Mutex::Autolock _l(mLock);
5522 PlaybackThread *thread = checkPlaybackThread_l(output);
5523
5524 if (thread == NULL) {
5525 return BAD_VALUE;
5526 }
5527
Steve Block71f2cf12011-10-20 11:56:00 +01005528 ALOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005529 thread->suspend();
5530
5531 return NO_ERROR;
5532}
5533
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005534status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Eric Laurenta553c252009-07-17 12:17:14 -07005535{
5536 Mutex::Autolock _l(mLock);
5537 PlaybackThread *thread = checkPlaybackThread_l(output);
5538
5539 if (thread == NULL) {
5540 return BAD_VALUE;
5541 }
5542
Steve Block71f2cf12011-10-20 11:56:00 +01005543 ALOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005544
5545 thread->restore();
5546
5547 return NO_ERROR;
5548}
5549
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005550audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07005551 uint32_t *pSamplingRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005552 audio_format_t *pFormat,
Eric Laurenta553c252009-07-17 12:17:14 -07005553 uint32_t *pChannels,
Glenn Kasten882c0a22012-01-27 12:32:34 -08005554 audio_in_acoustics_t acoustics)
Eric Laurenta553c252009-07-17 12:17:14 -07005555{
5556 status_t status;
5557 RecordThread *thread = NULL;
5558 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005559 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Eric Laurenta553c252009-07-17 12:17:14 -07005560 uint32_t channels = pChannels ? *pChannels : 0;
5561 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005562 audio_format_t reqFormat = format;
Eric Laurenta553c252009-07-17 12:17:14 -07005563 uint32_t reqChannels = channels;
Dima Zavin31f188892011-04-18 16:57:27 -07005564 audio_stream_in_t *inStream;
5565 audio_hw_device_t *inHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07005566
5567 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005568 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005569 }
Dima Zavin31f188892011-04-18 16:57:27 -07005570
Eric Laurenta553c252009-07-17 12:17:14 -07005571 Mutex::Autolock _l(mLock);
5572
Dima Zavin31f188892011-04-18 16:57:27 -07005573 inHwDev = findSuitableHwDev_l(*pDevices);
5574 if (inHwDev == NULL)
5575 return 0;
5576
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005577 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin31f188892011-04-18 16:57:27 -07005578 &channels, &samplingRate,
Glenn Kasten882c0a22012-01-27 12:32:34 -08005579 acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005580 &inStream);
Steve Block71f2cf12011-10-20 11:56:00 +01005581 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07005582 inStream,
Eric Laurenta553c252009-07-17 12:17:14 -07005583 samplingRate,
5584 format,
5585 channels,
5586 acoustics,
5587 status);
5588
5589 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5590 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5591 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin31f188892011-04-18 16:57:27 -07005592 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005593 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Eric Laurenta553c252009-07-17 12:17:14 -07005594 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005595 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block71f2cf12011-10-20 11:56:00 +01005596 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005597 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin31f188892011-04-18 16:57:27 -07005598 &channels, &samplingRate,
Glenn Kasten882c0a22012-01-27 12:32:34 -08005599 acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005600 &inStream);
Eric Laurenta553c252009-07-17 12:17:14 -07005601 }
5602
Dima Zavin31f188892011-04-18 16:57:27 -07005603 if (inStream != NULL) {
5604 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5605
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005606 audio_io_handle_t id = nextUniqueId();
Eric Laurent464d5b32011-06-17 21:29:58 -07005607 // Start record thread
5608 // RecorThread require both input and output device indication to forward to audio
5609 // pre processing modules
5610 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5611 thread = new RecordThread(this,
5612 input,
5613 reqSamplingRate,
5614 reqChannels,
5615 id,
5616 device);
Eric Laurent65b65452010-06-01 23:49:17 -07005617 mRecordThreads.add(id, thread);
Steve Block71f2cf12011-10-20 11:56:00 +01005618 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kasten3694ec12012-01-27 16:47:15 -08005619 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5620 if (pFormat != NULL) *pFormat = format;
5621 if (pChannels != NULL) *pChannels = reqChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07005622
Dima Zavin31f188892011-04-18 16:57:27 -07005623 input->stream->common.standby(&input->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08005624
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005625 // notify client processes of the new input creation
5626 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07005627 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07005628 }
5629
Eric Laurent9cc489a22009-12-05 05:20:01 -08005630 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005631}
5632
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005633status_t AudioFlinger::closeInput(audio_io_handle_t input)
Eric Laurenta553c252009-07-17 12:17:14 -07005634{
Eric Laurent49018a52009-08-04 08:37:05 -07005635 // keep strong reference on the record thread so that
5636 // it is not destroyed while exit() is executed
5637 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07005638 {
5639 Mutex::Autolock _l(mLock);
5640 thread = checkRecordThread_l(input);
5641 if (thread == NULL) {
5642 return BAD_VALUE;
5643 }
5644
Steve Block71f2cf12011-10-20 11:56:00 +01005645 ALOGV("closeInput() %d", input);
Glenn Kasten7d3be3a2012-01-26 10:53:32 -08005646 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Eric Laurentddb78e72009-07-28 08:44:33 -07005647 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07005648 }
5649 thread->exit();
Glenn Kasten761286f2012-01-06 08:39:38 -08005650 // The thread entity (active unit of execution) is no longer running here,
5651 // but the ThreadBase container still exists.
Eric Laurenta553c252009-07-17 12:17:14 -07005652
Eric Laurent828b9772011-08-07 16:32:26 -07005653 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5b0135e2012-01-26 09:46:34 -08005654 assert(in != NULL);
Eric Laurent828b9772011-08-07 16:32:26 -07005655 // from now on thread->mInput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005656 in->hwDev->close_input_stream(in->hwDev, in->stream);
5657 delete in;
Eric Laurent49018a52009-08-04 08:37:05 -07005658
Eric Laurenta553c252009-07-17 12:17:14 -07005659 return NO_ERROR;
5660}
5661
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005662status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Eric Laurenta553c252009-07-17 12:17:14 -07005663{
5664 Mutex::Autolock _l(mLock);
5665 MixerThread *dstThread = checkMixerThread_l(output);
5666 if (dstThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005667 ALOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005668 return BAD_VALUE;
5669 }
5670
Steve Block71f2cf12011-10-20 11:56:00 +01005671 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005672 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005673
Eric Laurent05ce0942011-08-30 10:18:54 -07005674 dstThread->setStreamValid(stream, true);
5675
Eric Laurenta553c252009-07-17 12:17:14 -07005676 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005677 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kasten7d3be3a2012-01-26 10:53:32 -08005678 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005679 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent05ce0942011-08-30 10:18:54 -07005680 srcThread->setStreamValid(stream, false);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005681 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005682 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005683 }
Eric Laurentd069f322009-09-01 05:56:26 -07005684
Eric Laurenta553c252009-07-17 12:17:14 -07005685 return NO_ERROR;
5686}
5687
Eric Laurent65b65452010-06-01 23:49:17 -07005688
5689int AudioFlinger::newAudioSessionId()
5690{
Eric Laurent464d5b32011-06-17 21:29:58 -07005691 return nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07005692}
5693
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005694void AudioFlinger::acquireAudioSessionId(int audioSession)
5695{
5696 Mutex::Autolock _l(mLock);
Glenn Kastend153b1f2012-02-03 11:10:26 -08005697 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005698 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten150d2382012-02-08 14:04:28 -08005699 size_t num = mAudioSessionRefs.size();
5700 for (size_t i = 0; i< num; i++) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005701 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten9a42ac92012-03-06 11:22:01 -08005702 if (ref->mSessionid == audioSession && ref->mPid == caller) {
5703 ref->mCnt++;
5704 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005705 return;
5706 }
5707 }
Glenn Kastendc3ac852012-01-25 15:28:08 -08005708 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5709 ALOGV(" added new entry for %d", audioSession);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005710}
5711
5712void AudioFlinger::releaseAudioSessionId(int audioSession)
5713{
5714 Mutex::Autolock _l(mLock);
Glenn Kastend153b1f2012-02-03 11:10:26 -08005715 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005716 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten150d2382012-02-08 14:04:28 -08005717 size_t num = mAudioSessionRefs.size();
5718 for (size_t i = 0; i< num; i++) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005719 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten9a42ac92012-03-06 11:22:01 -08005720 if (ref->mSessionid == audioSession && ref->mPid == caller) {
5721 ref->mCnt--;
5722 ALOGV(" decremented refcount to %d", ref->mCnt);
5723 if (ref->mCnt == 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005724 mAudioSessionRefs.removeAt(i);
5725 delete ref;
5726 purgeStaleEffects_l();
5727 }
5728 return;
5729 }
5730 }
Steve Block8564c8d2012-01-05 23:22:43 +00005731 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005732}
5733
5734void AudioFlinger::purgeStaleEffects_l() {
5735
Steve Block71f2cf12011-10-20 11:56:00 +01005736 ALOGV("purging stale effects");
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005737
5738 Vector< sp<EffectChain> > chains;
5739
5740 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5741 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5742 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5743 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen2255a1e2011-08-12 14:14:39 -07005744 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5745 chains.push(ec);
5746 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005747 }
5748 }
5749 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5750 sp<RecordThread> t = mRecordThreads.valueAt(i);
5751 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5752 sp<EffectChain> ec = t->mEffectChains[j];
5753 chains.push(ec);
5754 }
5755 }
5756
5757 for (size_t i = 0; i < chains.size(); i++) {
5758 sp<EffectChain> ec = chains[i];
5759 int sessionid = ec->sessionId();
5760 sp<ThreadBase> t = ec->mThread.promote();
5761 if (t == 0) {
5762 continue;
5763 }
5764 size_t numsessionrefs = mAudioSessionRefs.size();
5765 bool found = false;
5766 for (size_t k = 0; k < numsessionrefs; k++) {
5767 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten9a42ac92012-03-06 11:22:01 -08005768 if (ref->mSessionid == sessionid) {
Steve Block71f2cf12011-10-20 11:56:00 +01005769 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kasten9a42ac92012-03-06 11:22:01 -08005770 sessionid, ref->mPid, ref->mCnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005771 found = true;
5772 break;
5773 }
5774 }
5775 if (!found) {
5776 // remove all effects from the chain
5777 while (ec->mEffects.size()) {
5778 sp<EffectModule> effect = ec->mEffects[0];
5779 effect->unPin();
5780 Mutex::Autolock _l (t->mLock);
5781 t->removeEffect_l(effect);
5782 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5783 sp<EffectHandle> handle = effect->mHandles[j].promote();
5784 if (handle != 0) {
5785 handle->mEffect.clear();
Eric Laurent7fa1cee2011-10-19 11:44:54 -07005786 if (handle->mHasControl && handle->mEnabled) {
5787 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5788 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005789 }
5790 }
5791 AudioSystem::unregisterEffect(effect->id());
5792 }
5793 }
5794 }
5795 return;
5796}
5797
Eric Laurenta553c252009-07-17 12:17:14 -07005798// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005799AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005800{
Glenn Kasten7d3be3a2012-01-26 10:53:32 -08005801 return mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005802}
5803
5804// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005805AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005806{
5807 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kasten7d3be3a2012-01-26 10:53:32 -08005808 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07005809}
5810
5811// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005812AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Eric Laurenta553c252009-07-17 12:17:14 -07005813{
Glenn Kasten7d3be3a2012-01-26 10:53:32 -08005814 return mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005815}
5816
Eric Laurent464d5b32011-06-17 21:29:58 -07005817uint32_t AudioFlinger::nextUniqueId()
Eric Laurent65b65452010-06-01 23:49:17 -07005818{
Eric Laurent464d5b32011-06-17 21:29:58 -07005819 return android_atomic_inc(&mNextUniqueId);
Eric Laurent65b65452010-06-01 23:49:17 -07005820}
5821
Glenn Kasten0fccd352012-02-24 15:42:17 -08005822AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent464d5b32011-06-17 21:29:58 -07005823{
5824 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5825 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent828b9772011-08-07 16:32:26 -07005826 AudioStreamOut *output = thread->getOutput();
5827 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005828 return thread;
5829 }
5830 }
5831 return NULL;
5832}
5833
Glenn Kasten0fccd352012-02-24 15:42:17 -08005834uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent464d5b32011-06-17 21:29:58 -07005835{
5836 PlaybackThread *thread = primaryPlaybackThread_l();
5837
5838 if (thread == NULL) {
5839 return 0;
5840 }
5841
5842 return thread->device();
5843}
5844
5845
Eric Laurent65b65452010-06-01 23:49:17 -07005846// ----------------------------------------------------------------------------
5847// Effect management
5848// ----------------------------------------------------------------------------
5849
5850
Glenn Kasten3f6d83a2012-01-26 16:25:10 -08005851status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Eric Laurent65b65452010-06-01 23:49:17 -07005852{
5853 Mutex::Autolock _l(mLock);
5854 return EffectQueryNumberEffects(numEffects);
5855}
5856
Glenn Kasten3f6d83a2012-01-26 16:25:10 -08005857status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Eric Laurent65b65452010-06-01 23:49:17 -07005858{
5859 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005860 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07005861}
5862
Glenn Kasten67313332012-01-30 07:40:52 -08005863status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kasten3f6d83a2012-01-26 16:25:10 -08005864 effect_descriptor_t *descriptor) const
Eric Laurent65b65452010-06-01 23:49:17 -07005865{
5866 Mutex::Autolock _l(mLock);
5867 return EffectGetDescriptor(pUuid, descriptor);
5868}
5869
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005870
Eric Laurent65b65452010-06-01 23:49:17 -07005871sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5872 effect_descriptor_t *pDesc,
5873 const sp<IEffectClient>& effectClient,
5874 int32_t priority,
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005875 audio_io_handle_t io,
Eric Laurent65b65452010-06-01 23:49:17 -07005876 int sessionId,
5877 status_t *status,
5878 int *id,
5879 int *enabled)
5880{
5881 status_t lStatus = NO_ERROR;
5882 sp<EffectHandle> handle;
Eric Laurent65b65452010-06-01 23:49:17 -07005883 effect_descriptor_t desc;
Eric Laurent65b65452010-06-01 23:49:17 -07005884
Glenn Kasten803a86a2012-01-25 14:28:29 -08005885 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent464d5b32011-06-17 21:29:58 -07005886 pid, effectClient.get(), priority, sessionId, io);
Eric Laurent65b65452010-06-01 23:49:17 -07005887
5888 if (pDesc == NULL) {
5889 lStatus = BAD_VALUE;
5890 goto Exit;
5891 }
5892
Eric Laurent98c92592010-09-23 16:10:16 -07005893 // check audio settings permission for global effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005894 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent98c92592010-09-23 16:10:16 -07005895 lStatus = PERMISSION_DENIED;
5896 goto Exit;
5897 }
5898
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005899 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent98c92592010-09-23 16:10:16 -07005900 // that can only be created by audio policy manager (running in same process)
Glenn Kasten81211142012-02-05 18:09:08 -08005901 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent98c92592010-09-23 16:10:16 -07005902 lStatus = PERMISSION_DENIED;
5903 goto Exit;
5904 }
5905
Eric Laurent464d5b32011-06-17 21:29:58 -07005906 if (io == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005907 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent98c92592010-09-23 16:10:16 -07005908 // output must be specified by AudioPolicyManager when using session
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005909 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent98c92592010-09-23 16:10:16 -07005910 lStatus = BAD_VALUE;
5911 goto Exit;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005912 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent98c92592010-09-23 16:10:16 -07005913 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent464d5b32011-06-17 21:29:58 -07005914 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent98c92592010-09-23 16:10:16 -07005915 // and we will exit safely
Eric Laurent464d5b32011-06-17 21:29:58 -07005916 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent98c92592010-09-23 16:10:16 -07005917 }
5918 }
5919
Eric Laurent65b65452010-06-01 23:49:17 -07005920 {
5921 Mutex::Autolock _l(mLock);
5922
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005923
Eric Laurent65b65452010-06-01 23:49:17 -07005924 if (!EffectIsNullUuid(&pDesc->uuid)) {
5925 // if uuid is specified, request effect descriptor
5926 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5927 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005928 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005929 goto Exit;
5930 }
5931 } else {
5932 // if uuid is not specified, look for an available implementation
5933 // of the required type in effect factory
5934 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block8564c8d2012-01-05 23:22:43 +00005935 ALOGW("createEffect() no effect type");
Eric Laurent65b65452010-06-01 23:49:17 -07005936 lStatus = BAD_VALUE;
5937 goto Exit;
5938 }
5939 uint32_t numEffects = 0;
5940 effect_descriptor_t d;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005941 d.flags = 0; // prevent compiler warning
Eric Laurent65b65452010-06-01 23:49:17 -07005942 bool found = false;
5943
5944 lStatus = EffectQueryNumberEffects(&numEffects);
5945 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005946 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005947 goto Exit;
5948 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005949 for (uint32_t i = 0; i < numEffects; i++) {
5950 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005951 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005952 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005953 continue;
5954 }
5955 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5956 // If matching type found save effect descriptor. If the session is
5957 // 0 and the effect is not auxiliary, continue enumeration in case
5958 // an auxiliary version of this effect type is available
5959 found = true;
5960 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005961 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07005962 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5963 break;
5964 }
5965 }
5966 }
5967 if (!found) {
5968 lStatus = BAD_VALUE;
Steve Block8564c8d2012-01-05 23:22:43 +00005969 ALOGW("createEffect() effect not found");
Eric Laurent65b65452010-06-01 23:49:17 -07005970 goto Exit;
5971 }
5972 // For same effect type, chose auxiliary version over insert version if
5973 // connect to output mix (Compliance to OpenSL ES)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005974 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005975 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5976 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5977 }
5978 }
5979
5980 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005981 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005982 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5983 lStatus = INVALID_OPERATION;
5984 goto Exit;
5985 }
5986
Eric Laurentf82fccd2011-07-27 19:49:51 -07005987 // check recording permission for visualizer
5988 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5989 !recordingAllowed()) {
5990 lStatus = PERMISSION_DENIED;
5991 goto Exit;
5992 }
5993
Eric Laurent65b65452010-06-01 23:49:17 -07005994 // return effect descriptor
5995 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5996
5997 // If output is not specified try to find a matching audio session ID in one of the
5998 // output threads.
Eric Laurent98c92592010-09-23 16:10:16 -07005999 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
6000 // because of code checking output when entering the function.
Eric Laurent464d5b32011-06-17 21:29:58 -07006001 // Note: io is never 0 when creating an effect on an input
6002 if (io == 0) {
Eric Laurent98c92592010-09-23 16:10:16 -07006003 // look for the thread where the specified audio session is present
6004 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6005 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07006006 io = mPlaybackThreads.keyAt(i);
Eric Laurent98c92592010-09-23 16:10:16 -07006007 break;
Eric Laurent493941b2010-07-28 01:32:47 -07006008 }
Eric Laurent65b65452010-06-01 23:49:17 -07006009 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006010 if (io == 0) {
6011 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6012 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6013 io = mRecordThreads.keyAt(i);
6014 break;
6015 }
6016 }
6017 }
Eric Laurent98c92592010-09-23 16:10:16 -07006018 // If no output thread contains the requested session ID, default to
6019 // first output. The effect chain will be moved to the correct output
6020 // thread when a track with the same session ID is created
Eric Laurent464d5b32011-06-17 21:29:58 -07006021 if (io == 0 && mPlaybackThreads.size()) {
6022 io = mPlaybackThreads.keyAt(0);
6023 }
Steve Block71f2cf12011-10-20 11:56:00 +01006024 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent464d5b32011-06-17 21:29:58 -07006025 }
6026 ThreadBase *thread = checkRecordThread_l(io);
6027 if (thread == NULL) {
6028 thread = checkPlaybackThread_l(io);
6029 if (thread == NULL) {
Steve Block3762c312012-01-06 19:20:56 +00006030 ALOGE("createEffect() unknown output thread");
Eric Laurent464d5b32011-06-17 21:29:58 -07006031 lStatus = BAD_VALUE;
6032 goto Exit;
Eric Laurent98c92592010-09-23 16:10:16 -07006033 }
Eric Laurent65b65452010-06-01 23:49:17 -07006034 }
Eric Laurent98c92592010-09-23 16:10:16 -07006035
Glenn Kasten803a86a2012-01-25 14:28:29 -08006036 sp<Client> client = registerPid_l(pid);
Eric Laurent65b65452010-06-01 23:49:17 -07006037
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006038 // create effect on selected output thread
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006039 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6040 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006041 if (handle != 0 && id != NULL) {
6042 *id = handle->id();
6043 }
6044 }
6045
6046Exit:
6047 if(status) {
6048 *status = lStatus;
6049 }
6050 return handle;
6051}
6052
Glenn Kasten39d00cb2012-01-17 11:09:42 -08006053status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
6054 audio_io_handle_t dstOutput)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006055{
Steve Block71f2cf12011-10-20 11:56:00 +01006056 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07006057 sessionId, srcOutput, dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006058 Mutex::Autolock _l(mLock);
6059 if (srcOutput == dstOutput) {
Steve Block8564c8d2012-01-05 23:22:43 +00006060 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006061 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07006062 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006063 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6064 if (srcThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00006065 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006066 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07006067 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006068 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6069 if (dstThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00006070 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006071 return BAD_VALUE;
6072 }
6073
6074 Mutex::Autolock _dl(dstThread->mLock);
6075 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006076 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006077
Eric Laurent53334cd2010-06-23 17:38:20 -07006078 return NO_ERROR;
6079}
6080
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006081// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurentf82fccd2011-07-27 19:49:51 -07006082status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006083 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent493941b2010-07-28 01:32:47 -07006084 AudioFlinger::PlaybackThread *dstThread,
6085 bool reRegister)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006086{
Steve Block71f2cf12011-10-20 11:56:00 +01006087 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07006088 sessionId, srcThread, dstThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006089
Eric Laurentf82fccd2011-07-27 19:49:51 -07006090 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006091 if (chain == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00006092 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07006093 sessionId, srcThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006094 return INVALID_OPERATION;
6095 }
6096
Eric Laurent493941b2010-07-28 01:32:47 -07006097 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006098 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurent6fccbd02011-10-05 17:42:25 -07006099 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006100 // removed.
6101 srcThread->removeEffectChain_l(chain);
6102
6103 // transfer all effects one by one so that new effect chain is created on new thread with
6104 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten39d00cb2012-01-17 11:09:42 -08006105 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent493941b2010-07-28 01:32:47 -07006106 sp<EffectChain> dstChain;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006107 uint32_t strategy = 0; // prevent compiler warning
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006108 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6109 while (effect != 0) {
6110 srcThread->removeEffect_l(effect);
6111 dstThread->addEffect_l(effect);
Eric Laurent6fccbd02011-10-05 17:42:25 -07006112 // removeEffect_l() has stopped the effect if it was active so it must be restarted
6113 if (effect->state() == EffectModule::ACTIVE ||
6114 effect->state() == EffectModule::STOPPING) {
6115 effect->start();
6116 }
Eric Laurent493941b2010-07-28 01:32:47 -07006117 // if the move request is not received from audio policy manager, the effect must be
6118 // re-registered with the new strategy and output
6119 if (dstChain == 0) {
6120 dstChain = effect->chain().promote();
6121 if (dstChain == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00006122 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent493941b2010-07-28 01:32:47 -07006123 srcThread->addEffect_l(effect);
6124 return NO_INIT;
6125 }
6126 strategy = dstChain->strategy();
6127 }
6128 if (reRegister) {
6129 AudioSystem::unregisterEffect(effect->id());
6130 AudioSystem::registerEffect(&effect->desc(),
6131 dstOutput,
6132 strategy,
Eric Laurentf82fccd2011-07-27 19:49:51 -07006133 sessionId,
Eric Laurent493941b2010-07-28 01:32:47 -07006134 effect->id());
6135 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006136 effect = chain->getEffectFromId_l(0);
6137 }
6138
6139 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07006140}
6141
Eric Laurent464d5b32011-06-17 21:29:58 -07006142
Eric Laurent65b65452010-06-01 23:49:17 -07006143// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07006144sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Eric Laurent65b65452010-06-01 23:49:17 -07006145 const sp<AudioFlinger::Client>& client,
6146 const sp<IEffectClient>& effectClient,
6147 int32_t priority,
6148 int sessionId,
6149 effect_descriptor_t *desc,
6150 int *enabled,
6151 status_t *status
6152 )
6153{
6154 sp<EffectModule> effect;
6155 sp<EffectHandle> handle;
6156 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -07006157 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006158 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07006159 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07006160 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07006161
Eric Laurent464d5b32011-06-17 21:29:58 -07006162 lStatus = initCheck();
6163 if (lStatus != NO_ERROR) {
Steve Block8564c8d2012-01-05 23:22:43 +00006164 ALOGW("createEffect_l() Audio driver not initialized.");
Eric Laurent65b65452010-06-01 23:49:17 -07006165 goto Exit;
6166 }
6167
6168 // Do not allow effects with session ID 0 on direct output or duplicating threads
6169 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006170 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block8564c8d2012-01-05 23:22:43 +00006171 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006172 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07006173 lStatus = BAD_VALUE;
6174 goto Exit;
6175 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006176 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kasten7d3be3a2012-01-26 10:53:32 -08006177 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block8564c8d2012-01-05 23:22:43 +00006178 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent464d5b32011-06-17 21:29:58 -07006179 desc->name, desc->flags, mType);
6180 lStatus = BAD_VALUE;
6181 goto Exit;
6182 }
Eric Laurent65b65452010-06-01 23:49:17 -07006183
Steve Block71f2cf12011-10-20 11:56:00 +01006184 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07006185
6186 { // scope for mLock
6187 Mutex::Autolock _l(mLock);
6188
6189 // check for existing effect chain with the requested audio session
6190 chain = getEffectChain_l(sessionId);
6191 if (chain == 0) {
6192 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01006193 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07006194 chain = new EffectChain(this, sessionId);
6195 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006196 chain->setStrategy(getStrategyForSession_l(sessionId));
6197 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07006198 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07006199 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07006200 }
6201
Glenn Kasten70ed6b72012-01-10 10:46:34 -08006202 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Eric Laurent65b65452010-06-01 23:49:17 -07006203
6204 if (effect == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07006205 int id = mAudioFlinger->nextUniqueId();
Eric Laurent53334cd2010-06-23 17:38:20 -07006206 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006207 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07006208 if (lStatus != NO_ERROR) {
6209 goto Exit;
6210 }
6211 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07006212 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006213 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07006214 lStatus = effect->status();
6215 if (lStatus != NO_ERROR) {
6216 goto Exit;
6217 }
Eric Laurent76c40f72010-07-15 12:50:15 -07006218 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07006219 if (lStatus != NO_ERROR) {
6220 goto Exit;
6221 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006222 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07006223
6224 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07006225 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07006226 }
6227 // create effect handle and connect it to effect module
6228 handle = new EffectHandle(effect, client, effectClient, priority);
6229 lStatus = effect->addHandle(handle);
Glenn Kasten3694ec12012-01-27 16:47:15 -08006230 if (enabled != NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006231 *enabled = (int)effect->isEnabled();
6232 }
6233 }
6234
6235Exit:
6236 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006237 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07006238 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006239 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07006240 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006241 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006242 AudioSystem::unregisterEffect(effect->id());
6243 }
6244 if (chainCreated) {
6245 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07006246 }
Eric Laurent65b65452010-06-01 23:49:17 -07006247 handle.clear();
6248 }
6249
6250 if(status) {
6251 *status = lStatus;
6252 }
6253 return handle;
6254}
6255
Eric Laurent464d5b32011-06-17 21:29:58 -07006256sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6257{
Eric Laurent464d5b32011-06-17 21:29:58 -07006258 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kastenc64a6f02012-01-30 13:00:02 -08006259 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent464d5b32011-06-17 21:29:58 -07006260}
6261
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006262// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6263// PlaybackThread::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07006264status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006265{
6266 // check for existing effect chain with the requested audio session
6267 int sessionId = effect->sessionId();
6268 sp<EffectChain> chain = getEffectChain_l(sessionId);
6269 bool chainCreated = false;
6270
6271 if (chain == 0) {
6272 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01006273 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006274 chain = new EffectChain(this, sessionId);
6275 addEffectChain_l(chain);
6276 chain->setStrategy(getStrategyForSession_l(sessionId));
6277 chainCreated = true;
6278 }
Steve Block71f2cf12011-10-20 11:56:00 +01006279 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006280
6281 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00006282 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006283 this, effect->desc().name, chain.get());
6284 return BAD_VALUE;
6285 }
6286
6287 status_t status = chain->addEffect_l(effect);
6288 if (status != NO_ERROR) {
6289 if (chainCreated) {
6290 removeEffectChain_l(chain);
6291 }
6292 return status;
6293 }
6294
6295 effect->setDevice(mDevice);
6296 effect->setMode(mAudioFlinger->getMode());
6297 return NO_ERROR;
6298}
6299
Eric Laurent464d5b32011-06-17 21:29:58 -07006300void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006301
Steve Block71f2cf12011-10-20 11:56:00 +01006302 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07006303 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006304 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6305 detachAuxEffect_l(effect->id());
6306 }
6307
6308 sp<EffectChain> chain = effect->chain().promote();
6309 if (chain != 0) {
6310 // remove effect chain if removing last effect
6311 if (chain->removeEffect_l(effect) == 0) {
6312 removeEffectChain_l(chain);
6313 }
6314 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00006315 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006316 }
6317}
6318
Eric Laurent464d5b32011-06-17 21:29:58 -07006319void AudioFlinger::ThreadBase::lockEffectChains_l(
6320 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
6321{
6322 effectChains = mEffectChains;
6323 for (size_t i = 0; i < mEffectChains.size(); i++) {
6324 mEffectChains[i]->lock();
6325 }
6326}
6327
6328void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kasten0fccd352012-02-24 15:42:17 -08006329 const Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Eric Laurent464d5b32011-06-17 21:29:58 -07006330{
6331 for (size_t i = 0; i < effectChains.size(); i++) {
6332 effectChains[i]->unlock();
6333 }
6334}
6335
6336sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6337{
6338 Mutex::Autolock _l(mLock);
6339 return getEffectChain_l(sessionId);
6340}
6341
6342sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6343{
Eric Laurent464d5b32011-06-17 21:29:58 -07006344 size_t size = mEffectChains.size();
6345 for (size_t i = 0; i < size; i++) {
6346 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kastenc64a6f02012-01-30 13:00:02 -08006347 return mEffectChains[i];
Eric Laurent464d5b32011-06-17 21:29:58 -07006348 }
6349 }
Glenn Kastenc64a6f02012-01-30 13:00:02 -08006350 return 0;
Eric Laurent464d5b32011-06-17 21:29:58 -07006351}
6352
Glenn Kastenaccb1142012-01-04 11:00:47 -08006353void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent464d5b32011-06-17 21:29:58 -07006354{
6355 Mutex::Autolock _l(mLock);
6356 size_t size = mEffectChains.size();
6357 for (size_t i = 0; i < size; i++) {
6358 mEffectChains[i]->setMode_l(mode);
6359 }
6360}
6361
6362void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006363 const wp<EffectHandle>& handle,
Glenn Kasten29441ff2012-02-03 10:32:24 -08006364 bool unpinIfLast) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006365
Eric Laurent53334cd2010-06-23 17:38:20 -07006366 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006367 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07006368 // delete the effect module if removing last handle on it
6369 if (effect->removeHandle(handle) == 0) {
Glenn Kasten29441ff2012-02-03 10:32:24 -08006370 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006371 removeEffect_l(effect);
6372 AudioSystem::unregisterEffect(effect->id());
6373 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006374 }
6375}
6376
Eric Laurent65b65452010-06-01 23:49:17 -07006377status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6378{
6379 int session = chain->sessionId();
6380 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07006381 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07006382
Steve Block71f2cf12011-10-20 11:56:00 +01006383 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07006384 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07006385 // Only one effect chain can be present in direct output thread and it uses
6386 // the mix buffer as input
6387 if (mType != DIRECT) {
6388 size_t numSamples = mFrameCount * mChannelCount;
6389 buffer = new int16_t[numSamples];
6390 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block71f2cf12011-10-20 11:56:00 +01006391 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Eric Laurent65b65452010-06-01 23:49:17 -07006392 ownsBuffer = true;
6393 }
Eric Laurent65b65452010-06-01 23:49:17 -07006394
Eric Laurent53334cd2010-06-23 17:38:20 -07006395 // Attach all tracks with same session ID to this chain.
6396 for (size_t i = 0; i < mTracks.size(); ++i) {
6397 sp<Track> track = mTracks[i];
6398 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01006399 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Eric Laurent53334cd2010-06-23 17:38:20 -07006400 track->setMainBuffer(buffer);
Eric Laurent90681d62011-05-09 12:09:06 -07006401 chain->incTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07006402 }
6403 }
6404
6405 // indicate all active tracks in the chain
6406 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6407 sp<Track> track = mActiveTracks[i].promote();
6408 if (track == 0) continue;
6409 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01006410 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurent90681d62011-05-09 12:09:06 -07006411 chain->incActiveTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07006412 }
Eric Laurent65b65452010-06-01 23:49:17 -07006413 }
6414 }
6415
Eric Laurent53334cd2010-06-23 17:38:20 -07006416 chain->setInBuffer(buffer, ownsBuffer);
6417 chain->setOutBuffer(mMixBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006418 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006419 // chains list in order to be processed last as it contains output stage effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006420 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6421 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07006422 // after track specific effects and before output stage
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006423 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6424 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006425 // Effect chain for other sessions are inserted at beginning of effect
6426 // chains list to be processed before output mix effects. Relative order between other
6427 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07006428 size_t size = mEffectChains.size();
6429 size_t i = 0;
6430 for (i = 0; i < size; i++) {
6431 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07006432 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006433 mEffectChains.insertAt(chain, i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006434 checkSuspendOnAddEffectChain_l(chain);
Eric Laurent65b65452010-06-01 23:49:17 -07006435
6436 return NO_ERROR;
6437}
6438
6439size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6440{
6441 int session = chain->sessionId();
6442
Steve Block71f2cf12011-10-20 11:56:00 +01006443 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Eric Laurent65b65452010-06-01 23:49:17 -07006444
6445 for (size_t i = 0; i < mEffectChains.size(); i++) {
6446 if (chain == mEffectChains[i]) {
6447 mEffectChains.removeAt(i);
Eric Laurent90681d62011-05-09 12:09:06 -07006448 // detach all active tracks from the chain
6449 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6450 sp<Track> track = mActiveTracks[i].promote();
6451 if (track == 0) continue;
6452 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01006453 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurent90681d62011-05-09 12:09:06 -07006454 chain.get(), session);
6455 chain->decActiveTrackCnt();
6456 }
6457 }
6458
Eric Laurent65b65452010-06-01 23:49:17 -07006459 // detach all tracks with same session ID from this chain
6460 for (size_t i = 0; i < mTracks.size(); ++i) {
6461 sp<Track> track = mTracks[i];
6462 if (session == track->sessionId()) {
6463 track->setMainBuffer(mMixBuffer);
Eric Laurent90681d62011-05-09 12:09:06 -07006464 chain->decTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07006465 }
6466 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006467 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006468 }
6469 }
6470 return mEffectChains.size();
6471}
6472
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006473status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6474 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07006475{
6476 Mutex::Autolock _l(mLock);
6477 return attachAuxEffect_l(track, EffectId);
6478}
6479
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006480status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6481 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07006482{
6483 status_t status = NO_ERROR;
6484
6485 if (EffectId == 0) {
6486 track->setAuxBuffer(0, NULL);
6487 } else {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006488 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6489 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07006490 if (effect != 0) {
6491 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6492 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6493 } else {
6494 status = INVALID_OPERATION;
6495 }
6496 } else {
6497 status = BAD_VALUE;
6498 }
6499 }
6500 return status;
6501}
6502
6503void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6504{
6505 for (size_t i = 0; i < mTracks.size(); ++i) {
6506 sp<Track> track = mTracks[i];
6507 if (track->auxEffectId() == effectId) {
6508 attachAuxEffect_l(track, 0);
6509 }
6510 }
6511}
6512
Eric Laurent464d5b32011-06-17 21:29:58 -07006513status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6514{
6515 // only one chain per input thread
6516 if (mEffectChains.size() != 0) {
6517 return INVALID_OPERATION;
6518 }
Steve Block71f2cf12011-10-20 11:56:00 +01006519 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent464d5b32011-06-17 21:29:58 -07006520
6521 chain->setInBuffer(NULL);
6522 chain->setOutBuffer(NULL);
6523
Eric Laurentf82fccd2011-07-27 19:49:51 -07006524 checkSuspendOnAddEffectChain_l(chain);
6525
Eric Laurent464d5b32011-06-17 21:29:58 -07006526 mEffectChains.add(chain);
6527
6528 return NO_ERROR;
6529}
6530
6531size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6532{
Steve Block71f2cf12011-10-20 11:56:00 +01006533 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block8564c8d2012-01-05 23:22:43 +00006534 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent464d5b32011-06-17 21:29:58 -07006535 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6536 chain.get(), mEffectChains.size(), this);
6537 if (mEffectChains.size() == 1) {
6538 mEffectChains.removeAt(0);
6539 }
6540 return 0;
6541}
6542
Eric Laurent65b65452010-06-01 23:49:17 -07006543// ----------------------------------------------------------------------------
6544// EffectModule implementation
6545// ----------------------------------------------------------------------------
6546
6547#undef LOG_TAG
6548#define LOG_TAG "AudioFlinger::EffectModule"
6549
Glenn Kasten685c9ce2012-01-20 13:32:16 -08006550AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Eric Laurent65b65452010-06-01 23:49:17 -07006551 const wp<AudioFlinger::EffectChain>& chain,
6552 effect_descriptor_t *desc,
6553 int id,
6554 int sessionId)
Glenn Kasten685c9ce2012-01-20 13:32:16 -08006555 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006556 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006557{
Steve Block71f2cf12011-10-20 11:56:00 +01006558 ALOGV("Constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006559 int lStatus;
Glenn Kasten685c9ce2012-01-20 13:32:16 -08006560 if (thread == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006561 return;
6562 }
Eric Laurent65b65452010-06-01 23:49:17 -07006563
6564 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6565
6566 // create effect engine from effect factory
Eric Laurent464d5b32011-06-17 21:29:58 -07006567 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Eric Laurent53334cd2010-06-23 17:38:20 -07006568
Eric Laurent65b65452010-06-01 23:49:17 -07006569 if (mStatus != NO_ERROR) {
6570 return;
6571 }
6572 lStatus = init();
6573 if (lStatus < 0) {
6574 mStatus = lStatus;
6575 goto Error;
6576 }
6577
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006578 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6579 mPinned = true;
6580 }
Steve Block71f2cf12011-10-20 11:56:00 +01006581 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006582 return;
6583Error:
6584 EffectRelease(mEffectInterface);
6585 mEffectInterface = NULL;
Steve Block71f2cf12011-10-20 11:56:00 +01006586 ALOGV("Constructor Error %d", mStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006587}
6588
6589AudioFlinger::EffectModule::~EffectModule()
6590{
Steve Block71f2cf12011-10-20 11:56:00 +01006591 ALOGV("Destructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006592 if (mEffectInterface != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07006593 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6594 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6595 sp<ThreadBase> thread = mThread.promote();
6596 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006597 audio_stream_t *stream = thread->stream();
6598 if (stream != NULL) {
6599 stream->remove_audio_effect(stream, mEffectInterface);
6600 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006601 }
6602 }
Eric Laurent65b65452010-06-01 23:49:17 -07006603 // release effect engine
6604 EffectRelease(mEffectInterface);
6605 }
6606}
6607
Glenn Kasten1f812f72012-01-30 10:15:48 -08006608status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Eric Laurent65b65452010-06-01 23:49:17 -07006609{
6610 status_t status;
6611
6612 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006613 int priority = handle->priority();
6614 size_t size = mHandles.size();
6615 sp<EffectHandle> h;
6616 size_t i;
6617 for (i = 0; i < size; i++) {
6618 h = mHandles[i].promote();
6619 if (h == 0) continue;
6620 if (h->priority() <= priority) break;
6621 }
6622 // if inserted in first place, move effect control from previous owner to this handle
6623 if (i == 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006624 bool enabled = false;
Eric Laurent65b65452010-06-01 23:49:17 -07006625 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006626 enabled = h->enabled();
6627 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006628 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006629 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006630 status = NO_ERROR;
6631 } else {
6632 status = ALREADY_EXISTS;
6633 }
Steve Block71f2cf12011-10-20 11:56:00 +01006634 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Eric Laurent65b65452010-06-01 23:49:17 -07006635 mHandles.insertAt(handle, i);
6636 return status;
6637}
6638
6639size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6640{
6641 Mutex::Autolock _l(mLock);
6642 size_t size = mHandles.size();
6643 size_t i;
6644 for (i = 0; i < size; i++) {
6645 if (mHandles[i] == handle) break;
6646 }
6647 if (i == size) {
6648 return size;
6649 }
Steve Block71f2cf12011-10-20 11:56:00 +01006650 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006651
6652 bool enabled = false;
6653 EffectHandle *hdl = handle.unsafe_get();
Glenn Kasten3694ec12012-01-27 16:47:15 -08006654 if (hdl != NULL) {
Steve Block71f2cf12011-10-20 11:56:00 +01006655 ALOGV("removeHandle() unsafe_get OK");
Eric Laurentf82fccd2011-07-27 19:49:51 -07006656 enabled = hdl->enabled();
6657 }
Eric Laurent65b65452010-06-01 23:49:17 -07006658 mHandles.removeAt(i);
6659 size = mHandles.size();
6660 // if removed from first place, move effect control from this handle to next in line
6661 if (i == 0 && size != 0) {
6662 sp<EffectHandle> h = mHandles[0].promote();
6663 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006664 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006665 }
6666 }
6667
Eric Laurent21b5c472011-07-26 20:54:46 -07006668 // Prevent calls to process() and other functions on effect interface from now on.
6669 // The effect engine will be released by the destructor when the last strong reference on
6670 // this object is released which can happen after next process is called.
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006671 if (size == 0 && !mPinned) {
Eric Laurent21b5c472011-07-26 20:54:46 -07006672 mState = DESTROYED;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006673 }
6674
Eric Laurent65b65452010-06-01 23:49:17 -07006675 return size;
6676}
6677
Eric Laurentf82fccd2011-07-27 19:49:51 -07006678sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6679{
6680 Mutex::Autolock _l(mLock);
Glenn Kastenc64a6f02012-01-30 13:00:02 -08006681 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurentf82fccd2011-07-27 19:49:51 -07006682}
6683
Glenn Kasten29441ff2012-02-03 10:32:24 -08006684void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Eric Laurent65b65452010-06-01 23:49:17 -07006685{
Glenn Kasten0765c442012-01-27 15:24:38 -08006686 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Eric Laurent65b65452010-06-01 23:49:17 -07006687 // keep a strong reference on this EffectModule to avoid calling the
6688 // destructor before we exit
6689 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07006690 {
6691 sp<ThreadBase> thread = mThread.promote();
6692 if (thread != 0) {
Glenn Kasten29441ff2012-02-03 10:32:24 -08006693 thread->disconnectEffect(keep, handle, unpinIfLast);
Eric Laurent65b65452010-06-01 23:49:17 -07006694 }
6695 }
6696}
6697
Eric Laurent7d850f22010-07-09 13:34:17 -07006698void AudioFlinger::EffectModule::updateState() {
6699 Mutex::Autolock _l(mLock);
6700
6701 switch (mState) {
6702 case RESTART:
6703 reset_l();
6704 // FALL THROUGH
6705
6706 case STARTING:
6707 // clear auxiliary effect input buffer for next accumulation
6708 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6709 memset(mConfig.inputCfg.buffer.raw,
6710 0,
6711 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6712 }
6713 start_l();
6714 mState = ACTIVE;
6715 break;
6716 case STOPPING:
6717 stop_l();
6718 mDisableWaitCnt = mMaxDisableWaitCnt;
6719 mState = STOPPED;
6720 break;
6721 case STOPPED:
6722 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6723 // turn off sequence.
6724 if (--mDisableWaitCnt == 0) {
6725 reset_l();
6726 mState = IDLE;
6727 }
6728 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006729 default: //IDLE , ACTIVE, DESTROYED
Eric Laurent7d850f22010-07-09 13:34:17 -07006730 break;
6731 }
6732}
6733
Eric Laurent65b65452010-06-01 23:49:17 -07006734void AudioFlinger::EffectModule::process()
6735{
6736 Mutex::Autolock _l(mLock);
6737
Eric Laurent21b5c472011-07-26 20:54:46 -07006738 if (mState == DESTROYED || mEffectInterface == NULL ||
Eric Laurent7d850f22010-07-09 13:34:17 -07006739 mConfig.inputCfg.buffer.raw == NULL ||
6740 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006741 return;
6742 }
6743
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006744 if (isProcessEnabled()) {
Eric Laurent65b65452010-06-01 23:49:17 -07006745 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6746 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten490909d2011-12-15 09:52:39 -08006747 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Eric Laurent65b65452010-06-01 23:49:17 -07006748 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006749 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07006750 }
6751
Eric Laurent65b65452010-06-01 23:49:17 -07006752 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07006753 int ret = (*mEffectInterface)->process(mEffectInterface,
6754 &mConfig.inputCfg.buffer,
6755 &mConfig.outputCfg.buffer);
6756
6757 // force transition to IDLE state when engine is ready
6758 if (mState == STOPPED && ret == -ENODATA) {
6759 mDisableWaitCnt = 1;
6760 }
Eric Laurent65b65452010-06-01 23:49:17 -07006761
6762 // clear auxiliary effect input buffer for next accumulation
6763 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006764 memset(mConfig.inputCfg.buffer.raw, 0,
6765 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006766 }
6767 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent67b5ed32011-01-19 18:36:13 -08006768 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6769 // If an insert effect is idle and input buffer is different from output buffer,
6770 // accumulate input onto output
Eric Laurent65b65452010-06-01 23:49:17 -07006771 sp<EffectChain> chain = mChain.promote();
Eric Laurent90681d62011-05-09 12:09:06 -07006772 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006773 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6774 int16_t *in = mConfig.inputCfg.buffer.s16;
6775 int16_t *out = mConfig.outputCfg.buffer.s16;
6776 for (size_t i = 0; i < frameCnt; i++) {
6777 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Eric Laurent65b65452010-06-01 23:49:17 -07006778 }
Eric Laurent65b65452010-06-01 23:49:17 -07006779 }
6780 }
6781}
6782
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006783void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006784{
6785 if (mEffectInterface == NULL) {
6786 return;
6787 }
6788 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6789}
6790
6791status_t AudioFlinger::EffectModule::configure()
6792{
6793 uint32_t channels;
6794 if (mEffectInterface == NULL) {
6795 return NO_INIT;
6796 }
6797
6798 sp<ThreadBase> thread = mThread.promote();
6799 if (thread == 0) {
6800 return DEAD_OBJECT;
6801 }
6802
6803 // TODO: handle configuration of effects replacing track process
6804 if (thread->channelCount() == 1) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006805 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006806 } else {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006807 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurent65b65452010-06-01 23:49:17 -07006808 }
6809
6810 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006811 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006812 } else {
6813 mConfig.inputCfg.channels = channels;
6814 }
6815 mConfig.outputCfg.channels = channels;
Eric Laurent0fb66c22011-05-17 19:16:02 -07006816 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6817 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurent65b65452010-06-01 23:49:17 -07006818 mConfig.inputCfg.samplingRate = thread->sampleRate();
6819 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6820 mConfig.inputCfg.bufferProvider.cookie = NULL;
6821 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6822 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6823 mConfig.outputCfg.bufferProvider.cookie = NULL;
6824 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6825 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6826 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6827 // Insert effect:
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006828 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006829 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07006830 // - in other sessions:
6831 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6832 // other effect: overwrites output buffer: input buffer == output buffer
6833 // Auxiliary effect:
6834 // accumulates in output buffer: input buffer != output buffer
6835 // Therefore: accumulate <=> input buffer != output buffer
6836 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6837 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6838 } else {
6839 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6840 }
6841 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6842 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6843 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6844 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6845
Steve Block71f2cf12011-10-20 11:56:00 +01006846 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006847 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6848
Eric Laurent65b65452010-06-01 23:49:17 -07006849 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006850 uint32_t size = sizeof(int);
6851 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent4abf8822011-12-16 15:30:36 -08006852 EFFECT_CMD_SET_CONFIG,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006853 sizeof(effect_config_t),
6854 &mConfig,
6855 &size,
6856 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006857 if (status == 0) {
6858 status = cmdStatus;
6859 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006860
6861 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6862 (1000 * mConfig.outputCfg.buffer.frameCount);
6863
Eric Laurent65b65452010-06-01 23:49:17 -07006864 return status;
6865}
6866
6867status_t AudioFlinger::EffectModule::init()
6868{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006869 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006870 if (mEffectInterface == NULL) {
6871 return NO_INIT;
6872 }
6873 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006874 uint32_t size = sizeof(status_t);
6875 status_t status = (*mEffectInterface)->command(mEffectInterface,
6876 EFFECT_CMD_INIT,
6877 0,
6878 NULL,
6879 &size,
6880 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006881 if (status == 0) {
6882 status = cmdStatus;
6883 }
6884 return status;
6885}
6886
Eric Laurent6fccbd02011-10-05 17:42:25 -07006887status_t AudioFlinger::EffectModule::start()
6888{
6889 Mutex::Autolock _l(mLock);
6890 return start_l();
6891}
6892
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006893status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006894{
6895 if (mEffectInterface == NULL) {
6896 return NO_INIT;
6897 }
6898 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006899 uint32_t size = sizeof(status_t);
6900 status_t status = (*mEffectInterface)->command(mEffectInterface,
6901 EFFECT_CMD_ENABLE,
6902 0,
6903 NULL,
6904 &size,
6905 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006906 if (status == 0) {
6907 status = cmdStatus;
6908 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006909 if (status == 0 &&
6910 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6911 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6912 sp<ThreadBase> thread = mThread.promote();
6913 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006914 audio_stream_t *stream = thread->stream();
6915 if (stream != NULL) {
6916 stream->add_audio_effect(stream, mEffectInterface);
6917 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006918 }
6919 }
Eric Laurent65b65452010-06-01 23:49:17 -07006920 return status;
6921}
6922
Eric Laurent21b5c472011-07-26 20:54:46 -07006923status_t AudioFlinger::EffectModule::stop()
6924{
6925 Mutex::Autolock _l(mLock);
6926 return stop_l();
6927}
6928
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006929status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006930{
6931 if (mEffectInterface == NULL) {
6932 return NO_INIT;
6933 }
6934 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006935 uint32_t size = sizeof(status_t);
6936 status_t status = (*mEffectInterface)->command(mEffectInterface,
6937 EFFECT_CMD_DISABLE,
6938 0,
6939 NULL,
6940 &size,
6941 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006942 if (status == 0) {
6943 status = cmdStatus;
6944 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006945 if (status == 0 &&
6946 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6947 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6948 sp<ThreadBase> thread = mThread.promote();
6949 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006950 audio_stream_t *stream = thread->stream();
6951 if (stream != NULL) {
6952 stream->remove_audio_effect(stream, mEffectInterface);
6953 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006954 }
6955 }
Eric Laurent65b65452010-06-01 23:49:17 -07006956 return status;
6957}
6958
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006959status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6960 uint32_t cmdSize,
6961 void *pCmdData,
6962 uint32_t *replySize,
6963 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006964{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006965 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006966// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006967
Eric Laurent21b5c472011-07-26 20:54:46 -07006968 if (mState == DESTROYED || mEffectInterface == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006969 return NO_INIT;
6970 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006971 status_t status = (*mEffectInterface)->command(mEffectInterface,
6972 cmdCode,
6973 cmdSize,
6974 pCmdData,
6975 replySize,
6976 pReplyData);
Eric Laurent65b65452010-06-01 23:49:17 -07006977 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006978 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07006979 for (size_t i = 1; i < mHandles.size(); i++) {
6980 sp<EffectHandle> h = mHandles[i].promote();
6981 if (h != 0) {
6982 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6983 }
6984 }
6985 }
6986 return status;
6987}
6988
6989status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6990{
Eric Laurent6752ec82011-08-10 10:37:50 -07006991
Eric Laurent65b65452010-06-01 23:49:17 -07006992 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006993 ALOGV("setEnabled %p enabled %d", this, enabled);
Eric Laurent65b65452010-06-01 23:49:17 -07006994
6995 if (enabled != isEnabled()) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006996 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6997 if (enabled && status != NO_ERROR) {
6998 return status;
6999 }
7000
Eric Laurent65b65452010-06-01 23:49:17 -07007001 switch (mState) {
7002 // going from disabled to enabled
7003 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07007004 mState = STARTING;
7005 break;
7006 case STOPPED:
7007 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07007008 break;
7009 case STOPPING:
7010 mState = ACTIVE;
7011 break;
Eric Laurent65b65452010-06-01 23:49:17 -07007012
7013 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07007014 case RESTART:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07007015 mState = STOPPED;
7016 break;
Eric Laurent65b65452010-06-01 23:49:17 -07007017 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07007018 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07007019 break;
7020 case ACTIVE:
7021 mState = STOPPING;
7022 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07007023 case DESTROYED:
7024 return NO_ERROR; // simply ignore as we are being destroyed
Eric Laurent65b65452010-06-01 23:49:17 -07007025 }
7026 for (size_t i = 1; i < mHandles.size(); i++) {
7027 sp<EffectHandle> h = mHandles[i].promote();
7028 if (h != 0) {
7029 h->setEnabled(enabled);
7030 }
7031 }
7032 }
7033 return NO_ERROR;
7034}
7035
Glenn Kasteneabd94a2012-02-02 14:06:11 -08007036bool AudioFlinger::EffectModule::isEnabled() const
Eric Laurent65b65452010-06-01 23:49:17 -07007037{
7038 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07007039 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07007040 case STARTING:
7041 case ACTIVE:
7042 return true;
7043 case IDLE:
7044 case STOPPING:
7045 case STOPPED:
Eric Laurent21b5c472011-07-26 20:54:46 -07007046 case DESTROYED:
Eric Laurent65b65452010-06-01 23:49:17 -07007047 default:
7048 return false;
7049 }
7050}
7051
Glenn Kasteneabd94a2012-02-02 14:06:11 -08007052bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurenta92ebfa2010-08-31 13:50:07 -07007053{
7054 switch (mState) {
7055 case RESTART:
7056 case ACTIVE:
7057 case STOPPING:
7058 case STOPPED:
7059 return true;
7060 case IDLE:
7061 case STARTING:
Eric Laurent21b5c472011-07-26 20:54:46 -07007062 case DESTROYED:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07007063 default:
7064 return false;
7065 }
7066}
7067
Eric Laurent65b65452010-06-01 23:49:17 -07007068status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
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;
7072
7073 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7074 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurenta92ebfa2010-08-31 13:50:07 -07007075 if (isProcessEnabled() &&
Eric Laurent0d7e0482010-07-19 06:24:46 -07007076 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7077 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07007078 status_t cmdStatus;
7079 uint32_t volume[2];
7080 uint32_t *pVolume = NULL;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007081 uint32_t size = sizeof(volume);
Eric Laurent65b65452010-06-01 23:49:17 -07007082 volume[0] = *left;
7083 volume[1] = *right;
7084 if (controller) {
7085 pVolume = volume;
7086 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007087 status = (*mEffectInterface)->command(mEffectInterface,
7088 EFFECT_CMD_SET_VOLUME,
7089 size,
7090 volume,
7091 &size,
7092 pVolume);
Eric Laurent65b65452010-06-01 23:49:17 -07007093 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7094 *left = volume[0];
7095 *right = volume[1];
7096 }
7097 }
7098 return status;
7099}
7100
7101status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7102{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07007103 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07007104 status_t status = NO_ERROR;
Eric Laurent464d5b32011-06-17 21:29:58 -07007105 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7106 // audio pre processing modules on RecordThread can receive both output and
7107 // input device indication in the same call
7108 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7109 if (dev) {
7110 status_t cmdStatus;
7111 uint32_t size = sizeof(status_t);
7112
7113 status = (*mEffectInterface)->command(mEffectInterface,
7114 EFFECT_CMD_SET_DEVICE,
7115 sizeof(uint32_t),
7116 &dev,
7117 &size,
7118 &cmdStatus);
7119 if (status == NO_ERROR) {
7120 status = cmdStatus;
7121 }
7122 }
7123 dev = device & AUDIO_DEVICE_IN_ALL;
7124 if (dev) {
7125 status_t cmdStatus;
7126 uint32_t size = sizeof(status_t);
7127
7128 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7129 EFFECT_CMD_SET_INPUT_DEVICE,
7130 sizeof(uint32_t),
7131 &dev,
7132 &size,
7133 &cmdStatus);
7134 if (status2 == NO_ERROR) {
7135 status2 = cmdStatus;
7136 }
7137 if (status == NO_ERROR) {
7138 status = status2;
7139 }
Eric Laurent65b65452010-06-01 23:49:17 -07007140 }
7141 }
7142 return status;
7143}
7144
Glenn Kastenaccb1142012-01-04 11:00:47 -08007145status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07007146{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07007147 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07007148 status_t status = NO_ERROR;
7149 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Eric Laurent53334cd2010-06-23 17:38:20 -07007150 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007151 uint32_t size = sizeof(status_t);
7152 status = (*mEffectInterface)->command(mEffectInterface,
7153 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenaccb1142012-01-04 11:00:47 -08007154 sizeof(audio_mode_t),
Eric Laurent0fb66c22011-05-17 19:16:02 -07007155 &mode,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007156 &size,
7157 &cmdStatus);
Eric Laurent53334cd2010-06-23 17:38:20 -07007158 if (status == NO_ERROR) {
7159 status = cmdStatus;
7160 }
7161 }
7162 return status;
7163}
7164
Eric Laurentf82fccd2011-07-27 19:49:51 -07007165void AudioFlinger::EffectModule::setSuspended(bool suspended)
7166{
7167 Mutex::Autolock _l(mLock);
7168 mSuspended = suspended;
7169}
Glenn Kasten1dce8412012-01-04 11:01:11 -08007170
7171bool AudioFlinger::EffectModule::suspended() const
Eric Laurentf82fccd2011-07-27 19:49:51 -07007172{
7173 Mutex::Autolock _l(mLock);
7174 return mSuspended;
7175}
7176
Eric Laurent65b65452010-06-01 23:49:17 -07007177status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7178{
7179 const size_t SIZE = 256;
7180 char buffer[SIZE];
7181 String8 result;
7182
7183 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7184 result.append(buffer);
7185
7186 bool locked = tryLock(mLock);
7187 // failed to lock - AudioFlinger is probably deadlocked
7188 if (!locked) {
7189 result.append("\t\tCould not lock Fx mutex:\n");
7190 }
7191
7192 result.append("\t\tSession Status State Engine:\n");
7193 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7194 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7195 result.append(buffer);
7196
7197 result.append("\t\tDescriptor:\n");
7198 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7199 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7200 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7201 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7202 result.append(buffer);
7203 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7204 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7205 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7206 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7207 result.append(buffer);
Eric Laurent0fb66c22011-05-17 19:16:02 -07007208 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Eric Laurent65b65452010-06-01 23:49:17 -07007209 mDescriptor.apiVersion,
7210 mDescriptor.flags);
7211 result.append(buffer);
7212 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7213 mDescriptor.name);
7214 result.append(buffer);
7215 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7216 mDescriptor.implementor);
7217 result.append(buffer);
7218
7219 result.append("\t\t- Input configuration:\n");
7220 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7221 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7222 (uint32_t)mConfig.inputCfg.buffer.raw,
7223 mConfig.inputCfg.buffer.frameCount,
7224 mConfig.inputCfg.samplingRate,
7225 mConfig.inputCfg.channels,
7226 mConfig.inputCfg.format);
7227 result.append(buffer);
7228
7229 result.append("\t\t- Output configuration:\n");
7230 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7231 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7232 (uint32_t)mConfig.outputCfg.buffer.raw,
7233 mConfig.outputCfg.buffer.frameCount,
7234 mConfig.outputCfg.samplingRate,
7235 mConfig.outputCfg.channels,
7236 mConfig.outputCfg.format);
7237 result.append(buffer);
7238
7239 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7240 result.append(buffer);
7241 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7242 for (size_t i = 0; i < mHandles.size(); ++i) {
7243 sp<EffectHandle> handle = mHandles[i].promote();
7244 if (handle != 0) {
7245 handle->dump(buffer, SIZE);
7246 result.append(buffer);
7247 }
7248 }
7249
7250 result.append("\n");
7251
7252 write(fd, result.string(), result.length());
7253
7254 if (locked) {
7255 mLock.unlock();
7256 }
7257
7258 return NO_ERROR;
7259}
7260
7261// ----------------------------------------------------------------------------
7262// EffectHandle implementation
7263// ----------------------------------------------------------------------------
7264
7265#undef LOG_TAG
7266#define LOG_TAG "AudioFlinger::EffectHandle"
7267
7268AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7269 const sp<AudioFlinger::Client>& client,
7270 const sp<IEffectClient>& effectClient,
7271 int32_t priority)
7272 : BnEffect(),
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007273 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07007274 mPriority(priority), mHasControl(false), mEnabled(false)
Eric Laurent65b65452010-06-01 23:49:17 -07007275{
Steve Block71f2cf12011-10-20 11:56:00 +01007276 ALOGV("constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07007277
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007278 if (client == 0) {
7279 return;
7280 }
Eric Laurent65b65452010-06-01 23:49:17 -07007281 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7282 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7283 if (mCblkMemory != 0) {
7284 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7285
Glenn Kasten3694ec12012-01-27 16:47:15 -08007286 if (mCblk != NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07007287 new(mCblk) effect_param_cblk_t();
7288 mBuffer = (uint8_t *)mCblk + bufOffset;
7289 }
7290 } else {
Steve Block3762c312012-01-06 19:20:56 +00007291 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Eric Laurent65b65452010-06-01 23:49:17 -07007292 return;
7293 }
7294}
7295
7296AudioFlinger::EffectHandle::~EffectHandle()
7297{
Steve Block71f2cf12011-10-20 11:56:00 +01007298 ALOGV("Destructor %p", this);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007299 disconnect(false);
Steve Block71f2cf12011-10-20 11:56:00 +01007300 ALOGV("Destructor DONE %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07007301}
7302
7303status_t AudioFlinger::EffectHandle::enable()
7304{
Steve Block71f2cf12011-10-20 11:56:00 +01007305 ALOGV("enable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07007306 if (!mHasControl) return INVALID_OPERATION;
7307 if (mEffect == 0) return DEAD_OBJECT;
7308
Eric Laurent6752ec82011-08-10 10:37:50 -07007309 if (mEnabled) {
7310 return NO_ERROR;
7311 }
7312
Eric Laurentf82fccd2011-07-27 19:49:51 -07007313 mEnabled = true;
7314
7315 sp<ThreadBase> thread = mEffect->thread().promote();
7316 if (thread != 0) {
7317 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7318 }
7319
7320 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7321 if (mEffect->suspended()) {
7322 return NO_ERROR;
7323 }
7324
Eric Laurent6752ec82011-08-10 10:37:50 -07007325 status_t status = mEffect->setEnabled(true);
7326 if (status != NO_ERROR) {
7327 if (thread != 0) {
7328 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7329 }
7330 mEnabled = false;
7331 }
7332 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07007333}
7334
7335status_t AudioFlinger::EffectHandle::disable()
7336{
Steve Block71f2cf12011-10-20 11:56:00 +01007337 ALOGV("disable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07007338 if (!mHasControl) return INVALID_OPERATION;
Eric Laurentf82fccd2011-07-27 19:49:51 -07007339 if (mEffect == 0) return DEAD_OBJECT;
Eric Laurent65b65452010-06-01 23:49:17 -07007340
Eric Laurent6752ec82011-08-10 10:37:50 -07007341 if (!mEnabled) {
7342 return NO_ERROR;
7343 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007344 mEnabled = false;
7345
7346 if (mEffect->suspended()) {
7347 return NO_ERROR;
7348 }
7349
7350 status_t status = mEffect->setEnabled(false);
7351
7352 sp<ThreadBase> thread = mEffect->thread().promote();
7353 if (thread != 0) {
7354 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7355 }
7356
7357 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07007358}
7359
7360void AudioFlinger::EffectHandle::disconnect()
7361{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007362 disconnect(true);
7363}
7364
Glenn Kasten29441ff2012-02-03 10:32:24 -08007365void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007366{
Glenn Kasten29441ff2012-02-03 10:32:24 -08007367 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Eric Laurent65b65452010-06-01 23:49:17 -07007368 if (mEffect == 0) {
7369 return;
7370 }
Glenn Kasten29441ff2012-02-03 10:32:24 -08007371 mEffect->disconnect(this, unpinIfLast);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007372
Eric Laurent7fa1cee2011-10-19 11:44:54 -07007373 if (mHasControl && mEnabled) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007374 sp<ThreadBase> thread = mEffect->thread().promote();
7375 if (thread != 0) {
7376 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7377 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007378 }
7379
Eric Laurent65b65452010-06-01 23:49:17 -07007380 // release sp on module => module destructor can be called now
7381 mEffect.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07007382 if (mClient != 0) {
Glenn Kasten3694ec12012-01-27 16:47:15 -08007383 if (mCblk != NULL) {
Glenn Kastend9d68dc2012-02-03 10:24:48 -08007384 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007385 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7386 }
Glenn Kastenf31d0502012-01-25 15:27:15 -08007387 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten803a86a2012-01-25 14:28:29 -08007388 // Client destructor must run with AudioFlinger mutex locked
Eric Laurent65b65452010-06-01 23:49:17 -07007389 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7390 mClient.clear();
7391 }
7392}
7393
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007394status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7395 uint32_t cmdSize,
7396 void *pCmdData,
7397 uint32_t *replySize,
7398 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07007399{
Steve Block71f2cf12011-10-20 11:56:00 +01007400// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007401// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07007402
7403 // only get parameter command is permitted for applications not controlling the effect
7404 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7405 return INVALID_OPERATION;
7406 }
7407 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007408 if (mClient == 0) return INVALID_OPERATION;
Eric Laurent65b65452010-06-01 23:49:17 -07007409
7410 // handle commands that are not forwarded transparently to effect engine
7411 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7412 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7413 // no risk to block the whole media server process or mixer threads is we are stuck here
7414 Mutex::Autolock _l(mCblk->lock);
7415 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7416 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7417 mCblk->serverIndex = 0;
7418 mCblk->clientIndex = 0;
7419 return BAD_VALUE;
7420 }
7421 status_t status = NO_ERROR;
7422 while (mCblk->serverIndex < mCblk->clientIndex) {
7423 int reply;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007424 uint32_t rsize = sizeof(int);
Eric Laurent65b65452010-06-01 23:49:17 -07007425 int *p = (int *)(mBuffer + mCblk->serverIndex);
7426 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07007427 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block8564c8d2012-01-05 23:22:43 +00007428 ALOGW("command(): invalid parameter block size");
Eric Laurent53334cd2010-06-23 17:38:20 -07007429 break;
7430 }
Eric Laurent65b65452010-06-01 23:49:17 -07007431 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07007432 if (param->psize == 0 || param->vsize == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007433 ALOGW("command(): null parameter or value size");
Eric Laurent53334cd2010-06-23 17:38:20 -07007434 mCblk->serverIndex += size;
7435 continue;
7436 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007437 uint32_t psize = sizeof(effect_param_t) +
7438 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7439 param->vsize;
7440 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7441 psize,
7442 p,
7443 &rsize,
7444 &reply);
Eric Laurente65280c2010-09-02 11:56:55 -07007445 // stop at first error encountered
7446 if (ret != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07007447 status = ret;
Eric Laurente65280c2010-09-02 11:56:55 -07007448 *(int *)pReplyData = reply;
7449 break;
7450 } else if (reply != NO_ERROR) {
7451 *(int *)pReplyData = reply;
7452 break;
Eric Laurent65b65452010-06-01 23:49:17 -07007453 }
7454 mCblk->serverIndex += size;
7455 }
7456 mCblk->serverIndex = 0;
7457 mCblk->clientIndex = 0;
7458 return status;
7459 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07007460 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07007461 return enable();
7462 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07007463 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07007464 return disable();
7465 }
7466
7467 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7468}
7469
Eric Laurentf82fccd2011-07-27 19:49:51 -07007470void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Eric Laurent65b65452010-06-01 23:49:17 -07007471{
Steve Block71f2cf12011-10-20 11:56:00 +01007472 ALOGV("setControl %p control %d", this, hasControl);
Eric Laurent65b65452010-06-01 23:49:17 -07007473
7474 mHasControl = hasControl;
Eric Laurentf82fccd2011-07-27 19:49:51 -07007475 mEnabled = enabled;
7476
Eric Laurent65b65452010-06-01 23:49:17 -07007477 if (signal && mEffectClient != 0) {
7478 mEffectClient->controlStatusChanged(hasControl);
7479 }
7480}
7481
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007482void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7483 uint32_t cmdSize,
7484 void *pCmdData,
7485 uint32_t replySize,
7486 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07007487{
7488 if (mEffectClient != 0) {
7489 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7490 }
7491}
7492
7493
7494
7495void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7496{
7497 if (mEffectClient != 0) {
7498 mEffectClient->enableStatusChanged(enabled);
7499 }
7500}
7501
7502status_t AudioFlinger::EffectHandle::onTransact(
7503 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7504{
7505 return BnEffect::onTransact(code, data, reply, flags);
7506}
7507
7508
7509void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7510{
Glenn Kasten3694ec12012-01-27 16:47:15 -08007511 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Eric Laurent65b65452010-06-01 23:49:17 -07007512
7513 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten81211142012-02-05 18:09:08 -08007514 (mClient == 0) ? getpid_cached : mClient->pid(),
Eric Laurent65b65452010-06-01 23:49:17 -07007515 mPriority,
7516 mHasControl,
7517 !locked,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007518 mCblk ? mCblk->clientIndex : 0,
7519 mCblk ? mCblk->serverIndex : 0
Eric Laurent65b65452010-06-01 23:49:17 -07007520 );
7521
7522 if (locked) {
7523 mCblk->lock.unlock();
7524 }
7525}
7526
7527#undef LOG_TAG
7528#define LOG_TAG "AudioFlinger::EffectChain"
7529
Glenn Kasten685c9ce2012-01-20 13:32:16 -08007530AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Eric Laurent65b65452010-06-01 23:49:17 -07007531 int sessionId)
Glenn Kasten685c9ce2012-01-20 13:32:16 -08007532 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurent90681d62011-05-09 12:09:06 -07007533 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7534 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurent65b65452010-06-01 23:49:17 -07007535{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007536 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten685c9ce2012-01-20 13:32:16 -08007537 if (thread == NULL) {
Eric Laurentf9c361d2011-11-11 15:42:52 -08007538 return;
7539 }
7540 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7541 thread->frameCount();
Eric Laurent65b65452010-06-01 23:49:17 -07007542}
7543
7544AudioFlinger::EffectChain::~EffectChain()
7545{
7546 if (mOwnInBuffer) {
7547 delete mInBuffer;
7548 }
7549
7550}
7551
Eric Laurentf82fccd2011-07-27 19:49:51 -07007552// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007553sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07007554{
Eric Laurent65b65452010-06-01 23:49:17 -07007555 size_t size = mEffects.size();
7556
7557 for (size_t i = 0; i < size; i++) {
7558 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007559 return mEffects[i];
Eric Laurent65b65452010-06-01 23:49:17 -07007560 }
7561 }
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007562 return 0;
Eric Laurent65b65452010-06-01 23:49:17 -07007563}
7564
Eric Laurentf82fccd2011-07-27 19:49:51 -07007565// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007566sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07007567{
Eric Laurent65b65452010-06-01 23:49:17 -07007568 size_t size = mEffects.size();
7569
7570 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007571 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7572 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007573 return mEffects[i];
Eric Laurent65b65452010-06-01 23:49:17 -07007574 }
7575 }
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007576 return 0;
Eric Laurent65b65452010-06-01 23:49:17 -07007577}
7578
Eric Laurentf82fccd2011-07-27 19:49:51 -07007579// getEffectFromType_l() must be called with ThreadBase::mLock held
7580sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7581 const effect_uuid_t *type)
7582{
Eric Laurentf82fccd2011-07-27 19:49:51 -07007583 size_t size = mEffects.size();
7584
7585 for (size_t i = 0; i < size; i++) {
7586 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007587 return mEffects[i];
Eric Laurentf82fccd2011-07-27 19:49:51 -07007588 }
7589 }
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007590 return 0;
Eric Laurentf82fccd2011-07-27 19:49:51 -07007591}
7592
Eric Laurent65b65452010-06-01 23:49:17 -07007593// Must be called with EffectChain::mLock locked
7594void AudioFlinger::EffectChain::process_l()
7595{
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007596 sp<ThreadBase> thread = mThread.promote();
7597 if (thread == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007598 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007599 return;
7600 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007601 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7602 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007603 // always process effects unless no more tracks are on the session and the effect tail
7604 // has been rendered
7605 bool doProcess = true;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007606 if (!isGlobalSession) {
Eric Laurentf9c361d2011-11-11 15:42:52 -08007607 bool tracksOnSession = (trackCnt() != 0);
Eric Laurent90681d62011-05-09 12:09:06 -07007608
Eric Laurentf9c361d2011-11-11 15:42:52 -08007609 if (!tracksOnSession && mTailBufferCount == 0) {
7610 doProcess = false;
7611 }
7612
7613 if (activeTrackCnt() == 0) {
7614 // if no track is active and the effect tail has not been rendered,
7615 // the input buffer must be cleared here as the mixer process will not do it
7616 if (tracksOnSession || mTailBufferCount > 0) {
7617 size_t numSamples = thread->frameCount() * thread->channelCount();
7618 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7619 if (mTailBufferCount > 0) {
7620 mTailBufferCount--;
7621 }
7622 }
7623 }
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007624 }
7625
Eric Laurent65b65452010-06-01 23:49:17 -07007626 size_t size = mEffects.size();
Eric Laurentf9c361d2011-11-11 15:42:52 -08007627 if (doProcess) {
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007628 for (size_t i = 0; i < size; i++) {
7629 mEffects[i]->process();
7630 }
Eric Laurent65b65452010-06-01 23:49:17 -07007631 }
Eric Laurent7d850f22010-07-09 13:34:17 -07007632 for (size_t i = 0; i < size; i++) {
7633 mEffects[i]->updateState();
7634 }
Eric Laurent65b65452010-06-01 23:49:17 -07007635}
7636
Eric Laurent76c40f72010-07-15 12:50:15 -07007637// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007638status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007639{
7640 effect_descriptor_t desc = effect->desc();
7641 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7642
7643 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007644 effect->setChain(this);
7645 sp<ThreadBase> thread = mThread.promote();
7646 if (thread == 0) {
7647 return NO_INIT;
7648 }
7649 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07007650
7651 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7652 // Auxiliary effects are inserted at the beginning of mEffects vector as
7653 // they are processed first and accumulated in chain input buffer
7654 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007655
Eric Laurent65b65452010-06-01 23:49:17 -07007656 // the input buffer for auxiliary effect contains mono samples in
7657 // 32 bit format. This is to avoid saturation in AudoMixer
7658 // accumulation stage. Saturation is done in EffectModule::process() before
7659 // calling the process in effect engine
7660 size_t numSamples = thread->frameCount();
7661 int32_t *buffer = new int32_t[numSamples];
7662 memset(buffer, 0, numSamples * sizeof(int32_t));
7663 effect->setInBuffer((int16_t *)buffer);
7664 // auxiliary effects output samples to chain input buffer for further processing
7665 // by insert effects
7666 effect->setOutBuffer(mInBuffer);
7667 } else {
7668 // Insert effects are inserted at the end of mEffects vector as they are processed
7669 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07007670 // Insert effect order as a function of indicated preference:
7671 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7672 // another effect is present
7673 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7674 // last effect claiming first position
7675 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7676 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07007677 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07007678 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7679 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07007680
Glenn Kasten150d2382012-02-08 14:04:28 -08007681 size_t size = mEffects.size();
7682 size_t idx_insert = size;
7683 ssize_t idx_insert_first = -1;
7684 ssize_t idx_insert_last = -1;
Eric Laurent65b65452010-06-01 23:49:17 -07007685
Glenn Kasten150d2382012-02-08 14:04:28 -08007686 for (size_t i = 0; i < size; i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07007687 effect_descriptor_t d = mEffects[i]->desc();
7688 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7689 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7690 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7691 // check invalid effect chaining combinations
7692 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07007693 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block8564c8d2012-01-05 23:22:43 +00007694 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07007695 return INVALID_OPERATION;
7696 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007697 // remember position of first insert effect and by default
7698 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07007699 if (idx_insert == size) {
7700 idx_insert = i;
7701 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007702 // remember position of last insert effect claiming
7703 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07007704 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7705 idx_insert_first = i;
7706 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007707 // remember position of first insert effect claiming
7708 // last position
7709 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7710 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07007711 idx_insert_last = i;
7712 }
7713 }
7714 }
7715
Eric Laurent53334cd2010-06-23 17:38:20 -07007716 // modify idx_insert from first position if needed
7717 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7718 if (idx_insert_last != -1) {
7719 idx_insert = idx_insert_last;
7720 } else {
7721 idx_insert = size;
7722 }
7723 } else {
7724 if (idx_insert_first != -1) {
7725 idx_insert = idx_insert_first + 1;
7726 }
Eric Laurent65b65452010-06-01 23:49:17 -07007727 }
7728
7729 // always read samples from chain input buffer
7730 effect->setInBuffer(mInBuffer);
7731
7732 // if last effect in the chain, output samples to chain
7733 // output buffer, otherwise to chain input buffer
7734 if (idx_insert == size) {
7735 if (idx_insert != 0) {
7736 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7737 mEffects[idx_insert-1]->configure();
7738 }
7739 effect->setOutBuffer(mOutBuffer);
7740 } else {
7741 effect->setOutBuffer(mInBuffer);
7742 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007743 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007744
Steve Block71f2cf12011-10-20 11:56:00 +01007745 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007746 }
7747 effect->configure();
7748 return NO_ERROR;
7749}
7750
Eric Laurent76c40f72010-07-15 12:50:15 -07007751// removeEffect_l() must be called with PlaybackThread::mLock held
7752size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007753{
7754 Mutex::Autolock _l(mLock);
Glenn Kasten150d2382012-02-08 14:04:28 -08007755 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07007756 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7757
Glenn Kasten150d2382012-02-08 14:04:28 -08007758 for (size_t i = 0; i < size; i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07007759 if (effect == mEffects[i]) {
Eric Laurent21b5c472011-07-26 20:54:46 -07007760 // calling stop here will remove pre-processing effect from the audio HAL.
7761 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7762 // the middle of a read from audio HAL
Eric Laurent6fccbd02011-10-05 17:42:25 -07007763 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7764 mEffects[i]->state() == EffectModule::STOPPING) {
7765 mEffects[i]->stop();
7766 }
Eric Laurent65b65452010-06-01 23:49:17 -07007767 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7768 delete[] effect->inBuffer();
7769 } else {
7770 if (i == size - 1 && i != 0) {
7771 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7772 mEffects[i - 1]->configure();
7773 }
7774 }
7775 mEffects.removeAt(i);
Steve Block71f2cf12011-10-20 11:56:00 +01007776 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07007777 break;
7778 }
7779 }
Eric Laurent65b65452010-06-01 23:49:17 -07007780
7781 return mEffects.size();
7782}
7783
Eric Laurent76c40f72010-07-15 12:50:15 -07007784// setDevice_l() must be called with PlaybackThread::mLock held
7785void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07007786{
7787 size_t size = mEffects.size();
7788 for (size_t i = 0; i < size; i++) {
7789 mEffects[i]->setDevice(device);
7790 }
7791}
7792
Eric Laurent76c40f72010-07-15 12:50:15 -07007793// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenaccb1142012-01-04 11:00:47 -08007794void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07007795{
7796 size_t size = mEffects.size();
7797 for (size_t i = 0; i < size; i++) {
7798 mEffects[i]->setMode(mode);
7799 }
7800}
7801
Eric Laurent76c40f72010-07-15 12:50:15 -07007802// setVolume_l() must be called with PlaybackThread::mLock held
7803bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07007804{
7805 uint32_t newLeft = *left;
7806 uint32_t newRight = *right;
7807 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07007808 int ctrlIdx = -1;
7809 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07007810
Eric Laurent76c40f72010-07-15 12:50:15 -07007811 // first update volume controller
7812 for (size_t i = size; i > 0; i--) {
Eric Laurenta92ebfa2010-08-31 13:50:07 -07007813 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurent76c40f72010-07-15 12:50:15 -07007814 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7815 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007816 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07007817 break;
7818 }
7819 }
7820
7821 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07007822 if (hasControl) {
7823 *left = mNewLeftVolume;
7824 *right = mNewRightVolume;
7825 }
7826 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07007827 }
7828
7829 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007830 mLeftVolume = newLeft;
7831 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007832
7833 // second get volume update from volume controller
7834 if (ctrlIdx >= 0) {
7835 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07007836 mNewLeftVolume = newLeft;
7837 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07007838 }
7839 // then indicate volume to all other effects in chain.
7840 // Pass altered volume to effects before volume controller
7841 // and requested volume to effects after controller
7842 uint32_t lVol = newLeft;
7843 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007844
Eric Laurent65b65452010-06-01 23:49:17 -07007845 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07007846 if ((int)i == ctrlIdx) continue;
7847 // this also works for ctrlIdx == -1 when there is no volume controller
7848 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07007849 lVol = *left;
7850 rVol = *right;
7851 }
7852 mEffects[i]->setVolume(&lVol, &rVol, false);
7853 }
7854 *left = newLeft;
7855 *right = newRight;
7856
7857 return hasControl;
7858}
7859
Eric Laurent65b65452010-06-01 23:49:17 -07007860status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7861{
7862 const size_t SIZE = 256;
7863 char buffer[SIZE];
7864 String8 result;
7865
7866 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7867 result.append(buffer);
7868
7869 bool locked = tryLock(mLock);
7870 // failed to lock - AudioFlinger is probably deadlocked
7871 if (!locked) {
7872 result.append("\tCould not lock mutex:\n");
7873 }
7874
Eric Laurent76c40f72010-07-15 12:50:15 -07007875 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7876 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07007877 mEffects.size(),
7878 (uint32_t)mInBuffer,
7879 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07007880 mActiveTrackCnt);
7881 result.append(buffer);
7882 write(fd, result.string(), result.size());
7883
7884 for (size_t i = 0; i < mEffects.size(); ++i) {
7885 sp<EffectModule> effect = mEffects[i];
7886 if (effect != 0) {
7887 effect->dump(fd, args);
7888 }
7889 }
7890
7891 if (locked) {
7892 mLock.unlock();
7893 }
7894
7895 return NO_ERROR;
7896}
7897
Eric Laurentf82fccd2011-07-27 19:49:51 -07007898// must be called with ThreadBase::mLock held
7899void AudioFlinger::EffectChain::setEffectSuspended_l(
7900 const effect_uuid_t *type, bool suspend)
7901{
7902 sp<SuspendedEffectDesc> desc;
7903 // use effect type UUID timelow as key as there is no real risk of identical
7904 // timeLow fields among effect type UUIDs.
Glenn Kasten150d2382012-02-08 14:04:28 -08007905 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007906 if (suspend) {
7907 if (index >= 0) {
7908 desc = mSuspendedEffects.valueAt(index);
7909 } else {
7910 desc = new SuspendedEffectDesc();
7911 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7912 mSuspendedEffects.add(type->timeLow, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007913 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007914 }
7915 if (desc->mRefCount++ == 0) {
7916 sp<EffectModule> effect = getEffectIfEnabled(type);
7917 if (effect != 0) {
7918 desc->mEffect = effect;
7919 effect->setSuspended(true);
7920 effect->setEnabled(false);
7921 }
7922 }
7923 } else {
7924 if (index < 0) {
7925 return;
7926 }
7927 desc = mSuspendedEffects.valueAt(index);
7928 if (desc->mRefCount <= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007929 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007930 desc->mRefCount = 1;
7931 }
7932 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01007933 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007934 if (desc->mEffect != 0) {
7935 sp<EffectModule> effect = desc->mEffect.promote();
7936 if (effect != 0) {
7937 effect->setSuspended(false);
7938 sp<EffectHandle> handle = effect->controlHandle();
7939 if (handle != 0) {
7940 effect->setEnabled(handle->enabled());
7941 }
7942 }
7943 desc->mEffect.clear();
7944 }
7945 mSuspendedEffects.removeItemsAt(index);
7946 }
7947 }
7948}
7949
7950// must be called with ThreadBase::mLock held
7951void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7952{
7953 sp<SuspendedEffectDesc> desc;
7954
Glenn Kasten150d2382012-02-08 14:04:28 -08007955 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007956 if (suspend) {
7957 if (index >= 0) {
7958 desc = mSuspendedEffects.valueAt(index);
7959 } else {
7960 desc = new SuspendedEffectDesc();
7961 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007962 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurentf82fccd2011-07-27 19:49:51 -07007963 }
7964 if (desc->mRefCount++ == 0) {
Glenn Kasten97040262012-01-30 12:56:03 -08007965 Vector< sp<EffectModule> > effects;
7966 getSuspendEligibleEffects(effects);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007967 for (size_t i = 0; i < effects.size(); i++) {
7968 setEffectSuspended_l(&effects[i]->desc().type, true);
7969 }
7970 }
7971 } else {
7972 if (index < 0) {
7973 return;
7974 }
7975 desc = mSuspendedEffects.valueAt(index);
7976 if (desc->mRefCount <= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007977 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007978 desc->mRefCount = 1;
7979 }
7980 if (--desc->mRefCount == 0) {
7981 Vector<const effect_uuid_t *> types;
7982 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7983 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7984 continue;
7985 }
7986 types.add(&mSuspendedEffects.valueAt(i)->mType);
7987 }
7988 for (size_t i = 0; i < types.size(); i++) {
7989 setEffectSuspended_l(types[i], false);
7990 }
Steve Block71f2cf12011-10-20 11:56:00 +01007991 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007992 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7993 }
7994 }
7995}
7996
Eric Laurent5e7acae2011-09-23 08:40:41 -07007997
7998// The volume effect is used for automated tests only
7999#ifndef OPENSL_ES_H_
8000static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
8001 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
8002const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
8003#endif //OPENSL_ES_H_
8004
Eric Laurent6752ec82011-08-10 10:37:50 -07008005bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
8006{
8007 // auxiliary effects and visualizer are never suspended on output mix
8008 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8009 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent5e7acae2011-09-23 08:40:41 -07008010 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8011 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurent6752ec82011-08-10 10:37:50 -07008012 return false;
8013 }
8014 return true;
8015}
8016
Glenn Kasten97040262012-01-30 12:56:03 -08008017void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurentf82fccd2011-07-27 19:49:51 -07008018{
Glenn Kasten97040262012-01-30 12:56:03 -08008019 effects.clear();
Eric Laurentf82fccd2011-07-27 19:49:51 -07008020 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kasten97040262012-01-30 12:56:03 -08008021 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8022 effects.add(mEffects[i]);
Eric Laurentf82fccd2011-07-27 19:49:51 -07008023 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07008024 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07008025}
8026
8027sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8028 const effect_uuid_t *type)
8029{
Glenn Kastenc64a6f02012-01-30 13:00:02 -08008030 sp<EffectModule> effect = getEffectFromType_l(type);
8031 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurentf82fccd2011-07-27 19:49:51 -07008032}
8033
8034void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8035 bool enabled)
8036{
Glenn Kasten150d2382012-02-08 14:04:28 -08008037 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentf82fccd2011-07-27 19:49:51 -07008038 if (enabled) {
8039 if (index < 0) {
8040 // if the effect is not suspend check if all effects are suspended
8041 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8042 if (index < 0) {
8043 return;
8044 }
Eric Laurent6752ec82011-08-10 10:37:50 -07008045 if (!isEffectEligibleForSuspend(effect->desc())) {
8046 return;
8047 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07008048 setEffectSuspended_l(&effect->desc().type, enabled);
8049 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent6752ec82011-08-10 10:37:50 -07008050 if (index < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00008051 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurent6752ec82011-08-10 10:37:50 -07008052 return;
8053 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07008054 }
Steve Block71f2cf12011-10-20 11:56:00 +01008055 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07008056 effect->desc().type.timeLow);
8057 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8058 // if effect is requested to suspended but was not yet enabled, supend it now.
8059 if (desc->mEffect == 0) {
8060 desc->mEffect = effect;
8061 effect->setEnabled(false);
8062 effect->setSuspended(true);
8063 }
8064 } else {
8065 if (index < 0) {
8066 return;
8067 }
Steve Block71f2cf12011-10-20 11:56:00 +01008068 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07008069 effect->desc().type.timeLow);
8070 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8071 desc->mEffect.clear();
8072 effect->setSuspended(false);
8073 }
8074}
8075
Eric Laurent65b65452010-06-01 23:49:17 -07008076#undef LOG_TAG
8077#define LOG_TAG "AudioFlinger"
8078
Eric Laurenta553c252009-07-17 12:17:14 -07008079// ----------------------------------------------------------------------------
8080
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07008081status_t AudioFlinger::onTransact(
8082 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8083{
8084 return BnAudioFlinger::onTransact(code, data, reply, flags);
8085}
8086
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07008087}; // namespace android