blob: 1d4f12b404f70c062be8303ff1bd41c4bb475f50 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070034#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035
Dima Zavinfce7a472011-04-19 22:30:36 -070036#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080038#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039
Glenn Kastend3cee2f2012-03-13 17:55:35 -070040#undef ADD_BATTERY_DATA
41
42#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080043#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080044#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070045#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070046
47#include <private/media/AudioTrackShared.h>
48#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070049
Dima Zavin64760242011-05-11 14:15:23 -070050#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070051#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
53#include "AudioMixer.h"
54#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080055#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Mathias Agopian65ab4712010-07-14 17:59:35 -070057#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070058#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070059#include <audio_effects/effect_ns.h>
60#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061
Glenn Kasten3b21c502011-12-15 09:52:39 -080062#include <audio_utils/primitives.h>
63
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070064#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070065#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070066// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
67
John Grossman4ff14ba2012-02-08 16:37:41 -080068#include <common_time/cc_helper.h>
69#include <common_time/local_clock.h>
70
Mathias Agopian65ab4712010-07-14 17:59:35 -070071// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070072
Eric Laurentde070132010-07-13 04:45:46 -070073
Mathias Agopian65ab4712010-07-14 17:59:35 -070074namespace android {
75
Glenn Kastenec1d6b52011-12-12 09:04:45 -080076static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
77static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070078
Mathias Agopian65ab4712010-07-14 17:59:35 -070079static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -080080static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070081
82// retry counts for buffer fill timeout
83// 50 * ~20msecs = 1 second
84static const int8_t kMaxTrackRetries = 50;
85static const int8_t kMaxTrackStartupRetries = 50;
86// allow less retry attempts on direct output thread.
87// direct outputs can be a scarce resource in audio hardware and should
88// be released as quickly as possible.
89static const int8_t kMaxTrackRetriesDirect = 2;
90
91static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -080092static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070093
Glenn Kasten7dede872011-12-13 11:04:14 -080094// don't warn about blocked writes or record buffer overflows more often than this
95static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -070096
Eric Laurent7c7f10b2011-06-17 21:29:58 -070097// RecordThread loop sleep time upon application overrun or audio HAL read error
98static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070099
Glenn Kasten7dede872011-12-13 11:04:14 -0800100// maximum time to wait for setParameters to complete
101static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700102
Eric Laurent7cafbb32011-11-22 18:50:29 -0800103// minimum sleep time for the mixer thread loop when tracks are active but in underrun
104static const uint32_t kMinThreadSleepTimeUs = 5000;
105// maximum divider applied to the active sleep time in the mixer thread loop
106static const uint32_t kMaxThreadSleepTimeShift = 2;
107
John Grossman4ff14ba2012-02-08 16:37:41 -0800108nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800109
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110// ----------------------------------------------------------------------------
111
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700112#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800113// To collect the amplifier usage
114static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800115 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
116 if (service == NULL) {
117 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800118 return;
119 }
120
121 service->addBatteryData(params);
122}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700123#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800124
Dima Zavin799a70e2011-04-18 16:57:27 -0700125static int load_audio_interface(const char *if_name, const hw_module_t **mod,
126 audio_hw_device_t **dev)
127{
128 int rc;
129
130 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
131 if (rc)
132 goto out;
133
134 rc = audio_hw_device_open(*mod, dev);
Steve Block29357bc2012-01-06 19:20:56 +0000135 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin799a70e2011-04-18 16:57:27 -0700136 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
137 if (rc)
138 goto out;
139
140 return 0;
141
142out:
143 *mod = NULL;
144 *dev = NULL;
145 return rc;
146}
147
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800148static const char * const audio_interfaces[] = {
Dima Zavin799a70e2011-04-18 16:57:27 -0700149 "primary",
150 "a2dp",
151 "usb",
152};
153#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
154
Mathias Agopian65ab4712010-07-14 17:59:35 -0700155// ----------------------------------------------------------------------------
156
157AudioFlinger::AudioFlinger()
158 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800159 mPrimaryHardwareDev(NULL),
160 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
161 mMasterVolume(1.0f),
162 mMasterVolumeSupportLvl(MVS_NONE),
163 mMasterMute(false),
164 mNextUniqueId(1),
165 mMode(AUDIO_MODE_INVALID),
166 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700167{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700168}
169
170void AudioFlinger::onFirstRef()
171{
Dima Zavin799a70e2011-04-18 16:57:27 -0700172 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700173
Eric Laurent93575202011-01-18 18:39:02 -0800174 Mutex::Autolock _l(mLock);
175
Dima Zavin799a70e2011-04-18 16:57:27 -0700176 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800177 char val_str[PROPERTY_VALUE_MAX] = { 0 };
178 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
179 uint32_t int_val;
180 if (1 == sscanf(val_str, "%u", &int_val)) {
181 mStandbyTimeInNsecs = milliseconds(int_val);
182 ALOGI("Using %u mSec as standby time.", int_val);
183 } else {
184 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
185 ALOGI("Using default %u mSec as standby time.",
186 (uint32_t)(mStandbyTimeInNsecs / 1000000));
187 }
188 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700189
Dima Zavin799a70e2011-04-18 16:57:27 -0700190 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
191 const hw_module_t *mod;
192 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700193
Dima Zavin799a70e2011-04-18 16:57:27 -0700194 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
195 if (rc)
196 continue;
197
Steve Blockdf64d152012-01-04 20:05:49 +0000198 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700199 mod->name, mod->id);
Dima Zavin799a70e2011-04-18 16:57:27 -0700200 mAudioHwDevs.push(dev);
201
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800202 if (mPrimaryHardwareDev == NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700203 mPrimaryHardwareDev = dev;
Steve Blockdf64d152012-01-04 20:05:49 +0000204 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700205 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700206 }
207 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700208
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800209 if (mPrimaryHardwareDev == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000210 ALOGE("Primary audio interface not found");
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800211 // proceed, all later accesses to mPrimaryHardwareDev verify it's safe with initCheck()
Dima Zavin799a70e2011-04-18 16:57:27 -0700212 }
213
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800214 // Currently (mPrimaryHardwareDev == NULL) == (mAudioHwDevs.size() == 0), but the way the
215 // primary HW dev is selected can change so these conditions might not always be equivalent.
216 // When that happens, re-visit all the code that assumes this.
217
218 AutoMutex lock(mHardwareLock);
219
John Grossman4ff14ba2012-02-08 16:37:41 -0800220 // Determine the level of master volume support the primary audio HAL has,
221 // and set the initial master volume at the same time.
222 float initialVolume = 1.0;
223 mMasterVolumeSupportLvl = MVS_NONE;
224 if (0 == mPrimaryHardwareDev->init_check(mPrimaryHardwareDev)) {
225 audio_hw_device_t *dev = mPrimaryHardwareDev;
226
227 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
228 if ((NULL != dev->get_master_volume) &&
229 (NO_ERROR == dev->get_master_volume(dev, &initialVolume))) {
230 mMasterVolumeSupportLvl = MVS_FULL;
231 } else {
232 mMasterVolumeSupportLvl = MVS_SETONLY;
233 initialVolume = 1.0;
234 }
235
236 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
237 if ((NULL == dev->set_master_volume) ||
238 (NO_ERROR != dev->set_master_volume(dev, initialVolume))) {
239 mMasterVolumeSupportLvl = MVS_NONE;
240 }
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800241 mHardwareStatus = AUDIO_HW_IDLE;
John Grossman4ff14ba2012-02-08 16:37:41 -0800242 }
243
244 // Set the mode for each audio HAL, and try to set the initial volume (if
245 // supported) for all of the non-primary audio HALs.
Dima Zavin799a70e2011-04-18 16:57:27 -0700246 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
247 audio_hw_device_t *dev = mAudioHwDevs[i];
248
249 mHardwareStatus = AUDIO_HW_INIT;
250 rc = dev->init_check(dev);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800251 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700252 if (rc == 0) {
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800253 mMode = AUDIO_MODE_NORMAL; // assigned multiple times with same value
Dima Zavin799a70e2011-04-18 16:57:27 -0700254 mHardwareStatus = AUDIO_HW_SET_MODE;
255 dev->set_mode(dev, mMode);
John Grossman4ff14ba2012-02-08 16:37:41 -0800256
257 if ((dev != mPrimaryHardwareDev) &&
258 (NULL != dev->set_master_volume)) {
259 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
260 dev->set_master_volume(dev, initialVolume);
261 }
262
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800263 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700264 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700265 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800266
267 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
268 ? initialVolume
269 : 1.0;
270 mMasterVolume = initialVolume;
271 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700272}
273
274AudioFlinger::~AudioFlinger()
275{
Dima Zavin799a70e2011-04-18 16:57:27 -0700276
Mathias Agopian65ab4712010-07-14 17:59:35 -0700277 while (!mRecordThreads.isEmpty()) {
278 // closeInput() will remove first entry from mRecordThreads
279 closeInput(mRecordThreads.keyAt(0));
280 }
281 while (!mPlaybackThreads.isEmpty()) {
282 // closeOutput() will remove first entry from mPlaybackThreads
283 closeOutput(mPlaybackThreads.keyAt(0));
284 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700285
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800286 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
287 // no mHardwareLock needed, as there are no other references to this
288 audio_hw_device_close(mAudioHwDevs[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700289 }
290}
291
Dima Zavin799a70e2011-04-18 16:57:27 -0700292audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
293{
294 /* first matching HW device is returned */
295 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
296 audio_hw_device_t *dev = mAudioHwDevs[i];
297 if ((dev->get_supported_devices(dev) & devices) == devices)
298 return dev;
299 }
300 return NULL;
301}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700302
303status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
304{
305 const size_t SIZE = 256;
306 char buffer[SIZE];
307 String8 result;
308
309 result.append("Clients:\n");
310 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800311 sp<Client> client = mClients.valueAt(i).promote();
312 if (client != 0) {
313 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
314 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700315 }
316 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700317
318 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800319 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700320 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
321 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800322 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700323 result.append(buffer);
324 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700325 write(fd, result.string(), result.size());
326 return NO_ERROR;
327}
328
329
330status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
331{
332 const size_t SIZE = 256;
333 char buffer[SIZE];
334 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800335 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700336
John Grossman4ff14ba2012-02-08 16:37:41 -0800337 snprintf(buffer, SIZE, "Hardware status: %d\n"
338 "Standby Time mSec: %u\n",
339 hardwareStatus,
340 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700341 result.append(buffer);
342 write(fd, result.string(), result.size());
343 return NO_ERROR;
344}
345
346status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
347{
348 const size_t SIZE = 256;
349 char buffer[SIZE];
350 String8 result;
351 snprintf(buffer, SIZE, "Permission Denial: "
352 "can't dump AudioFlinger from pid=%d, uid=%d\n",
353 IPCThreadState::self()->getCallingPid(),
354 IPCThreadState::self()->getCallingUid());
355 result.append(buffer);
356 write(fd, result.string(), result.size());
357 return NO_ERROR;
358}
359
360static bool tryLock(Mutex& mutex)
361{
362 bool locked = false;
363 for (int i = 0; i < kDumpLockRetries; ++i) {
364 if (mutex.tryLock() == NO_ERROR) {
365 locked = true;
366 break;
367 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800368 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700369 }
370 return locked;
371}
372
373status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
374{
Glenn Kasten44deb052012-02-05 18:09:08 -0800375 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700376 dumpPermissionDenial(fd, args);
377 } else {
378 // get state of hardware lock
379 bool hardwareLocked = tryLock(mHardwareLock);
380 if (!hardwareLocked) {
381 String8 result(kHardwareLockedString);
382 write(fd, result.string(), result.size());
383 } else {
384 mHardwareLock.unlock();
385 }
386
387 bool locked = tryLock(mLock);
388
389 // failed to lock - AudioFlinger is probably deadlocked
390 if (!locked) {
391 String8 result(kDeadlockedString);
392 write(fd, result.string(), result.size());
393 }
394
395 dumpClients(fd, args);
396 dumpInternals(fd, args);
397
398 // dump playback threads
399 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
400 mPlaybackThreads.valueAt(i)->dump(fd, args);
401 }
402
403 // dump record threads
404 for (size_t i = 0; i < mRecordThreads.size(); i++) {
405 mRecordThreads.valueAt(i)->dump(fd, args);
406 }
407
Dima Zavin799a70e2011-04-18 16:57:27 -0700408 // dump all hardware devs
409 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
410 audio_hw_device_t *dev = mAudioHwDevs[i];
411 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700412 }
413 if (locked) mLock.unlock();
414 }
415 return NO_ERROR;
416}
417
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800418sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
419{
420 // If pid is already in the mClients wp<> map, then use that entry
421 // (for which promote() is always != 0), otherwise create a new entry and Client.
422 sp<Client> client = mClients.valueFor(pid).promote();
423 if (client == 0) {
424 client = new Client(this, pid);
425 mClients.add(pid, client);
426 }
427
428 return client;
429}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700430
431// IAudioFlinger interface
432
433
434sp<IAudioTrack> AudioFlinger::createTrack(
435 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800436 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700437 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800438 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700439 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700440 int frameCount,
Glenn Kasten5cf034d2012-02-21 10:35:56 -0800441 // FIXME dead, remove from IAudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700442 uint32_t flags,
443 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800444 audio_io_handle_t output,
John Grossman4ff14ba2012-02-08 16:37:41 -0800445 bool isTimed,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700446 int *sessionId,
447 status_t *status)
448{
449 sp<PlaybackThread::Track> track;
450 sp<TrackHandle> trackHandle;
451 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700452 status_t lStatus;
453 int lSessionId;
454
Glenn Kasten263709e2012-01-06 08:40:01 -0800455 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
456 // but if someone uses binder directly they could bypass that and cause us to crash
457 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000458 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700459 lStatus = BAD_VALUE;
460 goto Exit;
461 }
462
463 {
464 Mutex::Autolock _l(mLock);
465 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700466 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700467 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000468 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700469 lStatus = BAD_VALUE;
470 goto Exit;
471 }
472
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800473 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700474
Steve Block3856b092011-10-20 11:56:00 +0100475 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700476 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700477 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700478 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
479 if (mPlaybackThreads.keyAt(i) != output) {
480 // prevent same audio session on different output threads
481 uint32_t sessions = t->hasAudioSession(*sessionId);
482 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000483 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700484 lStatus = BAD_VALUE;
485 goto Exit;
486 }
487 // check if an effect with same session ID is waiting for a track to be created
488 if (sessions & PlaybackThread::EFFECT_SESSION) {
489 effectThread = t.get();
490 }
Eric Laurentde070132010-07-13 04:45:46 -0700491 }
492 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700493 lSessionId = *sessionId;
494 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700495 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700496 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700497 if (sessionId != NULL) {
498 *sessionId = lSessionId;
499 }
500 }
Steve Block3856b092011-10-20 11:56:00 +0100501 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700502
503 track = thread->createTrack_l(client, streamType, sampleRate, format,
John Grossman4ff14ba2012-02-08 16:37:41 -0800504 channelMask, frameCount, sharedBuffer, lSessionId, isTimed, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700505
506 // move effect chain to this output thread if an effect on same session was waiting
507 // for a track to be created
508 if (lStatus == NO_ERROR && effectThread != NULL) {
509 Mutex::Autolock _dl(thread->mLock);
510 Mutex::Autolock _sl(effectThread->mLock);
511 moveEffectChain_l(lSessionId, effectThread, thread, true);
512 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700513 }
514 if (lStatus == NO_ERROR) {
515 trackHandle = new TrackHandle(track);
516 } else {
517 // remove local strong reference to Client before deleting the Track so that the Client
518 // destructor is called by the TrackBase destructor with mLock held
519 client.clear();
520 track.clear();
521 }
522
523Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700524 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700525 *status = lStatus;
526 }
527 return trackHandle;
528}
529
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800530uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700531{
532 Mutex::Autolock _l(mLock);
533 PlaybackThread *thread = checkPlaybackThread_l(output);
534 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000535 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700536 return 0;
537 }
538 return thread->sampleRate();
539}
540
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800541int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700542{
543 Mutex::Autolock _l(mLock);
544 PlaybackThread *thread = checkPlaybackThread_l(output);
545 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000546 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700547 return 0;
548 }
549 return thread->channelCount();
550}
551
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800552audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700553{
554 Mutex::Autolock _l(mLock);
555 PlaybackThread *thread = checkPlaybackThread_l(output);
556 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000557 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800558 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700559 }
560 return thread->format();
561}
562
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800563size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700564{
565 Mutex::Autolock _l(mLock);
566 PlaybackThread *thread = checkPlaybackThread_l(output);
567 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000568 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700569 return 0;
570 }
571 return thread->frameCount();
572}
573
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800574uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700575{
576 Mutex::Autolock _l(mLock);
577 PlaybackThread *thread = checkPlaybackThread_l(output);
578 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000579 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700580 return 0;
581 }
582 return thread->latency();
583}
584
585status_t AudioFlinger::setMasterVolume(float value)
586{
Eric Laurenta1884f92011-08-23 08:25:03 -0700587 status_t ret = initCheck();
588 if (ret != NO_ERROR) {
589 return ret;
590 }
591
Mathias Agopian65ab4712010-07-14 17:59:35 -0700592 // check calling permissions
593 if (!settingsAllowed()) {
594 return PERMISSION_DENIED;
595 }
596
John Grossman4ff14ba2012-02-08 16:37:41 -0800597 float swmv = value;
598
Mathias Agopian65ab4712010-07-14 17:59:35 -0700599 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800600 if (MVS_NONE != mMasterVolumeSupportLvl) {
601 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
602 AutoMutex lock(mHardwareLock);
603 audio_hw_device_t *dev = mAudioHwDevs[i];
604
605 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
606 if (NULL != dev->set_master_volume) {
607 dev->set_master_volume(dev, value);
608 }
609 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800610 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800611
612 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700613 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700614
Eric Laurent93575202011-01-18 18:39:02 -0800615 Mutex::Autolock _l(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -0800616 mMasterVolume = value;
617 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800618 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700619 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700620
621 return NO_ERROR;
622}
623
Glenn Kastenf78aee72012-01-04 11:00:47 -0800624status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700625{
Eric Laurenta1884f92011-08-23 08:25:03 -0700626 status_t ret = initCheck();
627 if (ret != NO_ERROR) {
628 return ret;
629 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700630
631 // check calling permissions
632 if (!settingsAllowed()) {
633 return PERMISSION_DENIED;
634 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800635 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000636 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700637 return BAD_VALUE;
638 }
639
640 { // scope for the lock
641 AutoMutex lock(mHardwareLock);
642 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700643 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700644 mHardwareStatus = AUDIO_HW_IDLE;
645 }
646
647 if (NO_ERROR == ret) {
648 Mutex::Autolock _l(mLock);
649 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800650 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700651 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700652 }
653
654 return ret;
655}
656
657status_t AudioFlinger::setMicMute(bool state)
658{
Eric Laurenta1884f92011-08-23 08:25:03 -0700659 status_t ret = initCheck();
660 if (ret != NO_ERROR) {
661 return ret;
662 }
663
Mathias Agopian65ab4712010-07-14 17:59:35 -0700664 // check calling permissions
665 if (!settingsAllowed()) {
666 return PERMISSION_DENIED;
667 }
668
669 AutoMutex lock(mHardwareLock);
670 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700671 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700672 mHardwareStatus = AUDIO_HW_IDLE;
673 return ret;
674}
675
676bool AudioFlinger::getMicMute() const
677{
Eric Laurenta1884f92011-08-23 08:25:03 -0700678 status_t ret = initCheck();
679 if (ret != NO_ERROR) {
680 return false;
681 }
682
Dima Zavinfce7a472011-04-19 22:30:36 -0700683 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800684 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700685 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700686 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700687 mHardwareStatus = AUDIO_HW_IDLE;
688 return state;
689}
690
691status_t AudioFlinger::setMasterMute(bool muted)
692{
693 // check calling permissions
694 if (!settingsAllowed()) {
695 return PERMISSION_DENIED;
696 }
697
Eric Laurent93575202011-01-18 18:39:02 -0800698 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800699 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700700 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800701 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700702 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700703
704 return NO_ERROR;
705}
706
707float AudioFlinger::masterVolume() const
708{
Glenn Kasten98067102011-12-13 11:47:54 -0800709 Mutex::Autolock _l(mLock);
710 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700711}
712
John Grossman4ff14ba2012-02-08 16:37:41 -0800713float AudioFlinger::masterVolumeSW() const
714{
715 Mutex::Autolock _l(mLock);
716 return masterVolumeSW_l();
717}
718
Mathias Agopian65ab4712010-07-14 17:59:35 -0700719bool AudioFlinger::masterMute() const
720{
Glenn Kasten98067102011-12-13 11:47:54 -0800721 Mutex::Autolock _l(mLock);
722 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700723}
724
John Grossman4ff14ba2012-02-08 16:37:41 -0800725float AudioFlinger::masterVolume_l() const
726{
727 if (MVS_FULL == mMasterVolumeSupportLvl) {
728 float ret_val;
729 AutoMutex lock(mHardwareLock);
730
731 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800732 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
733 (NULL != mPrimaryHardwareDev->get_master_volume),
734 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800735
736 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
737 mHardwareStatus = AUDIO_HW_IDLE;
738 return ret_val;
739 }
740
741 return mMasterVolume;
742}
743
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800744status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
745 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700746{
747 // check calling permissions
748 if (!settingsAllowed()) {
749 return PERMISSION_DENIED;
750 }
751
Glenn Kasten263709e2012-01-06 08:40:01 -0800752 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000753 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700754 return BAD_VALUE;
755 }
756
757 AutoMutex lock(mLock);
758 PlaybackThread *thread = NULL;
759 if (output) {
760 thread = checkPlaybackThread_l(output);
761 if (thread == NULL) {
762 return BAD_VALUE;
763 }
764 }
765
766 mStreamTypes[stream].volume = value;
767
768 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800769 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700770 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700771 }
772 } else {
773 thread->setStreamVolume(stream, value);
774 }
775
776 return NO_ERROR;
777}
778
Glenn Kastenfff6d712012-01-12 16:38:12 -0800779status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700780{
781 // check calling permissions
782 if (!settingsAllowed()) {
783 return PERMISSION_DENIED;
784 }
785
Glenn Kasten263709e2012-01-06 08:40:01 -0800786 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700787 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000788 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700789 return BAD_VALUE;
790 }
791
Eric Laurent93575202011-01-18 18:39:02 -0800792 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700793 mStreamTypes[stream].mute = muted;
794 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700795 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796
797 return NO_ERROR;
798}
799
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800800float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700801{
Glenn Kasten263709e2012-01-06 08:40:01 -0800802 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700803 return 0.0f;
804 }
805
806 AutoMutex lock(mLock);
807 float volume;
808 if (output) {
809 PlaybackThread *thread = checkPlaybackThread_l(output);
810 if (thread == NULL) {
811 return 0.0f;
812 }
813 volume = thread->streamVolume(stream);
814 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800815 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700816 }
817
818 return volume;
819}
820
Glenn Kastenfff6d712012-01-12 16:38:12 -0800821bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700822{
Glenn Kasten263709e2012-01-06 08:40:01 -0800823 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700824 return true;
825 }
826
Glenn Kasten6637baa2012-01-09 09:40:36 -0800827 AutoMutex lock(mLock);
828 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700829}
830
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800831status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700832{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800833 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700834 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
835 // check calling permissions
836 if (!settingsAllowed()) {
837 return PERMISSION_DENIED;
838 }
839
Mathias Agopian65ab4712010-07-14 17:59:35 -0700840 // ioHandle == 0 means the parameters are global to the audio hardware interface
841 if (ioHandle == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700842 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800843 {
844 AutoMutex lock(mHardwareLock);
845 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700846 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
847 audio_hw_device_t *dev = mAudioHwDevs[i];
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800848 status_t result = dev->set_parameters(dev, keyValuePairs.string());
Dima Zavin799a70e2011-04-18 16:57:27 -0700849 final_result = result ?: final_result;
850 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700851 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800852 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700853 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
854 AudioParameter param = AudioParameter(keyValuePairs);
855 String8 value;
856 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
857 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700858 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
859 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700860 for (size_t i = 0; i < mRecordThreads.size(); i++) {
861 sp<RecordThread> thread = mRecordThreads.valueAt(i);
862 RecordThread::RecordTrack *track = thread->track();
863 if (track != NULL) {
864 audio_devices_t device = (audio_devices_t)(
865 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700866 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700867 thread->setEffectSuspended(FX_IID_AEC,
868 suspend,
869 track->sessionId());
870 thread->setEffectSuspended(FX_IID_NS,
871 suspend,
872 track->sessionId());
873 }
874 }
Eric Laurentbee53372011-08-29 12:42:48 -0700875 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700876 }
877 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700878 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700879 }
880
881 // hold a strong ref on thread in case closeOutput() or closeInput() is called
882 // and the thread is exited once the lock is released
883 sp<ThreadBase> thread;
884 {
885 Mutex::Autolock _l(mLock);
886 thread = checkPlaybackThread_l(ioHandle);
887 if (thread == NULL) {
888 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800889 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700890 // indicate output device change to all input threads for pre processing
891 AudioParameter param = AudioParameter(keyValuePairs);
892 int value;
893 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
894 for (size_t i = 0; i < mRecordThreads.size(); i++) {
895 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
896 }
897 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700898 }
899 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800900 if (thread != 0) {
901 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700902 }
903 return BAD_VALUE;
904}
905
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800906String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700907{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800908// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700909// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
910
911 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700912 String8 out_s8;
913
Dima Zavin799a70e2011-04-18 16:57:27 -0700914 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800915 char *s;
916 {
917 AutoMutex lock(mHardwareLock);
918 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700919 audio_hw_device_t *dev = mAudioHwDevs[i];
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800920 s = dev->get_parameters(dev, keys.string());
921 mHardwareStatus = AUDIO_HW_IDLE;
922 }
John Grossmanef7740b2012-02-09 11:28:36 -0800923 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700924 free(s);
925 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700926 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700927 }
928
929 Mutex::Autolock _l(mLock);
930
931 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
932 if (playbackThread != NULL) {
933 return playbackThread->getParameters(keys);
934 }
935 RecordThread *recordThread = checkRecordThread_l(ioHandle);
936 if (recordThread != NULL) {
937 return recordThread->getParameters(keys);
938 }
939 return String8("");
940}
941
Glenn Kastenf587ba52012-01-26 16:25:10 -0800942size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700943{
Eric Laurenta1884f92011-08-23 08:25:03 -0700944 status_t ret = initCheck();
945 if (ret != NO_ERROR) {
946 return 0;
947 }
948
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800949 AutoMutex lock(mHardwareLock);
950 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
951 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
952 mHardwareStatus = AUDIO_HW_IDLE;
953 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700954}
955
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800956unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700957{
958 if (ioHandle == 0) {
959 return 0;
960 }
961
962 Mutex::Autolock _l(mLock);
963
964 RecordThread *recordThread = checkRecordThread_l(ioHandle);
965 if (recordThread != NULL) {
966 return recordThread->getInputFramesLost();
967 }
968 return 0;
969}
970
971status_t AudioFlinger::setVoiceVolume(float value)
972{
Eric Laurenta1884f92011-08-23 08:25:03 -0700973 status_t ret = initCheck();
974 if (ret != NO_ERROR) {
975 return ret;
976 }
977
Mathias Agopian65ab4712010-07-14 17:59:35 -0700978 // check calling permissions
979 if (!settingsAllowed()) {
980 return PERMISSION_DENIED;
981 }
982
983 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800984 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700985 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700986 mHardwareStatus = AUDIO_HW_IDLE;
987
988 return ret;
989}
990
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800991status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
992 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700993{
994 status_t status;
995
996 Mutex::Autolock _l(mLock);
997
998 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
999 if (playbackThread != NULL) {
1000 return playbackThread->getRenderPosition(halFrames, dspFrames);
1001 }
1002
1003 return BAD_VALUE;
1004}
1005
1006void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1007{
1008
1009 Mutex::Autolock _l(mLock);
1010
Glenn Kastenbb001922012-02-03 11:10:26 -08001011 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001012 if (mNotificationClients.indexOfKey(pid) < 0) {
1013 sp<NotificationClient> notificationClient = new NotificationClient(this,
1014 client,
1015 pid);
Steve Block3856b092011-10-20 11:56:00 +01001016 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001017
1018 mNotificationClients.add(pid, notificationClient);
1019
1020 sp<IBinder> binder = client->asBinder();
1021 binder->linkToDeath(notificationClient);
1022
1023 // the config change is always sent from playback or record threads to avoid deadlock
1024 // with AudioSystem::gLock
1025 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1026 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1027 }
1028
1029 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1030 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1031 }
1032 }
1033}
1034
1035void AudioFlinger::removeNotificationClient(pid_t pid)
1036{
1037 Mutex::Autolock _l(mLock);
1038
Glenn Kastena3b09252012-01-20 09:19:01 -08001039 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001040
Steve Block3856b092011-10-20 11:56:00 +01001041 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001042 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001043 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001044 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001045 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001046 ALOGV(" pid %d @ %d", ref->mPid, i);
1047 if (ref->mPid == pid) {
1048 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001049 mAudioSessionRefs.removeAt(i);
1050 delete ref;
1051 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001052 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001053 } else {
1054 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001055 }
1056 }
1057 if (removed) {
1058 purgeStaleEffects_l();
1059 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001060}
1061
1062// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001063void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001064{
1065 size_t size = mNotificationClients.size();
1066 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001067 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1068 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001069 }
1070}
1071
1072// removeClient_l() must be called with AudioFlinger::mLock held
1073void AudioFlinger::removeClient_l(pid_t pid)
1074{
Steve Block3856b092011-10-20 11:56:00 +01001075 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001076 mClients.removeItem(pid);
1077}
1078
1079
1080// ----------------------------------------------------------------------------
1081
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001082AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1083 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001084 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001085 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001086 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
1087 // mChannelMask
1088 mChannelCount(0),
1089 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1090 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001091 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001092 mDevice(device),
1093 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001094{
1095}
1096
1097AudioFlinger::ThreadBase::~ThreadBase()
1098{
1099 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001100 // do not lock the mutex in destructor
1101 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001102 if (mPowerManager != 0) {
1103 sp<IBinder> binder = mPowerManager->asBinder();
1104 binder->unlinkToDeath(mDeathRecipient);
1105 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001106}
1107
1108void AudioFlinger::ThreadBase::exit()
1109{
Steve Block3856b092011-10-20 11:56:00 +01001110 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001111 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001112 // This lock prevents the following race in thread (uniprocessor for illustration):
1113 // if (!exitPending()) {
1114 // // context switch from here to exit()
1115 // // exit() calls requestExit(), what exitPending() observes
1116 // // exit() calls signal(), which is dropped since no waiters
1117 // // context switch back from exit() to here
1118 // mWaitWorkCV.wait(...);
1119 // // now thread is hung
1120 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001121 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001122 requestExit();
1123 mWaitWorkCV.signal();
1124 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001125 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1126 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001127 requestExitAndWait();
1128}
1129
Mathias Agopian65ab4712010-07-14 17:59:35 -07001130status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1131{
1132 status_t status;
1133
Steve Block3856b092011-10-20 11:56:00 +01001134 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001135 Mutex::Autolock _l(mLock);
1136
1137 mNewParameters.add(keyValuePairs);
1138 mWaitWorkCV.signal();
1139 // wait condition with timeout in case the thread loop has exited
1140 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001141 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001142 status = mParamStatus;
1143 mWaitWorkCV.signal();
1144 } else {
1145 status = TIMED_OUT;
1146 }
1147 return status;
1148}
1149
1150void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1151{
1152 Mutex::Autolock _l(mLock);
1153 sendConfigEvent_l(event, param);
1154}
1155
1156// sendConfigEvent_l() must be called with ThreadBase::mLock held
1157void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1158{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001159 ConfigEvent configEvent;
1160 configEvent.mEvent = event;
1161 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001162 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001163 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001164 mWaitWorkCV.signal();
1165}
1166
1167void AudioFlinger::ThreadBase::processConfigEvents()
1168{
1169 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001170 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001171 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001172 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001173 mConfigEvents.removeAt(0);
1174 // release mLock before locking AudioFlinger mLock: lock order is always
1175 // AudioFlinger then ThreadBase to avoid cross deadlock
1176 mLock.unlock();
1177 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001178 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001179 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001180 mLock.lock();
1181 }
1182 mLock.unlock();
1183}
1184
1185status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1186{
1187 const size_t SIZE = 256;
1188 char buffer[SIZE];
1189 String8 result;
1190
1191 bool locked = tryLock(mLock);
1192 if (!locked) {
1193 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1194 write(fd, buffer, strlen(buffer));
1195 }
1196
1197 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1198 result.append(buffer);
1199 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1200 result.append(buffer);
1201 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1202 result.append(buffer);
1203 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1204 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001205 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1206 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001207 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1208 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001209 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001210 result.append(buffer);
1211
1212 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1213 result.append(buffer);
1214 result.append(" Index Command");
1215 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1216 snprintf(buffer, SIZE, "\n %02d ", i);
1217 result.append(buffer);
1218 result.append(mNewParameters[i]);
1219 }
1220
1221 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1222 result.append(buffer);
1223 snprintf(buffer, SIZE, " Index event param\n");
1224 result.append(buffer);
1225 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001226 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001227 result.append(buffer);
1228 }
1229 result.append("\n");
1230
1231 write(fd, result.string(), result.size());
1232
1233 if (locked) {
1234 mLock.unlock();
1235 }
1236 return NO_ERROR;
1237}
1238
Eric Laurent1d2bff02011-07-24 17:49:51 -07001239status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1240{
1241 const size_t SIZE = 256;
1242 char buffer[SIZE];
1243 String8 result;
1244
1245 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1246 write(fd, buffer, strlen(buffer));
1247
1248 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1249 sp<EffectChain> chain = mEffectChains[i];
1250 if (chain != 0) {
1251 chain->dump(fd, args);
1252 }
1253 }
1254 return NO_ERROR;
1255}
1256
Eric Laurentfeb0db62011-07-22 09:04:31 -07001257void AudioFlinger::ThreadBase::acquireWakeLock()
1258{
1259 Mutex::Autolock _l(mLock);
1260 acquireWakeLock_l();
1261}
1262
1263void AudioFlinger::ThreadBase::acquireWakeLock_l()
1264{
1265 if (mPowerManager == 0) {
1266 // use checkService() to avoid blocking if power service is not up yet
1267 sp<IBinder> binder =
1268 defaultServiceManager()->checkService(String16("power"));
1269 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001270 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001271 } else {
1272 mPowerManager = interface_cast<IPowerManager>(binder);
1273 binder->linkToDeath(mDeathRecipient);
1274 }
1275 }
1276 if (mPowerManager != 0) {
1277 sp<IBinder> binder = new BBinder();
1278 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1279 binder,
1280 String16(mName));
1281 if (status == NO_ERROR) {
1282 mWakeLockToken = binder;
1283 }
Steve Block3856b092011-10-20 11:56:00 +01001284 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001285 }
1286}
1287
1288void AudioFlinger::ThreadBase::releaseWakeLock()
1289{
1290 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001291 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001292}
1293
1294void AudioFlinger::ThreadBase::releaseWakeLock_l()
1295{
1296 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001297 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001298 if (mPowerManager != 0) {
1299 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1300 }
1301 mWakeLockToken.clear();
1302 }
1303}
1304
1305void AudioFlinger::ThreadBase::clearPowerManager()
1306{
1307 Mutex::Autolock _l(mLock);
1308 releaseWakeLock_l();
1309 mPowerManager.clear();
1310}
1311
1312void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1313{
1314 sp<ThreadBase> thread = mThread.promote();
1315 if (thread != 0) {
1316 thread->clearPowerManager();
1317 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001318 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001319}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001320
Eric Laurent59255e42011-07-27 19:49:51 -07001321void AudioFlinger::ThreadBase::setEffectSuspended(
1322 const effect_uuid_t *type, bool suspend, int sessionId)
1323{
1324 Mutex::Autolock _l(mLock);
1325 setEffectSuspended_l(type, suspend, sessionId);
1326}
1327
1328void AudioFlinger::ThreadBase::setEffectSuspended_l(
1329 const effect_uuid_t *type, bool suspend, int sessionId)
1330{
Glenn Kasten090f0192012-01-30 13:00:02 -08001331 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001332 if (chain != 0) {
1333 if (type != NULL) {
1334 chain->setEffectSuspended_l(type, suspend);
1335 } else {
1336 chain->setEffectSuspendedAll_l(suspend);
1337 }
1338 }
1339
1340 updateSuspendedSessions_l(type, suspend, sessionId);
1341}
1342
1343void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1344{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001345 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001346 if (index < 0) {
1347 return;
1348 }
1349
1350 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1351 mSuspendedSessions.editValueAt(index);
1352
1353 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001354 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001355 for (int j = 0; j < desc->mRefCount; j++) {
1356 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1357 chain->setEffectSuspendedAll_l(true);
1358 } else {
Steve Block3856b092011-10-20 11:56:00 +01001359 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001360 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001361 chain->setEffectSuspended_l(&desc->mType, true);
1362 }
1363 }
1364 }
1365}
1366
Eric Laurent59255e42011-07-27 19:49:51 -07001367void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1368 bool suspend,
1369 int sessionId)
1370{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001371 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001372
1373 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1374
1375 if (suspend) {
1376 if (index >= 0) {
1377 sessionEffects = mSuspendedSessions.editValueAt(index);
1378 } else {
1379 mSuspendedSessions.add(sessionId, sessionEffects);
1380 }
1381 } else {
1382 if (index < 0) {
1383 return;
1384 }
1385 sessionEffects = mSuspendedSessions.editValueAt(index);
1386 }
1387
1388
1389 int key = EffectChain::kKeyForSuspendAll;
1390 if (type != NULL) {
1391 key = type->timeLow;
1392 }
1393 index = sessionEffects.indexOfKey(key);
1394
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001395 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001396 if (suspend) {
1397 if (index >= 0) {
1398 desc = sessionEffects.valueAt(index);
1399 } else {
1400 desc = new SuspendedSessionDesc();
1401 if (type != NULL) {
1402 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1403 }
1404 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001405 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001406 }
1407 desc->mRefCount++;
1408 } else {
1409 if (index < 0) {
1410 return;
1411 }
1412 desc = sessionEffects.valueAt(index);
1413 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001414 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001415 sessionEffects.removeItemsAt(index);
1416 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001417 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001418 sessionId);
1419 mSuspendedSessions.removeItem(sessionId);
1420 }
1421 }
1422 }
1423 if (!sessionEffects.isEmpty()) {
1424 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1425 }
1426}
1427
1428void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1429 bool enabled,
1430 int sessionId)
1431{
1432 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001433 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1434}
Eric Laurent59255e42011-07-27 19:49:51 -07001435
Eric Laurenta85a74a2011-10-19 11:44:54 -07001436void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1437 bool enabled,
1438 int sessionId)
1439{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001440 if (mType != RECORD) {
1441 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1442 // another session. This gives the priority to well behaved effect control panels
1443 // and applications not using global effects.
1444 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1445 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1446 }
1447 }
Eric Laurent59255e42011-07-27 19:49:51 -07001448
1449 sp<EffectChain> chain = getEffectChain_l(sessionId);
1450 if (chain != 0) {
1451 chain->checkSuspendOnEffectEnabled(effect, enabled);
1452 }
1453}
1454
Mathias Agopian65ab4712010-07-14 17:59:35 -07001455// ----------------------------------------------------------------------------
1456
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001457AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1458 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001459 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001460 uint32_t device,
1461 type_t type)
1462 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001463 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1464 // Assumes constructor is called by AudioFlinger with it's mLock held,
1465 // but it would be safer to explicitly pass initial masterMute as parameter
1466 mMasterMute(audioFlinger->masterMute_l()),
1467 // mStreamTypes[] initialized in constructor body
1468 mOutput(output),
1469 // Assumes constructor is called by AudioFlinger with it's mLock held,
1470 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001471 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001472 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001473 mMixerStatus(MIXER_IDLE),
Glenn Kasten66fcab92012-02-24 14:59:21 -08001474 mPrevMixerStatus(MIXER_IDLE),
1475 standbyDelay(AudioFlinger::mStandbyTimeInNsecs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001476{
Glenn Kasten480b4682012-02-28 12:30:08 -08001477 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001478
Mathias Agopian65ab4712010-07-14 17:59:35 -07001479 readOutputParameters();
1480
Glenn Kasten263709e2012-01-06 08:40:01 -08001481 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001482 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1483 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1484 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001485 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1486 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001487 // initialized by stream_type_t default constructor
1488 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001489 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001490 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1491 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001492}
1493
1494AudioFlinger::PlaybackThread::~PlaybackThread()
1495{
1496 delete [] mMixBuffer;
1497}
1498
1499status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1500{
1501 dumpInternals(fd, args);
1502 dumpTracks(fd, args);
1503 dumpEffectChains(fd, args);
1504 return NO_ERROR;
1505}
1506
1507status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1508{
1509 const size_t SIZE = 256;
1510 char buffer[SIZE];
1511 String8 result;
1512
1513 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1514 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001515 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001516 for (size_t i = 0; i < mTracks.size(); ++i) {
1517 sp<Track> track = mTracks[i];
1518 if (track != 0) {
1519 track->dump(buffer, SIZE);
1520 result.append(buffer);
1521 }
1522 }
1523
1524 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1525 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001526 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001527 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001528 sp<Track> track = mActiveTracks[i].promote();
1529 if (track != 0) {
1530 track->dump(buffer, SIZE);
1531 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001532 }
1533 }
1534 write(fd, result.string(), result.size());
1535 return NO_ERROR;
1536}
1537
Mathias Agopian65ab4712010-07-14 17:59:35 -07001538status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1539{
1540 const size_t SIZE = 256;
1541 char buffer[SIZE];
1542 String8 result;
1543
1544 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1545 result.append(buffer);
1546 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1547 result.append(buffer);
1548 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1549 result.append(buffer);
1550 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1551 result.append(buffer);
1552 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1553 result.append(buffer);
1554 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1555 result.append(buffer);
1556 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1557 result.append(buffer);
1558 write(fd, result.string(), result.size());
1559
1560 dumpBase(fd, args);
1561
1562 return NO_ERROR;
1563}
1564
1565// Thread virtuals
1566status_t AudioFlinger::PlaybackThread::readyToRun()
1567{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001568 status_t status = initCheck();
1569 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001570 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001571 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001572 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001573 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001574 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001575}
1576
1577void AudioFlinger::PlaybackThread::onFirstRef()
1578{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001579 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001580}
1581
1582// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1583sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1584 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001585 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001586 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001587 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001588 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001589 int frameCount,
1590 const sp<IMemory>& sharedBuffer,
1591 int sessionId,
John Grossman4ff14ba2012-02-08 16:37:41 -08001592 bool isTimed,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001593 status_t *status)
1594{
1595 sp<Track> track;
1596 status_t lStatus;
1597
1598 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001599 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1600 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001601 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001602 "for output %p with format %d",
1603 sampleRate, format, channelMask, mOutput, mFormat);
1604 lStatus = BAD_VALUE;
1605 goto Exit;
1606 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001607 }
1608 } else {
1609 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1610 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001611 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001612 lStatus = BAD_VALUE;
1613 goto Exit;
1614 }
1615 }
1616
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001617 lStatus = initCheck();
1618 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001619 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001620 goto Exit;
1621 }
1622
1623 { // scope for mLock
1624 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001625
1626 // all tracks in same audio session must share the same routing strategy otherwise
1627 // conflicts will happen when tracks are moved from one output to another by audio policy
1628 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001629 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001630 for (size_t i = 0; i < mTracks.size(); ++i) {
1631 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001632 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001633 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001634 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001635 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001636 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001637 lStatus = BAD_VALUE;
1638 goto Exit;
1639 }
1640 }
1641 }
1642
John Grossman4ff14ba2012-02-08 16:37:41 -08001643 if (!isTimed) {
1644 track = new Track(this, client, streamType, sampleRate, format,
1645 channelMask, frameCount, sharedBuffer, sessionId);
1646 } else {
1647 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1648 channelMask, frameCount, sharedBuffer, sessionId);
1649 }
1650 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001651 lStatus = NO_MEMORY;
1652 goto Exit;
1653 }
1654 mTracks.add(track);
1655
1656 sp<EffectChain> chain = getEffectChain_l(sessionId);
1657 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001658 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001659 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001660 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001661 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001662 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001663
1664 // invalidate track immediately if the stream type was moved to another thread since
1665 // createTrack() was called by the client process.
1666 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001667 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001668 this, streamType);
Eric Laurent9f6530f2011-08-30 10:18:54 -07001669 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1670 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001671 }
1672 lStatus = NO_ERROR;
1673
1674Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001675 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001676 *status = lStatus;
1677 }
1678 return track;
1679}
1680
1681uint32_t AudioFlinger::PlaybackThread::latency() const
1682{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001683 Mutex::Autolock _l(mLock);
1684 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001685 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001686 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001687 return 0;
1688 }
1689}
1690
Glenn Kasten6637baa2012-01-09 09:40:36 -08001691void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001692{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001693 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001694 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695}
1696
Glenn Kasten6637baa2012-01-09 09:40:36 -08001697void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001698{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001699 Mutex::Autolock _l(mLock);
1700 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001701}
1702
Glenn Kasten6637baa2012-01-09 09:40:36 -08001703void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001704{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001705 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001706 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001707}
1708
Glenn Kasten6637baa2012-01-09 09:40:36 -08001709void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001710{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001711 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001712 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001713}
1714
Glenn Kastenfff6d712012-01-12 16:38:12 -08001715float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001716{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001717 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001718 return mStreamTypes[stream].volume;
1719}
1720
Mathias Agopian65ab4712010-07-14 17:59:35 -07001721// addTrack_l() must be called with ThreadBase::mLock held
1722status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1723{
1724 status_t status = ALREADY_EXISTS;
1725
1726 // set retry count for buffer fill
1727 track->mRetryCount = kMaxTrackStartupRetries;
1728 if (mActiveTracks.indexOf(track) < 0) {
1729 // the track is newly added, make sure it fills up all its
1730 // buffers before playing. This is to ensure the client will
1731 // effectively get the latency it requested.
1732 track->mFillingUpStatus = Track::FS_FILLING;
1733 track->mResetDone = false;
1734 mActiveTracks.add(track);
1735 if (track->mainBuffer() != mMixBuffer) {
1736 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1737 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001738 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001739 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001740 }
1741 }
1742
1743 status = NO_ERROR;
1744 }
1745
Steve Block3856b092011-10-20 11:56:00 +01001746 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001747 mWaitWorkCV.broadcast();
1748
1749 return status;
1750}
1751
1752// destroyTrack_l() must be called with ThreadBase::mLock held
1753void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1754{
1755 track->mState = TrackBase::TERMINATED;
1756 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001757 removeTrack_l(track);
1758 }
1759}
1760
1761void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1762{
1763 mTracks.remove(track);
1764 deleteTrackName_l(track->name());
1765 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1766 if (chain != 0) {
1767 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001768 }
1769}
1770
1771String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1772{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001773 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001774 char *s;
1775
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001776 Mutex::Autolock _l(mLock);
1777 if (initCheck() != NO_ERROR) {
1778 return out_s8;
1779 }
1780
Dima Zavin799a70e2011-04-18 16:57:27 -07001781 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001782 out_s8 = String8(s);
1783 free(s);
1784 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001785}
1786
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001787// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001788void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1789 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001790 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001791
Steve Block3856b092011-10-20 11:56:00 +01001792 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001793
1794 switch (event) {
1795 case AudioSystem::OUTPUT_OPENED:
1796 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001797 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001798 desc.samplingRate = mSampleRate;
1799 desc.format = mFormat;
1800 desc.frameCount = mFrameCount;
1801 desc.latency = latency();
1802 param2 = &desc;
1803 break;
1804
1805 case AudioSystem::STREAM_CONFIG_CHANGED:
1806 param2 = &param;
1807 case AudioSystem::OUTPUT_CLOSED:
1808 default:
1809 break;
1810 }
1811 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1812}
1813
1814void AudioFlinger::PlaybackThread::readOutputParameters()
1815{
Dima Zavin799a70e2011-04-18 16:57:27 -07001816 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001817 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1818 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001819 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001820 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001821 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001822
1823 // FIXME - Current mixer implementation only supports stereo output: Always
1824 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001825 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001826 mMixBuffer = new int16_t[mFrameCount * 2];
1827 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1828
Eric Laurentde070132010-07-13 04:45:46 -07001829 // force reconfiguration of effect chains and engines to take new buffer size and audio
1830 // parameters into account
1831 // Note that mLock is not held when readOutputParameters() is called from the constructor
1832 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1833 // matter.
1834 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1835 Vector< sp<EffectChain> > effectChains = mEffectChains;
1836 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001837 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001838 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001839}
1840
1841status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1842{
Glenn Kastena0d68332012-01-27 16:47:15 -08001843 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001844 return BAD_VALUE;
1845 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001846 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001847 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001848 return INVALID_OPERATION;
1849 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001850 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001851
Dima Zavin799a70e2011-04-18 16:57:27 -07001852 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853}
1854
Eric Laurent39e94f82010-07-28 01:32:47 -07001855uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856{
1857 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001858 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001859 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001860 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861 }
1862
1863 for (size_t i = 0; i < mTracks.size(); ++i) {
1864 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001865 if (sessionId == track->sessionId() &&
1866 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001867 result |= TRACK_SESSION;
1868 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001869 }
1870 }
1871
Eric Laurent39e94f82010-07-28 01:32:47 -07001872 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001873}
1874
Eric Laurentde070132010-07-13 04:45:46 -07001875uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1876{
Dima Zavinfce7a472011-04-19 22:30:36 -07001877 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001878 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001879 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1880 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001881 }
1882 for (size_t i = 0; i < mTracks.size(); i++) {
1883 sp<Track> track = mTracks[i];
1884 if (sessionId == track->sessionId() &&
1885 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001886 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07001887 }
1888 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001889 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001890}
1891
Mathias Agopian65ab4712010-07-14 17:59:35 -07001892
Glenn Kastenaed850d2012-01-26 09:46:34 -08001893AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001894{
1895 Mutex::Autolock _l(mLock);
1896 return mOutput;
1897}
1898
1899AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1900{
1901 Mutex::Autolock _l(mLock);
1902 AudioStreamOut *output = mOutput;
1903 mOutput = NULL;
1904 return output;
1905}
1906
1907// this method must always be called either with ThreadBase mLock held or inside the thread loop
1908audio_stream_t* AudioFlinger::PlaybackThread::stream()
1909{
1910 if (mOutput == NULL) {
1911 return NULL;
1912 }
1913 return &mOutput->stream->common;
1914}
1915
Eric Laurent162b40b2011-12-05 09:47:19 -08001916uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1917{
1918 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1919 // decoding and transfer time. So sleeping for half of the latency would likely cause
1920 // underruns
1921 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1922 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1923 } else {
1924 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1925 }
1926}
1927
Mathias Agopian65ab4712010-07-14 17:59:35 -07001928// ----------------------------------------------------------------------------
1929
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001930AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001931 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten000f0e32012-03-01 17:10:56 -08001932 : PlaybackThread(audioFlinger, output, id, device, type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001933{
Glenn Kasten000f0e32012-03-01 17:10:56 -08001934 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001935 // FIXME - Current mixer implementation only supports stereo output
1936 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001937 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001938 }
1939}
1940
1941AudioFlinger::MixerThread::~MixerThread()
1942{
1943 delete mAudioMixer;
1944}
1945
Glenn Kasten83efdd02012-02-24 07:21:32 -08001946class CpuStats {
1947public:
1948 void sample();
1949#ifdef DEBUG_CPU_USAGE
1950private:
1951 ThreadCpuUsage mCpu;
1952#endif
1953};
1954
1955void CpuStats::sample() {
1956#ifdef DEBUG_CPU_USAGE
1957 const CentralTendencyStatistics& stats = mCpu.statistics();
1958 mCpu.sampleAndEnable();
1959 unsigned n = stats.n();
1960 // mCpu.elapsed() is expensive, so don't call it every loop
1961 if ((n & 127) == 1) {
1962 long long elapsed = mCpu.elapsed();
1963 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1964 double perLoop = elapsed / (double) n;
1965 double perLoop100 = perLoop * 0.01;
1966 double mean = stats.mean();
1967 double stddev = stats.stddev();
1968 double minimum = stats.minimum();
1969 double maximum = stats.maximum();
1970 mCpu.resetStatistics();
1971 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",
1972 elapsed * .000000001, n, perLoop * .000001,
1973 mean * .001,
1974 stddev * .001,
1975 minimum * .001,
1976 maximum * .001,
1977 mean / perLoop100,
1978 stddev / perLoop100,
1979 minimum / perLoop100,
1980 maximum / perLoop100);
1981 }
1982 }
1983#endif
1984};
1985
Glenn Kasten37d825e2012-02-24 07:21:48 -08001986void AudioFlinger::PlaybackThread::checkSilentMode_l()
1987{
1988 if (!mMasterMute) {
1989 char value[PROPERTY_VALUE_MAX];
1990 if (property_get("ro.audio.silent", value, "0") > 0) {
1991 char *endptr;
1992 unsigned long ul = strtoul(value, &endptr, 0);
1993 if (*endptr == '\0' && ul != 0) {
1994 ALOGD("Silence is golden");
1995 // The setprop command will not allow a property to be changed after
1996 // the first time it is set, so we don't have to worry about un-muting.
1997 setMasterMute_l(true);
1998 }
1999 }
2000 }
2001}
2002
Glenn Kasten000f0e32012-03-01 17:10:56 -08002003bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002004{
2005 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002006
Glenn Kasten000f0e32012-03-01 17:10:56 -08002007 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002008
2009 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002010 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002011if (mType == MIXER) {
2012 longStandbyExit = false;
2013}
Glenn Kasten688a6402012-02-29 07:57:06 -08002014
Glenn Kasten000f0e32012-03-01 17:10:56 -08002015 // DUPLICATING
2016 // FIXME could this be made local to while loop?
2017 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002018
Glenn Kasten66fcab92012-02-24 14:59:21 -08002019 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002020 sleepTime = idleSleepTime;
2021
2022if (mType == MIXER) {
2023 sleepTimeShift = 0;
2024}
2025
2026 // MIXER
Glenn Kasten83efdd02012-02-24 07:21:32 -08002027 CpuStats cpuStats;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002028
Eric Laurentfeb0db62011-07-22 09:04:31 -07002029 acquireWakeLock();
2030
Mathias Agopian65ab4712010-07-14 17:59:35 -07002031 while (!exitPending())
2032 {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002033if (mType == MIXER) {
Glenn Kasten83efdd02012-02-24 07:21:32 -08002034 cpuStats.sample();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002035}
Glenn Kasten688a6402012-02-29 07:57:06 -08002036
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002037 Vector< sp<EffectChain> > effectChains;
2038
Mathias Agopian65ab4712010-07-14 17:59:35 -07002039 processConfigEvents();
2040
Mathias Agopian65ab4712010-07-14 17:59:35 -07002041 { // scope for mLock
2042
2043 Mutex::Autolock _l(mLock);
2044
2045 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002046 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002047 }
2048
Glenn Kastenfa26a852012-03-06 11:28:04 -08002049 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002050
Mathias Agopian65ab4712010-07-14 17:59:35 -07002051 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002052 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002053 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002054 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002055
2056 threadLoop_standby();
2057
Mathias Agopian65ab4712010-07-14 17:59:35 -07002058 mStandby = true;
2059 mBytesWritten = 0;
2060 }
2061
Glenn Kasten3e074702012-02-28 18:40:35 -08002062 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002063 // we're about to wait, flush the binder command buffer
2064 IPCThreadState::self()->flushCommands();
2065
Glenn Kastenfa26a852012-03-06 11:28:04 -08002066 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002067
Mathias Agopian65ab4712010-07-14 17:59:35 -07002068 if (exitPending()) break;
2069
Eric Laurentfeb0db62011-07-22 09:04:31 -07002070 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002071 // wait until we have something to do...
Glenn Kastenc0b52832012-02-24 11:18:09 -08002072 ALOGV("Thread %p type %d TID %d going to sleep", this, mType, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002073 mWaitWorkCV.wait(mLock);
Glenn Kastenc0b52832012-02-24 11:18:09 -08002074 ALOGV("Thread %p type %d TID %d waking up", this, mType, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002075 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002076
Eric Laurent27741442012-01-17 19:20:12 -08002077 mPrevMixerStatus = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002078
Glenn Kasten37d825e2012-02-24 07:21:48 -08002079 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002080
Glenn Kasten000f0e32012-03-01 17:10:56 -08002081 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002082 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002083 if (mType == MIXER) {
2084 sleepTimeShift = 0;
2085 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002086
Mathias Agopian65ab4712010-07-14 17:59:35 -07002087 continue;
2088 }
2089 }
2090
Glenn Kastenfec279f2012-03-08 07:47:15 -08002091 mixer_state newMixerStatus = prepareTracks_l(&tracksToRemove);
2092 // Shift in the new status; this could be a queue if it's
2093 // useful to filter the mixer status over several cycles.
2094 mPrevMixerStatus = mMixerStatus;
2095 mMixerStatus = newMixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002096
2097 // prevent any changes in effect chain list and in each effect chain
2098 // during mixing and effect process as the audio buffers could be deleted
2099 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002100 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002101 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002102
Glenn Kastenfec279f2012-03-08 07:47:15 -08002103 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002104 threadLoop_mix();
2105 } else {
2106 threadLoop_sleepTime();
2107 }
2108
2109 if (mSuspended > 0) {
2110 sleepTime = suspendSleepTimeUs();
2111 }
2112
2113 // only process effects if we're going to write
2114 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002115 for (size_t i = 0; i < effectChains.size(); i ++) {
2116 effectChains[i]->process_l();
2117 }
2118 }
2119
2120 // enable changes in effect chain
2121 unlockEffectChains(effectChains);
2122
2123 // sleepTime == 0 means we must write to audio hardware
2124 if (sleepTime == 0) {
2125
2126 threadLoop_write();
2127
2128if (mType == MIXER) {
2129 // write blocked detection
2130 nsecs_t now = systemTime();
2131 nsecs_t delta = now - mLastWriteTime;
2132 if (!mStandby && delta > maxPeriod) {
2133 mNumDelayedWrites++;
2134 if ((now - lastWarning) > kWarningThrottleNs) {
2135 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2136 ns2ms(delta), mNumDelayedWrites, this);
2137 lastWarning = now;
2138 }
2139 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2140 // a different threshold. Or completely removed for what it is worth anyway...
2141 if (mStandby) {
2142 longStandbyExit = true;
2143 }
2144 }
2145}
2146
2147 mStandby = false;
2148 } else {
2149 usleep(sleepTime);
2150 }
2151
2152 // finally let go of removed track(s), without the lock held
2153 // since we can't guarantee the destructors won't acquire that
2154 // same lock.
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002155 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002156
Glenn Kastenfa26a852012-03-06 11:28:04 -08002157 // FIXME I don't understand the need for this here;
2158 // it was in the original code but maybe the
2159 // assignment in saveOutputTracks() makes this unnecessary?
2160 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002161
2162 // Effect chains will be actually deleted here if they were removed from
2163 // mEffectChains list during mixing or effects processing
2164 effectChains.clear();
2165
2166 // FIXME Note that the above .clear() is no longer necessary since effectChains
2167 // is now local to this block, but will keep it for now (at least until merge done).
2168 }
2169
2170if (mType == MIXER || mType == DIRECT) {
2171 // put output stream into standby mode
2172 if (!mStandby) {
2173 mOutput->stream->common.standby(&mOutput->stream->common);
2174 }
2175}
2176if (mType == DUPLICATING) {
2177 // for DuplicatingThread, standby mode is handled by the outputTracks
2178}
2179
2180 releaseWakeLock();
2181
2182 ALOGV("Thread %p type %d exiting", this, mType);
2183 return false;
2184}
2185
2186// shared by MIXER and DIRECT, overridden by DUPLICATING
2187void AudioFlinger::PlaybackThread::threadLoop_write()
2188{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002189 // FIXME rewrite to reduce number of system calls
2190 mLastWriteTime = systemTime();
2191 mInWrite = true;
2192 mBytesWritten += mixBufferSize;
2193 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2194 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2195 mNumWrites++;
2196 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002197}
2198
2199// shared by MIXER and DIRECT, overridden by DUPLICATING
2200void AudioFlinger::PlaybackThread::threadLoop_standby()
2201{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002202 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2203 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002204}
2205
2206void AudioFlinger::MixerThread::threadLoop_mix()
2207{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002208 // obtain the presentation timestamp of the next output buffer
2209 int64_t pts;
2210 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002211
Glenn Kasten952eeb22012-03-06 11:30:57 -08002212 if (NULL != mOutput->stream->get_next_write_timestamp) {
2213 status = mOutput->stream->get_next_write_timestamp(
2214 mOutput->stream, &pts);
2215 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002216
Glenn Kasten952eeb22012-03-06 11:30:57 -08002217 if (status != NO_ERROR) {
2218 pts = AudioBufferProvider::kInvalidPTS;
2219 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002220
Glenn Kasten952eeb22012-03-06 11:30:57 -08002221 // mix buffers...
2222 mAudioMixer->process(pts);
2223 // increase sleep time progressively when application underrun condition clears.
2224 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2225 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2226 // such that we would underrun the audio HAL.
2227 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2228 sleepTimeShift--;
2229 }
2230 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002231 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002232 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002233}
2234
2235void AudioFlinger::MixerThread::threadLoop_sleepTime()
2236{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002237 // If no tracks are ready, sleep once for the duration of an output
2238 // buffer size, then write 0s to the output
2239 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002240 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002241 sleepTime = activeSleepTime >> sleepTimeShift;
2242 if (sleepTime < kMinThreadSleepTimeUs) {
2243 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002244 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002245 // reduce sleep time in case of consecutive application underruns to avoid
2246 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2247 // duration we would end up writing less data than needed by the audio HAL if
2248 // the condition persists.
2249 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2250 sleepTimeShift++;
2251 }
2252 } else {
2253 sleepTime = idleSleepTime;
2254 }
2255 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002256 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002257 memset (mMixBuffer, 0, mixBufferSize);
2258 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002259 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002260 }
2261 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002262}
2263
2264// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002265AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002266 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002267{
2268
Glenn Kasten29c23c32012-01-26 13:37:52 -08002269 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002270 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002271 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002272 size_t mixedTracks = 0;
2273 size_t tracksWithEffect = 0;
2274
2275 float masterVolume = mMasterVolume;
2276 bool masterMute = mMasterMute;
2277
Eric Laurent571d49c2010-08-11 05:20:11 -07002278 if (masterMute) {
2279 masterVolume = 0;
2280 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002281 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002282 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002283 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002284 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002285 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002286 masterVolume = (float)((v + (1 << 23)) >> 24);
2287 chain.clear();
2288 }
2289
2290 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002291 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002292 if (t == 0) continue;
2293
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002294 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002295 Track* const track = t.get();
2296 audio_track_cblk_t* cblk = track->cblk();
2297
2298 // The first time a track is added we wait
2299 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002300 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002301 // make sure that we have enough frames to mix one full buffer.
2302 // enforce this condition only once to enable draining the buffer in case the client
2303 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002304 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002305 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002306 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002307 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002308 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002309 if (t->sampleRate() == (int)mSampleRate) {
2310 minFrames = mFrameCount;
2311 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002312 // +1 for rounding and +1 for additional sample needed for interpolation
2313 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2314 // add frames already consumed but not yet released by the resampler
2315 // because cblk->framesReady() will include these frames
2316 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2317 // the minimum track buffer size is normally twice the number of frames necessary
2318 // to fill one buffer and the resampler should not leave more than one buffer worth
2319 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002320 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002321 }
2322 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002323 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002324 !track->isPaused() && !track->isTerminated())
2325 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002326 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002327
2328 mixedTracks++;
2329
2330 // track->mainBuffer() != mMixBuffer means there is an effect chain
2331 // connected to the track
2332 chain.clear();
2333 if (track->mainBuffer() != mMixBuffer) {
2334 chain = getEffectChain_l(track->sessionId());
2335 // Delegate volume control to effect in track effect chain if needed
2336 if (chain != 0) {
2337 tracksWithEffect++;
2338 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002339 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002340 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002341 }
2342 }
2343
2344
2345 int param = AudioMixer::VOLUME;
2346 if (track->mFillingUpStatus == Track::FS_FILLED) {
2347 // no ramp for the first volume setting
2348 track->mFillingUpStatus = Track::FS_ACTIVE;
2349 if (track->mState == TrackBase::RESUMING) {
2350 track->mState = TrackBase::ACTIVE;
2351 param = AudioMixer::RAMP_VOLUME;
2352 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002353 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002354 } else if (cblk->server != 0) {
2355 // If the track is stopped before the first frame was mixed,
2356 // do not apply ramp
2357 param = AudioMixer::RAMP_VOLUME;
2358 }
2359
2360 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002361 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002362 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002363 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002364 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002365 if (track->isPausing()) {
2366 track->setPaused();
2367 }
2368 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002369
Mathias Agopian65ab4712010-07-14 17:59:35 -07002370 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002371 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002372 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002373 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002374 vl = vlr & 0xFFFF;
2375 vr = vlr >> 16;
2376 // track volumes come from shared memory, so can't be trusted and must be clamped
2377 if (vl > MAX_GAIN_INT) {
2378 ALOGV("Track left volume out of range: %04X", vl);
2379 vl = MAX_GAIN_INT;
2380 }
2381 if (vr > MAX_GAIN_INT) {
2382 ALOGV("Track right volume out of range: %04X", vr);
2383 vr = MAX_GAIN_INT;
2384 }
2385 // now apply the master volume and stream type volume
2386 vl = (uint32_t)(v * vl) << 12;
2387 vr = (uint32_t)(v * vr) << 12;
2388 // assuming master volume and stream type volume each go up to 1.0,
2389 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002390
Glenn Kasten05632a52012-01-03 14:22:33 -08002391 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2392 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002393 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002394 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002395 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002396 }
2397 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002398 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002399 // Delegate volume control to effect in track effect chain if needed
2400 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2401 // Do not ramp volume if volume is controlled by effect
2402 param = AudioMixer::VOLUME;
2403 track->mHasVolumeController = true;
2404 } else {
2405 // force no volume ramp when volume controller was just disabled or removed
2406 // from effect chain to avoid volume spike
2407 if (track->mHasVolumeController) {
2408 param = AudioMixer::VOLUME;
2409 }
2410 track->mHasVolumeController = false;
2411 }
2412
2413 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002414 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002415 vl = (vl + (1 << 11)) >> 12;
2416 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2417 vr = (vr + (1 << 11)) >> 12;
2418 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002419
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002420 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
Mathias Agopian65ab4712010-07-14 17:59:35 -07002421
Mathias Agopian65ab4712010-07-14 17:59:35 -07002422 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002423 mAudioMixer->setBufferProvider(name, track);
2424 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002425
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002426 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2427 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2428 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002429 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002430 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002431 AudioMixer::TRACK,
2432 AudioMixer::FORMAT, (void *)track->format());
2433 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002434 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002435 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002436 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002437 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002438 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002439 AudioMixer::RESAMPLE,
2440 AudioMixer::SAMPLE_RATE,
2441 (void *)(cblk->sampleRate));
2442 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002443 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002444 AudioMixer::TRACK,
2445 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2446 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002447 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002448 AudioMixer::TRACK,
2449 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2450
2451 // reset retry count
2452 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002453 // If one track is ready, set the mixer ready if:
2454 // - the mixer was not ready during previous round OR
2455 // - no other track is not ready
2456 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2457 mixerStatus != MIXER_TRACKS_ENABLED) {
2458 mixerStatus = MIXER_TRACKS_READY;
2459 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002460 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002461 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002462 if (track->isStopped()) {
2463 track->reset();
2464 }
2465 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2466 // We have consumed all the buffers of this track.
2467 // Remove it from the list of active tracks.
2468 tracksToRemove->add(track);
2469 } else {
2470 // No buffers for this track. Give it a few chances to
2471 // fill a buffer, then remove it from active list.
2472 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002473 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002474 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002475 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002476 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002477 // If one track is not ready, mark the mixer also not ready if:
2478 // - the mixer was ready during previous round OR
2479 // - no other track is ready
2480 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2481 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002482 mixerStatus = MIXER_TRACKS_ENABLED;
2483 }
2484 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002485 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002486 }
2487 }
2488
2489 // remove all the tracks that need to be...
2490 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002491 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002492 for (size_t i=0 ; i<count ; i++) {
2493 const sp<Track>& track = tracksToRemove->itemAt(i);
2494 mActiveTracks.remove(track);
2495 if (track->mainBuffer() != mMixBuffer) {
2496 chain = getEffectChain_l(track->sessionId());
2497 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002498 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002499 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002500 }
2501 }
2502 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002503 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002504 }
2505 }
2506 }
2507
2508 // mix buffer must be cleared if all tracks are connected to an
2509 // effect chain as in this case the mixer will not write to
2510 // mix buffer and track effects will accumulate into it
2511 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2512 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2513 }
2514
2515 return mixerStatus;
2516}
2517
Glenn Kasten66fcab92012-02-24 14:59:21 -08002518/*
2519The derived values that are cached:
2520 - mixBufferSize from frame count * frame size
2521 - activeSleepTime from activeSleepTimeUs()
2522 - idleSleepTime from idleSleepTimeUs()
2523 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2524 - maxPeriod from frame count and sample rate (MIXER only)
2525
2526The parameters that affect these derived values are:
2527 - frame count
2528 - frame size
2529 - sample rate
2530 - device type: A2DP or not
2531 - device latency
2532 - format: PCM or not
2533 - active sleep time
2534 - idle sleep time
2535*/
2536
2537void AudioFlinger::PlaybackThread::cacheParameters_l()
2538{
2539 mixBufferSize = mFrameCount * mFrameSize;
2540 activeSleepTime = activeSleepTimeUs();
2541 idleSleepTime = idleSleepTimeUs();
2542}
2543
Glenn Kastenfff6d712012-01-12 16:38:12 -08002544void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002545{
Steve Block3856b092011-10-20 11:56:00 +01002546 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002547 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002548 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002549
Mathias Agopian65ab4712010-07-14 17:59:35 -07002550 size_t size = mTracks.size();
2551 for (size_t i = 0; i < size; i++) {
2552 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08002553 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002554 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002555 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002556 }
2557 }
2558}
2559
Glenn Kastenfff6d712012-01-12 16:38:12 -08002560void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002561{
Steve Block3856b092011-10-20 11:56:00 +01002562 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002563 this, streamType, valid);
2564 Mutex::Autolock _l(mLock);
2565
2566 mStreamTypes[streamType].valid = valid;
2567}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002568
2569// getTrackName_l() must be called with ThreadBase::mLock held
2570int AudioFlinger::MixerThread::getTrackName_l()
2571{
2572 return mAudioMixer->getTrackName();
2573}
2574
2575// deleteTrackName_l() must be called with ThreadBase::mLock held
2576void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2577{
Steve Block3856b092011-10-20 11:56:00 +01002578 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002579 mAudioMixer->deleteTrackName(name);
2580}
2581
2582// checkForNewParameters_l() must be called with ThreadBase::mLock held
2583bool AudioFlinger::MixerThread::checkForNewParameters_l()
2584{
2585 bool reconfig = false;
2586
2587 while (!mNewParameters.isEmpty()) {
2588 status_t status = NO_ERROR;
2589 String8 keyValuePair = mNewParameters[0];
2590 AudioParameter param = AudioParameter(keyValuePair);
2591 int value;
2592
2593 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2594 reconfig = true;
2595 }
2596 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002597 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002598 status = BAD_VALUE;
2599 } else {
2600 reconfig = true;
2601 }
2602 }
2603 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002604 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002605 status = BAD_VALUE;
2606 } else {
2607 reconfig = true;
2608 }
2609 }
2610 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2611 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002612 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002613 // if frame count is changed after track creation
2614 if (!mTracks.isEmpty()) {
2615 status = INVALID_OPERATION;
2616 } else {
2617 reconfig = true;
2618 }
2619 }
2620 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07002621#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08002622 // when changing the audio output device, call addBatteryData to notify
2623 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002624 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002625 uint32_t params = 0;
2626 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002627 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002628 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2629 }
2630
2631 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002632 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002633 // check if any other device (except speaker) is on
2634 if (value & deviceWithoutSpeaker ) {
2635 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2636 }
2637
2638 if (params != 0) {
2639 addBatteryData(params);
2640 }
2641 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07002642#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08002643
Mathias Agopian65ab4712010-07-14 17:59:35 -07002644 // forward device change to effects that have requested to be
2645 // aware of attached audio device.
2646 mDevice = (uint32_t)value;
2647 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002648 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002649 }
2650 }
2651
2652 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002653 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002654 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002655 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002656 mOutput->stream->common.standby(&mOutput->stream->common);
2657 mStandby = true;
2658 mBytesWritten = 0;
2659 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002660 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002661 }
2662 if (status == NO_ERROR && reconfig) {
2663 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002664 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2665 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002666 readOutputParameters();
2667 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2668 for (size_t i = 0; i < mTracks.size() ; i++) {
2669 int name = getTrackName_l();
2670 if (name < 0) break;
2671 mTracks[i]->mName = name;
2672 // limit track sample rate to 2 x new output sample rate
2673 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2674 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2675 }
2676 }
2677 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2678 }
2679 }
2680
2681 mNewParameters.removeAt(0);
2682
2683 mParamStatus = status;
2684 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002685 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2686 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002687 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002688 }
2689 return reconfig;
2690}
2691
2692status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2693{
2694 const size_t SIZE = 256;
2695 char buffer[SIZE];
2696 String8 result;
2697
2698 PlaybackThread::dumpInternals(fd, args);
2699
2700 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2701 result.append(buffer);
2702 write(fd, result.string(), result.size());
2703 return NO_ERROR;
2704}
2705
Mathias Agopian65ab4712010-07-14 17:59:35 -07002706uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2707{
Eric Laurent60e18242010-07-29 06:50:24 -07002708 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002709}
2710
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002711uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2712{
2713 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2714}
2715
Glenn Kasten66fcab92012-02-24 14:59:21 -08002716void AudioFlinger::MixerThread::cacheParameters_l()
2717{
2718 PlaybackThread::cacheParameters_l();
2719
2720 // FIXME: Relaxed timing because of a certain device that can't meet latency
2721 // Should be reduced to 2x after the vendor fixes the driver issue
2722 // increase threshold again due to low power audio mode. The way this warning
2723 // threshold is calculated and its usefulness should be reconsidered anyway.
2724 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
2725}
2726
Mathias Agopian65ab4712010-07-14 17:59:35 -07002727// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002728AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2729 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002730 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002731 // mLeftVolFloat, mRightVolFloat
2732 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002733{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002734}
2735
2736AudioFlinger::DirectOutputThread::~DirectOutputThread()
2737{
2738}
2739
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002740AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
2741 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08002742)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002743{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002744 sp<Track> trackToRemove;
2745
Glenn Kastenfec279f2012-03-08 07:47:15 -08002746 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002747
Glenn Kasten952eeb22012-03-06 11:30:57 -08002748 // find out which tracks need to be processed
2749 if (mActiveTracks.size() != 0) {
2750 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08002751 // The track died recently
2752 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002753
Glenn Kasten952eeb22012-03-06 11:30:57 -08002754 Track* const track = t.get();
2755 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002756
Glenn Kasten952eeb22012-03-06 11:30:57 -08002757 // The first time a track is added we wait
2758 // for all its buffers to be filled before processing it
2759 if (cblk->framesReady() && track->isReady() &&
2760 !track->isPaused() && !track->isTerminated())
2761 {
2762 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002763
Glenn Kasten952eeb22012-03-06 11:30:57 -08002764 if (track->mFillingUpStatus == Track::FS_FILLED) {
2765 track->mFillingUpStatus = Track::FS_ACTIVE;
2766 mLeftVolFloat = mRightVolFloat = 0;
2767 mLeftVolShort = mRightVolShort = 0;
2768 if (track->mState == TrackBase::RESUMING) {
2769 track->mState = TrackBase::ACTIVE;
2770 rampVolume = true;
2771 }
2772 } else if (cblk->server != 0) {
2773 // If the track is stopped before the first frame was mixed,
2774 // do not apply ramp
2775 rampVolume = true;
2776 }
2777 // compute volume for this track
2778 float left, right;
2779 if (track->isMuted() || mMasterMute || track->isPausing() ||
2780 mStreamTypes[track->streamType()].mute) {
2781 left = right = 0;
2782 if (track->isPausing()) {
2783 track->setPaused();
2784 }
2785 } else {
2786 float typeVolume = mStreamTypes[track->streamType()].volume;
2787 float v = mMasterVolume * typeVolume;
2788 uint32_t vlr = cblk->getVolumeLR();
2789 float v_clamped = v * (vlr & 0xFFFF);
2790 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2791 left = v_clamped/MAX_GAIN;
2792 v_clamped = v * (vlr >> 16);
2793 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2794 right = v_clamped/MAX_GAIN;
2795 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002796
Glenn Kasten952eeb22012-03-06 11:30:57 -08002797 if (left != mLeftVolFloat || right != mRightVolFloat) {
2798 mLeftVolFloat = left;
2799 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002800
Glenn Kasten952eeb22012-03-06 11:30:57 -08002801 // If audio HAL implements volume control,
2802 // force software volume to nominal value
2803 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
2804 left = 1.0f;
2805 right = 1.0f;
2806 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002807
Glenn Kasten952eeb22012-03-06 11:30:57 -08002808 // Convert volumes from float to 8.24
2809 uint32_t vl = (uint32_t)(left * (1 << 24));
2810 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002811
Glenn Kasten952eeb22012-03-06 11:30:57 -08002812 // Delegate volume control to effect in track effect chain if needed
2813 // only one effect chain can be present on DirectOutputThread, so if
2814 // there is one, the track is connected to it
2815 if (!mEffectChains.isEmpty()) {
2816 // Do not ramp volume if volume is controlled by effect
2817 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002818 rampVolume = false;
2819 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002820 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002821
Glenn Kasten952eeb22012-03-06 11:30:57 -08002822 // Convert volumes from 8.24 to 4.12 format
2823 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2824 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2825 leftVol = (uint16_t)v_clamped;
2826 v_clamped = (vr + (1 << 11)) >> 12;
2827 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2828 rightVol = (uint16_t)v_clamped;
2829 } else {
2830 leftVol = mLeftVolShort;
2831 rightVol = mRightVolShort;
2832 rampVolume = false;
2833 }
2834
2835 // reset retry count
2836 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002837 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002838 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002839 } else {
2840 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2841 if (track->isStopped()) {
2842 track->reset();
2843 }
2844 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2845 // We have consumed all the buffers of this track.
2846 // Remove it from the list of active tracks.
2847 trackToRemove = track;
2848 } else {
2849 // No buffers for this track. Give it a few chances to
2850 // fill a buffer, then remove it from active list.
2851 if (--(track->mRetryCount) <= 0) {
2852 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2853 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002854 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002855 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002856 }
2857 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002858 }
2859 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002860
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002861 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08002862 // remove all the tracks that need to be...
2863 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002864 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002865 mActiveTracks.remove(trackToRemove);
2866 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002867 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08002868 trackToRemove->sessionId());
2869 mEffectChains[0]->decActiveTrackCnt();
2870 }
2871 if (trackToRemove->isTerminated()) {
2872 removeTrack_l(trackToRemove);
2873 }
2874 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002875
Glenn Kastenfec279f2012-03-08 07:47:15 -08002876 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002877}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002878
Glenn Kasten000f0e32012-03-01 17:10:56 -08002879void AudioFlinger::DirectOutputThread::threadLoop_mix()
2880{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002881 AudioBufferProvider::Buffer buffer;
2882 size_t frameCount = mFrameCount;
2883 int8_t *curBuf = (int8_t *)mMixBuffer;
2884 // output audio to hardware
2885 while (frameCount) {
2886 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002887 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002888 if (CC_UNLIKELY(buffer.raw == NULL)) {
2889 memset(curBuf, 0, frameCount * mFrameSize);
2890 break;
2891 }
2892 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2893 frameCount -= buffer.frameCount;
2894 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002895 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002896 }
2897 sleepTime = 0;
2898 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002899 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08002900
2901 // apply volume
2902
2903 // Do not apply volume on compressed audio
2904 if (!audio_is_linear_pcm(mFormat)) {
2905 return;
2906 }
2907
2908 // convert to signed 16 bit before volume calculation
2909 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
2910 size_t count = mFrameCount * mChannelCount;
2911 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2912 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002913 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08002914 *dst-- = (int16_t)(*src--^0x80) << 8;
2915 }
2916 }
2917
2918 frameCount = mFrameCount;
2919 int16_t *out = mMixBuffer;
2920 if (rampVolume) {
2921 if (mChannelCount == 1) {
2922 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2923 int32_t vlInc = d / (int32_t)frameCount;
2924 int32_t vl = ((int32_t)mLeftVolShort << 16);
2925 do {
2926 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2927 out++;
2928 vl += vlInc;
2929 } while (--frameCount);
2930
2931 } else {
2932 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2933 int32_t vlInc = d / (int32_t)frameCount;
2934 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2935 int32_t vrInc = d / (int32_t)frameCount;
2936 int32_t vl = ((int32_t)mLeftVolShort << 16);
2937 int32_t vr = ((int32_t)mRightVolShort << 16);
2938 do {
2939 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2940 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2941 out += 2;
2942 vl += vlInc;
2943 vr += vrInc;
2944 } while (--frameCount);
2945 }
2946 } else {
2947 if (mChannelCount == 1) {
2948 do {
2949 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2950 out++;
2951 } while (--frameCount);
2952 } else {
2953 do {
2954 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2955 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2956 out += 2;
2957 } while (--frameCount);
2958 }
2959 }
2960
2961 // convert back to unsigned 8 bit after volume calculation
2962 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
2963 size_t count = mFrameCount * mChannelCount;
2964 int16_t *src = mMixBuffer;
2965 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002966 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08002967 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2968 }
2969 }
2970
2971 mLeftVolShort = leftVol;
2972 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002973}
2974
2975void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
2976{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002977 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002978 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002979 sleepTime = activeSleepTime;
2980 } else {
2981 sleepTime = idleSleepTime;
2982 }
2983 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
2984 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2985 sleepTime = 0;
2986 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002987}
2988
2989// getTrackName_l() must be called with ThreadBase::mLock held
2990int AudioFlinger::DirectOutputThread::getTrackName_l()
2991{
2992 return 0;
2993}
2994
2995// deleteTrackName_l() must be called with ThreadBase::mLock held
2996void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2997{
2998}
2999
3000// checkForNewParameters_l() must be called with ThreadBase::mLock held
3001bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3002{
3003 bool reconfig = false;
3004
3005 while (!mNewParameters.isEmpty()) {
3006 status_t status = NO_ERROR;
3007 String8 keyValuePair = mNewParameters[0];
3008 AudioParameter param = AudioParameter(keyValuePair);
3009 int value;
3010
3011 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3012 // do not accept frame count changes if tracks are open as the track buffer
3013 // size depends on frame count and correct behavior would not be garantied
3014 // if frame count is changed after track creation
3015 if (!mTracks.isEmpty()) {
3016 status = INVALID_OPERATION;
3017 } else {
3018 reconfig = true;
3019 }
3020 }
3021 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003022 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003023 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003024 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003025 mOutput->stream->common.standby(&mOutput->stream->common);
3026 mStandby = true;
3027 mBytesWritten = 0;
3028 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003029 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003030 }
3031 if (status == NO_ERROR && reconfig) {
3032 readOutputParameters();
3033 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3034 }
3035 }
3036
3037 mNewParameters.removeAt(0);
3038
3039 mParamStatus = status;
3040 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003041 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3042 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003043 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003044 }
3045 return reconfig;
3046}
3047
3048uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
3049{
3050 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003051 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003052 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003053 } else {
3054 time = 10000;
3055 }
3056 return time;
3057}
3058
3059uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
3060{
3061 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003062 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003063 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003064 } else {
3065 time = 10000;
3066 }
3067 return time;
3068}
3069
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003070uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
3071{
3072 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003073 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003074 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3075 } else {
3076 time = 10000;
3077 }
3078 return time;
3079}
3080
Glenn Kasten66fcab92012-02-24 14:59:21 -08003081void AudioFlinger::DirectOutputThread::cacheParameters_l()
3082{
3083 PlaybackThread::cacheParameters_l();
3084
3085 // use shorter standby delay as on normal output to release
3086 // hardware resources as soon as possible
3087 standbyDelay = microseconds(activeSleepTime*2);
3088}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003089
Mathias Agopian65ab4712010-07-14 17:59:35 -07003090// ----------------------------------------------------------------------------
3091
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003092AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003093 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003094 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3095 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003096{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003097 addOutputTrack(mainThread);
3098}
3099
3100AudioFlinger::DuplicatingThread::~DuplicatingThread()
3101{
3102 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3103 mOutputTracks[i]->destroy();
3104 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003105}
3106
Glenn Kasten000f0e32012-03-01 17:10:56 -08003107void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003108{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003109 // mix buffers...
3110 if (outputsReady(outputTracks)) {
3111 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3112 } else {
3113 memset(mMixBuffer, 0, mixBufferSize);
3114 }
3115 sleepTime = 0;
3116 writeFrames = mFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003117}
3118
3119void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3120{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003121 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003122 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003123 sleepTime = activeSleepTime;
3124 } else {
3125 sleepTime = idleSleepTime;
3126 }
3127 } else if (mBytesWritten != 0) {
3128 // flush remaining overflow buffers in output tracks
3129 for (size_t i = 0; i < outputTracks.size(); i++) {
3130 if (outputTracks[i]->isActive()) {
3131 sleepTime = 0;
3132 writeFrames = 0;
3133 memset(mMixBuffer, 0, mixBufferSize);
3134 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003135 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003136 }
3137 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003138}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003139
Glenn Kasten000f0e32012-03-01 17:10:56 -08003140void AudioFlinger::DuplicatingThread::threadLoop_write()
3141{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003142 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003143 for (size_t i = 0; i < outputTracks.size(); i++) {
3144 outputTracks[i]->write(mMixBuffer, writeFrames);
3145 }
3146 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003147}
Glenn Kasten688a6402012-02-29 07:57:06 -08003148
Glenn Kasten000f0e32012-03-01 17:10:56 -08003149void AudioFlinger::DuplicatingThread::threadLoop_standby()
3150{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003151 // DuplicatingThread implements standby by stopping all tracks
3152 for (size_t i = 0; i < outputTracks.size(); i++) {
3153 outputTracks[i]->stop();
3154 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003155}
3156
Glenn Kastenfa26a852012-03-06 11:28:04 -08003157void AudioFlinger::DuplicatingThread::saveOutputTracks()
3158{
3159 outputTracks = mOutputTracks;
3160}
3161
3162void AudioFlinger::DuplicatingThread::clearOutputTracks()
3163{
3164 outputTracks.clear();
3165}
3166
Mathias Agopian65ab4712010-07-14 17:59:35 -07003167void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3168{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003169 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003170 // FIXME explain this formula
Mathias Agopian65ab4712010-07-14 17:59:35 -07003171 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003172 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003173 this,
3174 mSampleRate,
3175 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003176 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003177 frameCount);
3178 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003179 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003180 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003181 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003182 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003183 }
3184}
3185
3186void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3187{
3188 Mutex::Autolock _l(mLock);
3189 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003190 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003191 mOutputTracks[i]->destroy();
3192 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003193 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003194 return;
3195 }
3196 }
Steve Block3856b092011-10-20 11:56:00 +01003197 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003198}
3199
Glenn Kasten438b0362012-03-06 11:24:48 -08003200// caller must hold mLock
3201void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003202{
3203 mWaitTimeMs = UINT_MAX;
3204 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3205 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003206 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003207 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3208 if (waitTimeMs < mWaitTimeMs) {
3209 mWaitTimeMs = waitTimeMs;
3210 }
3211 }
3212 }
3213}
3214
3215
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003216bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003217{
3218 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003219 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003221 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003222 return false;
3223 }
3224 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3225 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003226 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003227 return false;
3228 }
3229 }
3230 return true;
3231}
3232
3233uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3234{
3235 return (mWaitTimeMs * 1000) / 2;
3236}
3237
Glenn Kasten66fcab92012-02-24 14:59:21 -08003238void AudioFlinger::DuplicatingThread::cacheParameters_l()
3239{
3240 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3241 updateWaitTime_l();
3242
3243 MixerThread::cacheParameters_l();
3244}
3245
Mathias Agopian65ab4712010-07-14 17:59:35 -07003246// ----------------------------------------------------------------------------
3247
3248// TrackBase constructor must be called with AudioFlinger::mLock held
3249AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003250 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003251 const sp<Client>& client,
3252 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003253 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003254 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003255 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003256 const sp<IMemory>& sharedBuffer,
3257 int sessionId)
3258 : RefBase(),
3259 mThread(thread),
3260 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003261 mCblk(NULL),
3262 // mBuffer
3263 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003264 mFrameCount(0),
3265 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003266 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003267 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003268 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003269 // mChannelCount
3270 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003271{
Steve Block3856b092011-10-20 11:56:00 +01003272 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003273
Steve Blockb8a80522011-12-20 16:23:08 +00003274 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003275 size_t size = sizeof(audio_track_cblk_t);
3276 uint8_t channelCount = popcount(channelMask);
3277 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3278 if (sharedBuffer == 0) {
3279 size += bufferSize;
3280 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003281
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003282 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003283 mCblkMemory = client->heap()->allocate(size);
3284 if (mCblkMemory != 0) {
3285 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003286 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003287 new(mCblk) audio_track_cblk_t();
3288 // clear all buffers
3289 mCblk->frameCount = frameCount;
3290 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003291 mChannelCount = channelCount;
3292 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003293 if (sharedBuffer == 0) {
3294 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3295 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3296 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003297 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003298 mCblk->flags = CBLK_UNDERRUN_ON;
3299 } else {
3300 mBuffer = sharedBuffer->pointer();
3301 }
3302 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3303 }
3304 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003305 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003306 client->heap()->dump("AudioTrack");
3307 return;
3308 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003309 } else {
3310 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3311 // construct the shared structure in-place.
3312 new(mCblk) audio_track_cblk_t();
3313 // clear all buffers
3314 mCblk->frameCount = frameCount;
3315 mCblk->sampleRate = sampleRate;
3316 mChannelCount = channelCount;
3317 mChannelMask = channelMask;
3318 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3319 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3320 // Force underrun condition to avoid false underrun callback until first data is
3321 // written to buffer (other flags are cleared)
3322 mCblk->flags = CBLK_UNDERRUN_ON;
3323 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3324 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003325}
3326
3327AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3328{
Glenn Kastena0d68332012-01-27 16:47:15 -08003329 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003330 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003331 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003332 } else {
3333 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003334 }
3335 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003336 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003337 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003338 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003339 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003340 // If the client's reference count drops to zero, the associated destructor
3341 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3342 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003343 mClient.clear();
3344 }
3345}
3346
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003347// AudioBufferProvider interface
3348// getNextBuffer() = 0;
3349// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07003350void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3351{
Glenn Kastene0feee32011-12-13 11:53:26 -08003352 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003353 mFrameCount = buffer->frameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003354 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003355 buffer->frameCount = 0;
3356}
3357
3358bool AudioFlinger::ThreadBase::TrackBase::step() {
3359 bool result;
3360 audio_track_cblk_t* cblk = this->cblk();
3361
3362 result = cblk->stepServer(mFrameCount);
3363 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003364 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003365 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003366 }
3367 return result;
3368}
3369
3370void AudioFlinger::ThreadBase::TrackBase::reset() {
3371 audio_track_cblk_t* cblk = this->cblk();
3372
3373 cblk->user = 0;
3374 cblk->server = 0;
3375 cblk->userBase = 0;
3376 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003377 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01003378 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003379}
3380
Mathias Agopian65ab4712010-07-14 17:59:35 -07003381int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3382 return (int)mCblk->sampleRate;
3383}
3384
Mathias Agopian65ab4712010-07-14 17:59:35 -07003385void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3386 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003387 size_t frameSize = cblk->frameSize;
3388 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3389 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003390
3391 // Check validity of returned pointer in case the track control block would have been corrupted.
3392 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003393 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003394 ALOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003395 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003396 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003397 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003398 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003399 }
3400
3401 return bufferStart;
3402}
3403
3404// ----------------------------------------------------------------------------
3405
3406// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3407AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003408 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003409 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003410 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003411 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003412 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003413 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003414 int frameCount,
3415 const sp<IMemory>& sharedBuffer,
3416 int sessionId)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003417 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003418 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3419 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003420{
3421 if (mCblk != NULL) {
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003422 if (thread != NULL) {
3423 mName = thread->getTrackName_l();
3424 mMainBuffer = thread->mixBuffer();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003425 }
Glenn Kasten23d82a92012-02-03 11:10:00 -08003426 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003427 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003428 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003429 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003430 mStreamType = streamType;
3431 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3432 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003433 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003434 }
3435}
3436
3437AudioFlinger::PlaybackThread::Track::~Track()
3438{
Steve Block3856b092011-10-20 11:56:00 +01003439 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003440 sp<ThreadBase> thread = mThread.promote();
3441 if (thread != 0) {
3442 Mutex::Autolock _l(thread->mLock);
3443 mState = TERMINATED;
3444 }
3445}
3446
3447void AudioFlinger::PlaybackThread::Track::destroy()
3448{
3449 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3450 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08003451 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003452 // we must acquire a strong reference on this Track before locking mLock
3453 // here so that the destructor is called only when exiting this function.
3454 // On the other hand, as long as Track::destroy() is only called by
3455 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3456 // this Track with its member mTrack.
3457 sp<Track> keep(this);
3458 { // scope for mLock
3459 sp<ThreadBase> thread = mThread.promote();
3460 if (thread != 0) {
3461 if (!isOutputTrack()) {
3462 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08003463 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003464
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003465#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003466 // to track the speaker usage
3467 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003468#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003469 }
3470 AudioSystem::releaseOutput(thread->id());
3471 }
3472 Mutex::Autolock _l(thread->mLock);
3473 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3474 playbackThread->destroyTrack_l(this);
3475 }
3476 }
3477}
3478
3479void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3480{
Glenn Kasten83d86532012-01-17 14:39:34 -08003481 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003482 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",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003483 mName - AudioMixer::TRACK0,
Glenn Kasten44deb052012-02-05 18:09:08 -08003484 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003485 mStreamType,
3486 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003487 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003488 mSessionId,
3489 mFrameCount,
3490 mState,
3491 mMute,
3492 mFillingUpStatus,
3493 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003494 vlr & 0xFFFF,
3495 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003496 mCblk->server,
3497 mCblk->user,
3498 (int)mMainBuffer,
3499 (int)mAuxBuffer);
3500}
3501
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003502// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08003503status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003504 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003505{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003506 audio_track_cblk_t* cblk = this->cblk();
3507 uint32_t framesReady;
3508 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003509
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003510 // Check if last stepServer failed, try to step now
3511 if (mStepServerFailed) {
3512 if (!step()) goto getNextBuffer_exit;
3513 ALOGV("stepServer recovered");
3514 mStepServerFailed = false;
3515 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003516
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003517 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003518
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003519 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003520 uint32_t s = cblk->server;
3521 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3522
3523 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3524 if (framesReq > framesReady) {
3525 framesReq = framesReady;
3526 }
3527 if (s + framesReq > bufferEnd) {
3528 framesReq = bufferEnd - s;
3529 }
3530
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003531 buffer->raw = getBuffer(s, framesReq);
3532 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003533
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003534 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003535 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003536 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003537
3538getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003539 buffer->raw = NULL;
3540 buffer->frameCount = 0;
3541 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3542 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003543}
3544
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003545uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08003546 return mCblk->framesReady();
3547}
3548
Mathias Agopian65ab4712010-07-14 17:59:35 -07003549bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003550 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003551
John Grossman4ff14ba2012-02-08 16:37:41 -08003552 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003553 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3554 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003555 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003556 return true;
3557 }
3558 return false;
3559}
3560
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003561status_t AudioFlinger::PlaybackThread::Track::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003562{
3563 status_t status = NO_ERROR;
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003564 ALOGV("start(%d), calling pid %d session %d tid %d",
3565 mName, IPCThreadState::self()->getCallingPid(), mSessionId, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003566 sp<ThreadBase> thread = mThread.promote();
3567 if (thread != 0) {
3568 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003569 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003570 // here the track could be either new, or restarted
3571 // in both cases "unstop" the track
3572 if (mState == PAUSED) {
3573 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003574 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003575 } else {
3576 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003577 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003578 }
3579
3580 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3581 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003582 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003583 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003584
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003585#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003586 // to track the speaker usage
3587 if (status == NO_ERROR) {
3588 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3589 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003590#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003591 }
3592 if (status == NO_ERROR) {
3593 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3594 playbackThread->addTrack_l(this);
3595 } else {
3596 mState = state;
3597 }
3598 } else {
3599 status = BAD_VALUE;
3600 }
3601 return status;
3602}
3603
3604void AudioFlinger::PlaybackThread::Track::stop()
3605{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003606 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003607 sp<ThreadBase> thread = mThread.promote();
3608 if (thread != 0) {
3609 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003610 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003611 if (mState > STOPPED) {
3612 mState = STOPPED;
3613 // If the track is not active (PAUSED and buffers full), flush buffers
3614 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3615 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3616 reset();
3617 }
Steve Block3856b092011-10-20 11:56:00 +01003618 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003619 }
3620 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3621 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003622 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003623 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003624
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003625#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003626 // to track the speaker usage
3627 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003628#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003629 }
3630 }
3631}
3632
3633void AudioFlinger::PlaybackThread::Track::pause()
3634{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003635 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003636 sp<ThreadBase> thread = mThread.promote();
3637 if (thread != 0) {
3638 Mutex::Autolock _l(thread->mLock);
3639 if (mState == ACTIVE || mState == RESUMING) {
3640 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003641 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003642 if (!isOutputTrack()) {
3643 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003644 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003645 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003646
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003647#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003648 // to track the speaker usage
3649 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003650#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003651 }
3652 }
3653 }
3654}
3655
3656void AudioFlinger::PlaybackThread::Track::flush()
3657{
Steve Block3856b092011-10-20 11:56:00 +01003658 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003659 sp<ThreadBase> thread = mThread.promote();
3660 if (thread != 0) {
3661 Mutex::Autolock _l(thread->mLock);
3662 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3663 return;
3664 }
3665 // No point remaining in PAUSED state after a flush => go to
3666 // STOPPED state
3667 mState = STOPPED;
3668
Eric Laurent38ccae22011-03-28 18:37:07 -07003669 // do not reset the track if it is still in the process of being stopped or paused.
3670 // this will be done by prepareTracks_l() when the track is stopped.
3671 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3672 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3673 reset();
3674 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003675 }
3676}
3677
3678void AudioFlinger::PlaybackThread::Track::reset()
3679{
3680 // Do not reset twice to avoid discarding data written just after a flush and before
3681 // the audioflinger thread detects the track is stopped.
3682 if (!mResetDone) {
3683 TrackBase::reset();
3684 // Force underrun condition to avoid false underrun callback until first data is
3685 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003686 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3687 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003688 mFillingUpStatus = FS_FILLING;
3689 mResetDone = true;
3690 }
3691}
3692
3693void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3694{
3695 mMute = muted;
3696}
3697
Mathias Agopian65ab4712010-07-14 17:59:35 -07003698status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3699{
3700 status_t status = DEAD_OBJECT;
3701 sp<ThreadBase> thread = mThread.promote();
3702 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003703 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3704 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003705 }
3706 return status;
3707}
3708
3709void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3710{
3711 mAuxEffectId = EffectId;
3712 mAuxBuffer = buffer;
3713}
3714
John Grossman4ff14ba2012-02-08 16:37:41 -08003715// timed audio tracks
3716
3717sp<AudioFlinger::PlaybackThread::TimedTrack>
3718AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003719 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003720 const sp<Client>& client,
3721 audio_stream_type_t streamType,
3722 uint32_t sampleRate,
3723 audio_format_t format,
3724 uint32_t channelMask,
3725 int frameCount,
3726 const sp<IMemory>& sharedBuffer,
3727 int sessionId) {
3728 if (!client->reserveTimedTrack())
3729 return NULL;
3730
3731 sp<TimedTrack> track = new TimedTrack(
3732 thread, client, streamType, sampleRate, format, channelMask, frameCount,
3733 sharedBuffer, sessionId);
3734
3735 if (track == NULL) {
3736 client->releaseTimedTrack();
3737 return NULL;
3738 }
3739
3740 return track;
3741}
3742
3743AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003744 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003745 const sp<Client>& client,
3746 audio_stream_type_t streamType,
3747 uint32_t sampleRate,
3748 audio_format_t format,
3749 uint32_t channelMask,
3750 int frameCount,
3751 const sp<IMemory>& sharedBuffer,
3752 int sessionId)
3753 : Track(thread, client, streamType, sampleRate, format, channelMask,
3754 frameCount, sharedBuffer, sessionId),
3755 mTimedSilenceBuffer(NULL),
3756 mTimedSilenceBufferSize(0),
3757 mTimedAudioOutputOnTime(false),
3758 mMediaTimeTransformValid(false)
3759{
3760 LocalClock lc;
3761 mLocalTimeFreq = lc.getLocalFreq();
3762
3763 mLocalTimeToSampleTransform.a_zero = 0;
3764 mLocalTimeToSampleTransform.b_zero = 0;
3765 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3766 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3767 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3768 &mLocalTimeToSampleTransform.a_to_b_denom);
3769}
3770
3771AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3772 mClient->releaseTimedTrack();
3773 delete [] mTimedSilenceBuffer;
3774}
3775
3776status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3777 size_t size, sp<IMemory>* buffer) {
3778
3779 Mutex::Autolock _l(mTimedBufferQueueLock);
3780
3781 trimTimedBufferQueue_l();
3782
3783 // lazily initialize the shared memory heap for timed buffers
3784 if (mTimedMemoryDealer == NULL) {
3785 const int kTimedBufferHeapSize = 512 << 10;
3786
3787 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3788 "AudioFlingerTimed");
3789 if (mTimedMemoryDealer == NULL)
3790 return NO_MEMORY;
3791 }
3792
3793 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3794 if (newBuffer == NULL) {
3795 newBuffer = mTimedMemoryDealer->allocate(size);
3796 if (newBuffer == NULL)
3797 return NO_MEMORY;
3798 }
3799
3800 *buffer = newBuffer;
3801 return NO_ERROR;
3802}
3803
3804// caller must hold mTimedBufferQueueLock
3805void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
3806 int64_t mediaTimeNow;
3807 {
3808 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3809 if (!mMediaTimeTransformValid)
3810 return;
3811
3812 int64_t targetTimeNow;
3813 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
3814 ? mCCHelper.getCommonTime(&targetTimeNow)
3815 : mCCHelper.getLocalTime(&targetTimeNow);
3816
3817 if (OK != res)
3818 return;
3819
3820 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
3821 &mediaTimeNow)) {
3822 return;
3823 }
3824 }
3825
3826 size_t trimIndex;
3827 for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
3828 if (mTimedBufferQueue[trimIndex].pts() > mediaTimeNow)
3829 break;
3830 }
3831
3832 if (trimIndex) {
3833 mTimedBufferQueue.removeItemsAt(0, trimIndex);
3834 }
3835}
3836
3837status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
3838 const sp<IMemory>& buffer, int64_t pts) {
3839
3840 {
3841 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3842 if (!mMediaTimeTransformValid)
3843 return INVALID_OPERATION;
3844 }
3845
3846 Mutex::Autolock _l(mTimedBufferQueueLock);
3847
3848 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
3849
3850 return NO_ERROR;
3851}
3852
3853status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
3854 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
3855
3856 ALOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
3857 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
3858 target);
3859
3860 if (!(target == TimedAudioTrack::LOCAL_TIME ||
3861 target == TimedAudioTrack::COMMON_TIME)) {
3862 return BAD_VALUE;
3863 }
3864
3865 Mutex::Autolock lock(mMediaTimeTransformLock);
3866 mMediaTimeTransform = xform;
3867 mMediaTimeTransformTarget = target;
3868 mMediaTimeTransformValid = true;
3869
3870 return NO_ERROR;
3871}
3872
3873#define min(a, b) ((a) < (b) ? (a) : (b))
3874
3875// implementation of getNextBuffer for tracks whose buffers have timestamps
3876status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
3877 AudioBufferProvider::Buffer* buffer, int64_t pts)
3878{
3879 if (pts == AudioBufferProvider::kInvalidPTS) {
3880 buffer->raw = 0;
3881 buffer->frameCount = 0;
3882 return INVALID_OPERATION;
3883 }
3884
John Grossman4ff14ba2012-02-08 16:37:41 -08003885 Mutex::Autolock _l(mTimedBufferQueueLock);
3886
3887 while (true) {
3888
3889 // if we have no timed buffers, then fail
3890 if (mTimedBufferQueue.isEmpty()) {
3891 buffer->raw = 0;
3892 buffer->frameCount = 0;
3893 return NOT_ENOUGH_DATA;
3894 }
3895
3896 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
3897
3898 // calculate the PTS of the head of the timed buffer queue expressed in
3899 // local time
3900 int64_t headLocalPTS;
3901 {
3902 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3903
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003904 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08003905
3906 if (mMediaTimeTransform.a_to_b_denom == 0) {
3907 // the transform represents a pause, so yield silence
3908 timedYieldSilence(buffer->frameCount, buffer);
3909 return NO_ERROR;
3910 }
3911
3912 int64_t transformedPTS;
3913 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
3914 &transformedPTS)) {
3915 // the transform failed. this shouldn't happen, but if it does
3916 // then just drop this buffer
3917 ALOGW("timedGetNextBuffer transform failed");
3918 buffer->raw = 0;
3919 buffer->frameCount = 0;
3920 mTimedBufferQueue.removeAt(0);
3921 return NO_ERROR;
3922 }
3923
3924 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
3925 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
3926 &headLocalPTS)) {
3927 buffer->raw = 0;
3928 buffer->frameCount = 0;
3929 return INVALID_OPERATION;
3930 }
3931 } else {
3932 headLocalPTS = transformedPTS;
3933 }
3934 }
3935
3936 // adjust the head buffer's PTS to reflect the portion of the head buffer
3937 // that has already been consumed
3938 int64_t effectivePTS = headLocalPTS +
3939 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
3940
3941 // Calculate the delta in samples between the head of the input buffer
3942 // queue and the start of the next output buffer that will be written.
3943 // If the transformation fails because of over or underflow, it means
3944 // that the sample's position in the output stream is so far out of
3945 // whack that it should just be dropped.
3946 int64_t sampleDelta;
3947 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
3948 ALOGV("*** head buffer is too far from PTS: dropped buffer");
3949 mTimedBufferQueue.removeAt(0);
3950 continue;
3951 }
3952 if (!mLocalTimeToSampleTransform.doForwardTransform(
3953 (effectivePTS - pts) << 32, &sampleDelta)) {
3954 ALOGV("*** too late during sample rate transform: dropped buffer");
3955 mTimedBufferQueue.removeAt(0);
3956 continue;
3957 }
3958
3959 ALOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
3960 __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
3961 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
3962 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
3963
3964 // if the delta between the ideal placement for the next input sample and
3965 // the current output position is within this threshold, then we will
3966 // concatenate the next input samples to the previous output
3967 const int64_t kSampleContinuityThreshold =
3968 (static_cast<int64_t>(sampleRate()) << 32) / 10;
3969
3970 // if this is the first buffer of audio that we're emitting from this track
3971 // then it should be almost exactly on time.
3972 const int64_t kSampleStartupThreshold = 1LL << 32;
3973
3974 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
3975 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
3976 // the next input is close enough to being on time, so concatenate it
3977 // with the last output
3978 timedYieldSamples(buffer);
3979
3980 ALOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
3981 return NO_ERROR;
3982 } else if (sampleDelta > 0) {
3983 // the gap between the current output position and the proper start of
3984 // the next input sample is too big, so fill it with silence
3985 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
3986
3987 timedYieldSilence(framesUntilNextInput, buffer);
3988 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
3989 return NO_ERROR;
3990 } else {
3991 // the next input sample is late
3992 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
3993 size_t onTimeSamplePosition =
3994 head.position() + lateFrames * mCblk->frameSize;
3995
3996 if (onTimeSamplePosition > head.buffer()->size()) {
3997 // all the remaining samples in the head are too late, so
3998 // drop it and move on
3999 ALOGV("*** too late: dropped buffer");
4000 mTimedBufferQueue.removeAt(0);
4001 continue;
4002 } else {
4003 // skip over the late samples
4004 head.setPosition(onTimeSamplePosition);
4005
4006 // yield the available samples
4007 timedYieldSamples(buffer);
4008
4009 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4010 return NO_ERROR;
4011 }
4012 }
4013 }
4014}
4015
4016// Yield samples from the timed buffer queue head up to the given output
4017// buffer's capacity.
4018//
4019// Caller must hold mTimedBufferQueueLock
4020void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples(
4021 AudioBufferProvider::Buffer* buffer) {
4022
4023 const TimedBuffer& head = mTimedBufferQueue[0];
4024
4025 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4026 head.position());
4027
4028 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4029 mCblk->frameSize);
4030 size_t framesRequested = buffer->frameCount;
4031 buffer->frameCount = min(framesLeftInHead, framesRequested);
4032
4033 mTimedAudioOutputOnTime = true;
4034}
4035
4036// Yield samples of silence up to the given output buffer's capacity
4037//
4038// Caller must hold mTimedBufferQueueLock
4039void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence(
4040 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4041
4042 // lazily allocate a buffer filled with silence
4043 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4044 delete [] mTimedSilenceBuffer;
4045 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4046 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4047 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4048 }
4049
4050 buffer->raw = mTimedSilenceBuffer;
4051 size_t framesRequested = buffer->frameCount;
4052 buffer->frameCount = min(numFrames, framesRequested);
4053
4054 mTimedAudioOutputOnTime = false;
4055}
4056
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004057// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004058void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4059 AudioBufferProvider::Buffer* buffer) {
4060
4061 Mutex::Autolock _l(mTimedBufferQueueLock);
4062
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004063 // If the buffer which was just released is part of the buffer at the head
4064 // of the queue, be sure to update the amt of the buffer which has been
4065 // consumed. If the buffer being returned is not part of the head of the
4066 // queue, its either because the buffer is part of the silence buffer, or
4067 // because the head of the timed queue was trimmed after the mixer called
4068 // getNextBuffer but before the mixer called releaseBuffer.
4069 if ((buffer->raw != mTimedSilenceBuffer) && mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004070 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004071
4072 void* start = head.buffer()->pointer();
Glenn Kastenf063b492012-02-17 16:24:10 -08004073 void* end = (char *) head.buffer()->pointer() + head.buffer()->size();
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004074
4075 if ((buffer->raw >= start) && (buffer->raw <= end)) {
4076 head.setPosition(head.position() +
4077 (buffer->frameCount * mCblk->frameSize));
4078 if (static_cast<size_t>(head.position()) >= head.buffer()->size()) {
4079 mTimedBufferQueue.removeAt(0);
4080 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004081 }
4082 }
4083
4084 buffer->raw = 0;
4085 buffer->frameCount = 0;
4086}
4087
4088uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4089 Mutex::Autolock _l(mTimedBufferQueueLock);
4090
4091 uint32_t frames = 0;
4092 for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4093 const TimedBuffer& tb = mTimedBufferQueue[i];
4094 frames += (tb.buffer()->size() - tb.position()) / mCblk->frameSize;
4095 }
4096
4097 return frames;
4098}
4099
4100AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4101 : mPTS(0), mPosition(0) {}
4102
4103AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4104 const sp<IMemory>& buffer, int64_t pts)
4105 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4106
Mathias Agopian65ab4712010-07-14 17:59:35 -07004107// ----------------------------------------------------------------------------
4108
4109// RecordTrack constructor must be called with AudioFlinger::mLock held
4110AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004111 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004112 const sp<Client>& client,
4113 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004114 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004115 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004116 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004117 int sessionId)
4118 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004119 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004120 mOverflow(false)
4121{
4122 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004123 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
4124 if (format == AUDIO_FORMAT_PCM_16_BIT) {
4125 mCblk->frameSize = mChannelCount * sizeof(int16_t);
4126 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
4127 mCblk->frameSize = mChannelCount * sizeof(int8_t);
4128 } else {
4129 mCblk->frameSize = sizeof(int8_t);
4130 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004131 }
4132}
4133
4134AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4135{
4136 sp<ThreadBase> thread = mThread.promote();
4137 if (thread != 0) {
4138 AudioSystem::releaseInput(thread->id());
4139 }
4140}
4141
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004142// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004143status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004144{
4145 audio_track_cblk_t* cblk = this->cblk();
4146 uint32_t framesAvail;
4147 uint32_t framesReq = buffer->frameCount;
4148
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004149 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004150 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004151 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004152 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004153 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004154 }
4155
4156 framesAvail = cblk->framesAvailable_l();
4157
Glenn Kastenf6b16782011-12-15 09:51:17 -08004158 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004159 uint32_t s = cblk->server;
4160 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4161
4162 if (framesReq > framesAvail) {
4163 framesReq = framesAvail;
4164 }
4165 if (s + framesReq > bufferEnd) {
4166 framesReq = bufferEnd - s;
4167 }
4168
4169 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004170 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004171
4172 buffer->frameCount = framesReq;
4173 return NO_ERROR;
4174 }
4175
4176getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004177 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004178 buffer->frameCount = 0;
4179 return NOT_ENOUGH_DATA;
4180}
4181
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004182status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004183{
4184 sp<ThreadBase> thread = mThread.promote();
4185 if (thread != 0) {
4186 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004187 return recordThread->start(this, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004188 } else {
4189 return BAD_VALUE;
4190 }
4191}
4192
4193void AudioFlinger::RecordThread::RecordTrack::stop()
4194{
4195 sp<ThreadBase> thread = mThread.promote();
4196 if (thread != 0) {
4197 RecordThread *recordThread = (RecordThread *)thread.get();
4198 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004199 TrackBase::reset();
4200 // Force overerrun condition to avoid false overrun callback until first data is
4201 // read from buffer
4202 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004203 }
4204}
4205
4206void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4207{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004208 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004209 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004210 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004211 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004212 mSessionId,
4213 mFrameCount,
4214 mState,
4215 mCblk->sampleRate,
4216 mCblk->server,
4217 mCblk->user);
4218}
4219
4220
4221// ----------------------------------------------------------------------------
4222
4223AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004224 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004225 DuplicatingThread *sourceThread,
4226 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004227 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004228 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004229 int frameCount)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004230 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004231 mActive(false), mSourceThread(sourceThread)
4232{
4233
Mathias Agopian65ab4712010-07-14 17:59:35 -07004234 if (mCblk != NULL) {
4235 mCblk->flags |= CBLK_DIRECTION_OUT;
4236 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004237 mOutBuffer.frameCount = 0;
4238 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01004239 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004240 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4241 mCblk, mBuffer, mCblk->buffers,
4242 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004243 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004244 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004245 }
4246}
4247
4248AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4249{
4250 clearBufferQueue();
4251}
4252
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004253status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004254{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004255 status_t status = Track::start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004256 if (status != NO_ERROR) {
4257 return status;
4258 }
4259
4260 mActive = true;
4261 mRetryCount = 127;
4262 return status;
4263}
4264
4265void AudioFlinger::PlaybackThread::OutputTrack::stop()
4266{
4267 Track::stop();
4268 clearBufferQueue();
4269 mOutBuffer.frameCount = 0;
4270 mActive = false;
4271}
4272
4273bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4274{
4275 Buffer *pInBuffer;
4276 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004277 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004278 bool outputBufferFull = false;
4279 inBuffer.frameCount = frames;
4280 inBuffer.i16 = data;
4281
4282 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4283
4284 if (!mActive && frames != 0) {
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004285 start(0);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004286 sp<ThreadBase> thread = mThread.promote();
4287 if (thread != 0) {
4288 MixerThread *mixerThread = (MixerThread *)thread.get();
4289 if (mCblk->frameCount > frames){
4290 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4291 uint32_t startFrames = (mCblk->frameCount - frames);
4292 pInBuffer = new Buffer;
4293 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4294 pInBuffer->frameCount = startFrames;
4295 pInBuffer->i16 = pInBuffer->mBuffer;
4296 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4297 mBufferQueue.add(pInBuffer);
4298 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004299 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004300 }
4301 }
4302 }
4303 }
4304
4305 while (waitTimeLeftMs) {
4306 // First write pending buffers, then new data
4307 if (mBufferQueue.size()) {
4308 pInBuffer = mBufferQueue.itemAt(0);
4309 } else {
4310 pInBuffer = &inBuffer;
4311 }
4312
4313 if (pInBuffer->frameCount == 0) {
4314 break;
4315 }
4316
4317 if (mOutBuffer.frameCount == 0) {
4318 mOutBuffer.frameCount = pInBuffer->frameCount;
4319 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08004320 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01004321 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004322 outputBufferFull = true;
4323 break;
4324 }
4325 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4326 if (waitTimeLeftMs >= waitTimeMs) {
4327 waitTimeLeftMs -= waitTimeMs;
4328 } else {
4329 waitTimeLeftMs = 0;
4330 }
4331 }
4332
4333 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4334 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4335 mCblk->stepUser(outFrames);
4336 pInBuffer->frameCount -= outFrames;
4337 pInBuffer->i16 += outFrames * channelCount;
4338 mOutBuffer.frameCount -= outFrames;
4339 mOutBuffer.i16 += outFrames * channelCount;
4340
4341 if (pInBuffer->frameCount == 0) {
4342 if (mBufferQueue.size()) {
4343 mBufferQueue.removeAt(0);
4344 delete [] pInBuffer->mBuffer;
4345 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01004346 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004347 } else {
4348 break;
4349 }
4350 }
4351 }
4352
4353 // If we could not write all frames, allocate a buffer and queue it for next time.
4354 if (inBuffer.frameCount) {
4355 sp<ThreadBase> thread = mThread.promote();
4356 if (thread != 0 && !thread->standby()) {
4357 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4358 pInBuffer = new Buffer;
4359 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4360 pInBuffer->frameCount = inBuffer.frameCount;
4361 pInBuffer->i16 = pInBuffer->mBuffer;
4362 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4363 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01004364 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004365 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004366 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004367 }
4368 }
4369 }
4370
4371 // Calling write() with a 0 length buffer, means that no more data will be written:
4372 // If no more buffers are pending, fill output track buffer to make sure it is started
4373 // by output mixer.
4374 if (frames == 0 && mBufferQueue.size() == 0) {
4375 if (mCblk->user < mCblk->frameCount) {
4376 frames = mCblk->frameCount - mCblk->user;
4377 pInBuffer = new Buffer;
4378 pInBuffer->mBuffer = new int16_t[frames * channelCount];
4379 pInBuffer->frameCount = frames;
4380 pInBuffer->i16 = pInBuffer->mBuffer;
4381 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4382 mBufferQueue.add(pInBuffer);
4383 } else if (mActive) {
4384 stop();
4385 }
4386 }
4387
4388 return outputBufferFull;
4389}
4390
4391status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4392{
4393 int active;
4394 status_t result;
4395 audio_track_cblk_t* cblk = mCblk;
4396 uint32_t framesReq = buffer->frameCount;
4397
Steve Block3856b092011-10-20 11:56:00 +01004398// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004399 buffer->frameCount = 0;
4400
4401 uint32_t framesAvail = cblk->framesAvailable();
4402
4403
4404 if (framesAvail == 0) {
4405 Mutex::Autolock _l(cblk->lock);
4406 goto start_loop_here;
4407 while (framesAvail == 0) {
4408 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004409 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004410 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004411 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004412 }
4413 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4414 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004415 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004416 }
4417 // read the server count again
4418 start_loop_here:
4419 framesAvail = cblk->framesAvailable_l();
4420 }
4421 }
4422
4423// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004424// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004425// }
4426
4427 if (framesReq > framesAvail) {
4428 framesReq = framesAvail;
4429 }
4430
4431 uint32_t u = cblk->user;
4432 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4433
4434 if (u + framesReq > bufferEnd) {
4435 framesReq = bufferEnd - u;
4436 }
4437
4438 buffer->frameCount = framesReq;
4439 buffer->raw = (void *)cblk->buffer(u);
4440 return NO_ERROR;
4441}
4442
4443
4444void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4445{
4446 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004447
4448 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004449 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004450 delete [] pBuffer->mBuffer;
4451 delete pBuffer;
4452 }
4453 mBufferQueue.clear();
4454}
4455
4456// ----------------------------------------------------------------------------
4457
4458AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4459 : RefBase(),
4460 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08004461 // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below
Mathias Agopian65ab4712010-07-14 17:59:35 -07004462 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08004463 mPid(pid),
4464 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004465{
4466 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4467}
4468
4469// Client destructor must be called with AudioFlinger::mLock held
4470AudioFlinger::Client::~Client()
4471{
4472 mAudioFlinger->removeClient_l(mPid);
4473}
4474
Glenn Kasten435dbe62012-01-30 10:15:48 -08004475sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004476{
4477 return mMemoryDealer;
4478}
4479
John Grossman4ff14ba2012-02-08 16:37:41 -08004480// Reserve one of the limited slots for a timed audio track associated
4481// with this client
4482bool AudioFlinger::Client::reserveTimedTrack()
4483{
4484 const int kMaxTimedTracksPerClient = 4;
4485
4486 Mutex::Autolock _l(mTimedTrackLock);
4487
4488 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4489 ALOGW("can not create timed track - pid %d has exceeded the limit",
4490 mPid);
4491 return false;
4492 }
4493
4494 mTimedTrackCount++;
4495 return true;
4496}
4497
4498// Release a slot for a timed audio track
4499void AudioFlinger::Client::releaseTimedTrack()
4500{
4501 Mutex::Autolock _l(mTimedTrackLock);
4502 mTimedTrackCount--;
4503}
4504
Mathias Agopian65ab4712010-07-14 17:59:35 -07004505// ----------------------------------------------------------------------------
4506
4507AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4508 const sp<IAudioFlingerClient>& client,
4509 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004510 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004511{
4512}
4513
4514AudioFlinger::NotificationClient::~NotificationClient()
4515{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004516}
4517
4518void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4519{
4520 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08004521 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004522}
4523
4524// ----------------------------------------------------------------------------
4525
4526AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4527 : BnAudioTrack(),
4528 mTrack(track)
4529{
4530}
4531
4532AudioFlinger::TrackHandle::~TrackHandle() {
4533 // just stop the track on deletion, associated resources
4534 // will be freed from the main thread once all pending buffers have
4535 // been played. Unless it's not in the active track list, in which
4536 // case we free everything now...
4537 mTrack->destroy();
4538}
4539
Glenn Kasten90716c52012-01-26 13:40:12 -08004540sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4541 return mTrack->getCblk();
4542}
4543
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004544status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4545 return mTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004546}
4547
4548void AudioFlinger::TrackHandle::stop() {
4549 mTrack->stop();
4550}
4551
4552void AudioFlinger::TrackHandle::flush() {
4553 mTrack->flush();
4554}
4555
4556void AudioFlinger::TrackHandle::mute(bool e) {
4557 mTrack->mute(e);
4558}
4559
4560void AudioFlinger::TrackHandle::pause() {
4561 mTrack->pause();
4562}
4563
Mathias Agopian65ab4712010-07-14 17:59:35 -07004564status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4565{
4566 return mTrack->attachAuxEffect(EffectId);
4567}
4568
John Grossman4ff14ba2012-02-08 16:37:41 -08004569status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4570 sp<IMemory>* buffer) {
4571 if (!mTrack->isTimedTrack())
4572 return INVALID_OPERATION;
4573
4574 PlaybackThread::TimedTrack* tt =
4575 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4576 return tt->allocateTimedBuffer(size, buffer);
4577}
4578
4579status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4580 int64_t pts) {
4581 if (!mTrack->isTimedTrack())
4582 return INVALID_OPERATION;
4583
4584 PlaybackThread::TimedTrack* tt =
4585 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4586 return tt->queueTimedBuffer(buffer, pts);
4587}
4588
4589status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4590 const LinearTransform& xform, int target) {
4591
4592 if (!mTrack->isTimedTrack())
4593 return INVALID_OPERATION;
4594
4595 PlaybackThread::TimedTrack* tt =
4596 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4597 return tt->setMediaTimeTransform(
4598 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4599}
4600
Mathias Agopian65ab4712010-07-14 17:59:35 -07004601status_t AudioFlinger::TrackHandle::onTransact(
4602 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4603{
4604 return BnAudioTrack::onTransact(code, data, reply, flags);
4605}
4606
4607// ----------------------------------------------------------------------------
4608
4609sp<IAudioRecord> AudioFlinger::openRecord(
4610 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004611 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004612 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004613 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004614 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004615 int frameCount,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004616 // FIXME dead, remove from IAudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -07004617 uint32_t flags,
4618 int *sessionId,
4619 status_t *status)
4620{
4621 sp<RecordThread::RecordTrack> recordTrack;
4622 sp<RecordHandle> recordHandle;
4623 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004624 status_t lStatus;
4625 RecordThread *thread;
4626 size_t inFrameCount;
4627 int lSessionId;
4628
4629 // check calling permissions
4630 if (!recordingAllowed()) {
4631 lStatus = PERMISSION_DENIED;
4632 goto Exit;
4633 }
4634
4635 // add client to list
4636 { // scope for mLock
4637 Mutex::Autolock _l(mLock);
4638 thread = checkRecordThread_l(input);
4639 if (thread == NULL) {
4640 lStatus = BAD_VALUE;
4641 goto Exit;
4642 }
4643
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004644 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004645
4646 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004647 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004648 lSessionId = *sessionId;
4649 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004650 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004651 if (sessionId != NULL) {
4652 *sessionId = lSessionId;
4653 }
4654 }
4655 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004656 recordTrack = thread->createRecordTrack_l(client,
4657 sampleRate,
4658 format,
4659 channelMask,
4660 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004661 lSessionId,
4662 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004663 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004664 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004665 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4666 // destructor is called by the TrackBase destructor with mLock held
4667 client.clear();
4668 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004669 goto Exit;
4670 }
4671
4672 // return to handle to client
4673 recordHandle = new RecordHandle(recordTrack);
4674 lStatus = NO_ERROR;
4675
4676Exit:
4677 if (status) {
4678 *status = lStatus;
4679 }
4680 return recordHandle;
4681}
4682
4683// ----------------------------------------------------------------------------
4684
4685AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4686 : BnAudioRecord(),
4687 mRecordTrack(recordTrack)
4688{
4689}
4690
4691AudioFlinger::RecordHandle::~RecordHandle() {
4692 stop();
4693}
4694
Glenn Kasten90716c52012-01-26 13:40:12 -08004695sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4696 return mRecordTrack->getCblk();
4697}
4698
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004699status_t AudioFlinger::RecordHandle::start(pid_t tid) {
Steve Block3856b092011-10-20 11:56:00 +01004700 ALOGV("RecordHandle::start()");
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004701 return mRecordTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004702}
4703
4704void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004705 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004706 mRecordTrack->stop();
4707}
4708
Mathias Agopian65ab4712010-07-14 17:59:35 -07004709status_t AudioFlinger::RecordHandle::onTransact(
4710 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4711{
4712 return BnAudioRecord::onTransact(code, data, reply, flags);
4713}
4714
4715// ----------------------------------------------------------------------------
4716
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004717AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4718 AudioStreamIn *input,
4719 uint32_t sampleRate,
4720 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004721 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004722 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004723 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004724 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4725 // mRsmpInIndex and mInputBytes set by readInputParameters()
4726 mReqChannelCount(popcount(channels)),
4727 mReqSampleRate(sampleRate)
4728 // mBytesRead is only meaningful while active, and so is cleared in start()
4729 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004730{
Glenn Kasten480b4682012-02-28 12:30:08 -08004731 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07004732
Mathias Agopian65ab4712010-07-14 17:59:35 -07004733 readInputParameters();
4734}
4735
4736
4737AudioFlinger::RecordThread::~RecordThread()
4738{
4739 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004740 delete mResampler;
4741 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004742}
4743
4744void AudioFlinger::RecordThread::onFirstRef()
4745{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004746 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004747}
4748
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004749status_t AudioFlinger::RecordThread::readyToRun()
4750{
4751 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004752 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004753 return status;
4754}
4755
Mathias Agopian65ab4712010-07-14 17:59:35 -07004756bool AudioFlinger::RecordThread::threadLoop()
4757{
4758 AudioBufferProvider::Buffer buffer;
4759 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004760 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004761
Eric Laurent44d98482010-09-30 16:12:31 -07004762 nsecs_t lastWarning = 0;
4763
Eric Laurentfeb0db62011-07-22 09:04:31 -07004764 acquireWakeLock();
4765
Mathias Agopian65ab4712010-07-14 17:59:35 -07004766 // start recording
4767 while (!exitPending()) {
4768
4769 processConfigEvents();
4770
4771 { // scope for mLock
4772 Mutex::Autolock _l(mLock);
4773 checkForNewParameters_l();
4774 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4775 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004776 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004777 mStandby = true;
4778 }
4779
4780 if (exitPending()) break;
4781
Eric Laurentfeb0db62011-07-22 09:04:31 -07004782 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004783 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004784 // go to sleep
4785 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004786 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004787 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004788 continue;
4789 }
4790 if (mActiveTrack != 0) {
4791 if (mActiveTrack->mState == TrackBase::PAUSING) {
4792 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004793 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004794 mStandby = true;
4795 }
4796 mActiveTrack.clear();
4797 mStartStopCond.broadcast();
4798 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4799 if (mReqChannelCount != mActiveTrack->channelCount()) {
4800 mActiveTrack.clear();
4801 mStartStopCond.broadcast();
4802 } else if (mBytesRead != 0) {
4803 // record start succeeds only if first read from audio input
4804 // succeeds
4805 if (mBytesRead > 0) {
4806 mActiveTrack->mState = TrackBase::ACTIVE;
4807 } else {
4808 mActiveTrack.clear();
4809 }
4810 mStartStopCond.broadcast();
4811 }
4812 mStandby = false;
4813 }
4814 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004815 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004816 }
4817
4818 if (mActiveTrack != 0) {
4819 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4820 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004821 unlockEffectChains(effectChains);
4822 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004823 continue;
4824 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004825 for (size_t i = 0; i < effectChains.size(); i ++) {
4826 effectChains[i]->process_l();
4827 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004828
Mathias Agopian65ab4712010-07-14 17:59:35 -07004829 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004830 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004831 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004832 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004833 // no resampling
4834 while (framesOut) {
4835 size_t framesIn = mFrameCount - mRsmpInIndex;
4836 if (framesIn) {
4837 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4838 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4839 if (framesIn > framesOut)
4840 framesIn = framesOut;
4841 mRsmpInIndex += framesIn;
4842 framesOut -= framesIn;
4843 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004844 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004845 memcpy(dst, src, framesIn * mFrameSize);
4846 } else {
4847 int16_t *src16 = (int16_t *)src;
4848 int16_t *dst16 = (int16_t *)dst;
4849 if (mChannelCount == 1) {
4850 while (framesIn--) {
4851 *dst16++ = *src16;
4852 *dst16++ = *src16++;
4853 }
4854 } else {
4855 while (framesIn--) {
4856 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4857 src16 += 2;
4858 }
4859 }
4860 }
4861 }
4862 if (framesOut && mFrameCount == mRsmpInIndex) {
4863 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004864 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004865 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004866 framesOut = 0;
4867 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004868 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004869 mRsmpInIndex = 0;
4870 }
4871 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004872 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004873 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4874 // Force input into standby so that it tries to
4875 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004876 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004877 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004878 }
4879 mRsmpInIndex = mFrameCount;
4880 framesOut = 0;
4881 buffer.frameCount = 0;
4882 }
4883 }
4884 }
4885 } else {
4886 // resampling
4887
4888 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4889 // alter output frame count as if we were expecting stereo samples
4890 if (mChannelCount == 1 && mReqChannelCount == 1) {
4891 framesOut >>= 1;
4892 }
4893 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4894 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4895 // are 32 bit aligned which should be always true.
4896 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004897 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004898 // the resampler always outputs stereo samples: do post stereo to mono conversion
4899 int16_t *src = (int16_t *)mRsmpOutBuffer;
4900 int16_t *dst = buffer.i16;
4901 while (framesOut--) {
4902 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4903 src += 2;
4904 }
4905 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004906 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004907 }
4908
4909 }
4910 mActiveTrack->releaseBuffer(&buffer);
4911 mActiveTrack->overflow();
4912 }
4913 // client isn't retrieving buffers fast enough
4914 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004915 if (!mActiveTrack->setOverflow()) {
4916 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004917 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004918 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004919 lastWarning = now;
4920 }
4921 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004922 // Release the processor for a while before asking for a new buffer.
4923 // This will give the application more chance to read from the buffer and
4924 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004925 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004926 }
4927 }
Eric Laurentec437d82011-07-26 20:54:46 -07004928 // enable changes in effect chain
4929 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004930 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004931 }
4932
4933 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004934 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004935 }
4936 mActiveTrack.clear();
4937
4938 mStartStopCond.broadcast();
4939
Eric Laurentfeb0db62011-07-22 09:04:31 -07004940 releaseWakeLock();
4941
Steve Block3856b092011-10-20 11:56:00 +01004942 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004943 return false;
4944}
4945
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004946
4947sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4948 const sp<AudioFlinger::Client>& client,
4949 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004950 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004951 int channelMask,
4952 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004953 int sessionId,
4954 status_t *status)
4955{
4956 sp<RecordTrack> track;
4957 status_t lStatus;
4958
4959 lStatus = initCheck();
4960 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004961 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004962 goto Exit;
4963 }
4964
4965 { // scope for mLock
4966 Mutex::Autolock _l(mLock);
4967
4968 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004969 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004970
Glenn Kasten7378ca52012-01-20 13:44:40 -08004971 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004972 lStatus = NO_MEMORY;
4973 goto Exit;
4974 }
4975
4976 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004977 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4978 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004979 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004980 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4981 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004982 }
4983 lStatus = NO_ERROR;
4984
4985Exit:
4986 if (status) {
4987 *status = lStatus;
4988 }
4989 return track;
4990}
4991
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004992status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004993{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004994 ALOGV("RecordThread::start tid=%d", tid);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004995 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004996 status_t status = NO_ERROR;
4997 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004998 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004999 if (mActiveTrack != 0) {
5000 if (recordTrack != mActiveTrack.get()) {
5001 status = -EBUSY;
5002 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5003 mActiveTrack->mState = TrackBase::ACTIVE;
5004 }
5005 return status;
5006 }
5007
5008 recordTrack->mState = TrackBase::IDLE;
5009 mActiveTrack = recordTrack;
5010 mLock.unlock();
5011 status_t status = AudioSystem::startInput(mId);
5012 mLock.lock();
5013 if (status != NO_ERROR) {
5014 mActiveTrack.clear();
5015 return status;
5016 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005017 mRsmpInIndex = mFrameCount;
5018 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005019 if (mResampler != NULL) {
5020 mResampler->reset();
5021 }
5022 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005023 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005024 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005025 mWaitWorkCV.signal();
5026 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005027 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005028 mActiveTrack.clear();
5029 status = INVALID_OPERATION;
5030 goto startError;
5031 }
5032 mStartStopCond.wait(mLock);
5033 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005034 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005035 status = BAD_VALUE;
5036 goto startError;
5037 }
Steve Block3856b092011-10-20 11:56:00 +01005038 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005039 return status;
5040 }
5041startError:
5042 AudioSystem::stopInput(mId);
5043 return status;
5044}
5045
5046void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005047 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005048 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005049 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005050 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005051 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5052 mActiveTrack->mState = TrackBase::PAUSING;
5053 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005054 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005055 return;
5056 }
5057 mStartStopCond.wait(mLock);
5058 // if we have been restarted, recordTrack == mActiveTrack.get() here
5059 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5060 mLock.unlock();
5061 AudioSystem::stopInput(mId);
5062 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005063 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005064 }
5065 }
5066 }
5067}
5068
5069status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5070{
5071 const size_t SIZE = 256;
5072 char buffer[SIZE];
5073 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005074
5075 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5076 result.append(buffer);
5077
5078 if (mActiveTrack != 0) {
5079 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005080 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005081 mActiveTrack->dump(buffer, SIZE);
5082 result.append(buffer);
5083
5084 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5085 result.append(buffer);
5086 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5087 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005088 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005089 result.append(buffer);
5090 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5091 result.append(buffer);
5092 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5093 result.append(buffer);
5094
5095
5096 } else {
5097 result.append("No record client\n");
5098 }
5099 write(fd, result.string(), result.size());
5100
5101 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005102 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005103
5104 return NO_ERROR;
5105}
5106
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005107// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005108status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005109{
5110 size_t framesReq = buffer->frameCount;
5111 size_t framesReady = mFrameCount - mRsmpInIndex;
5112 int channelCount;
5113
5114 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005115 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005116 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005117 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005118 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5119 // Force input into standby so that it tries to
5120 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005121 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005122 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005123 }
Glenn Kastene0feee32011-12-13 11:53:26 -08005124 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005125 buffer->frameCount = 0;
5126 return NOT_ENOUGH_DATA;
5127 }
5128 mRsmpInIndex = 0;
5129 framesReady = mFrameCount;
5130 }
5131
5132 if (framesReq > framesReady) {
5133 framesReq = framesReady;
5134 }
5135
5136 if (mChannelCount == 1 && mReqChannelCount == 2) {
5137 channelCount = 1;
5138 } else {
5139 channelCount = 2;
5140 }
5141 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5142 buffer->frameCount = framesReq;
5143 return NO_ERROR;
5144}
5145
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005146// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07005147void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5148{
5149 mRsmpInIndex += buffer->frameCount;
5150 buffer->frameCount = 0;
5151}
5152
5153bool AudioFlinger::RecordThread::checkForNewParameters_l()
5154{
5155 bool reconfig = false;
5156
5157 while (!mNewParameters.isEmpty()) {
5158 status_t status = NO_ERROR;
5159 String8 keyValuePair = mNewParameters[0];
5160 AudioParameter param = AudioParameter(keyValuePair);
5161 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08005162 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005163 int reqSamplingRate = mReqSampleRate;
5164 int reqChannelCount = mReqChannelCount;
5165
5166 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5167 reqSamplingRate = value;
5168 reconfig = true;
5169 }
5170 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08005171 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005172 reconfig = true;
5173 }
5174 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005175 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005176 reconfig = true;
5177 }
5178 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5179 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08005180 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005181 // if frame count is changed after track creation
5182 if (mActiveTrack != 0) {
5183 status = INVALID_OPERATION;
5184 } else {
5185 reconfig = true;
5186 }
5187 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005188 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5189 // forward device change to effects that have requested to be
5190 // aware of attached audio device.
5191 for (size_t i = 0; i < mEffectChains.size(); i++) {
5192 mEffectChains[i]->setDevice_l(value);
5193 }
5194 // store input device and output device but do not forward output device to audio HAL.
5195 // Note that status is ignored by the caller for output device
5196 // (see AudioFlinger::setParameters()
5197 if (value & AUDIO_DEVICE_OUT_ALL) {
5198 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5199 status = BAD_VALUE;
5200 } else {
5201 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07005202 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5203 if (mTrack != NULL) {
5204 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005205 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005206 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5207 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5208 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005209 }
5210 mDevice |= (uint32_t)value;
5211 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005212 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005213 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005214 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005215 mInput->stream->common.standby(&mInput->stream->common);
5216 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5217 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005218 }
5219 if (reconfig) {
5220 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005221 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005222 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005223 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08005224 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
5225 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005226 status = NO_ERROR;
5227 }
5228 if (status == NO_ERROR) {
5229 readInputParameters();
5230 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5231 }
5232 }
5233 }
5234
5235 mNewParameters.removeAt(0);
5236
5237 mParamStatus = status;
5238 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07005239 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5240 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08005241 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005242 }
5243 return reconfig;
5244}
5245
5246String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5247{
Dima Zavinfce7a472011-04-19 22:30:36 -07005248 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005249 String8 out_s8 = String8();
5250
5251 Mutex::Autolock _l(mLock);
5252 if (initCheck() != NO_ERROR) {
5253 return out_s8;
5254 }
Dima Zavinfce7a472011-04-19 22:30:36 -07005255
Dima Zavin799a70e2011-04-18 16:57:27 -07005256 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07005257 out_s8 = String8(s);
5258 free(s);
5259 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005260}
5261
5262void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5263 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08005264 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005265
5266 switch (event) {
5267 case AudioSystem::INPUT_OPENED:
5268 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005269 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005270 desc.samplingRate = mSampleRate;
5271 desc.format = mFormat;
5272 desc.frameCount = mFrameCount;
5273 desc.latency = 0;
5274 param2 = &desc;
5275 break;
5276
5277 case AudioSystem::INPUT_CLOSED:
5278 default:
5279 break;
5280 }
5281 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5282}
5283
5284void AudioFlinger::RecordThread::readInputParameters()
5285{
Glenn Kastene9dd0172012-01-27 18:08:45 -08005286 delete mRsmpInBuffer;
5287 // mRsmpInBuffer is always assigned a new[] below
5288 delete mRsmpOutBuffer;
5289 mRsmpOutBuffer = NULL;
5290 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08005291 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005292
Dima Zavin799a70e2011-04-18 16:57:27 -07005293 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005294 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5295 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07005296 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08005297 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07005298 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005299 mFrameCount = mInputBytes / mFrameSize;
5300 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5301
Glenn Kasten53d76db2012-03-08 12:32:47 -08005302 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005303 {
5304 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005305 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5306 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005307 if (mChannelCount == 1 && mReqChannelCount == 2) {
5308 channelCount = 1;
5309 } else {
5310 channelCount = 2;
5311 }
5312 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5313 mResampler->setSampleRate(mSampleRate);
5314 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5315 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5316
5317 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5318 if (mChannelCount == 1 && mReqChannelCount == 1) {
5319 mFrameCount >>= 1;
5320 }
5321
5322 }
5323 mRsmpInIndex = mFrameCount;
5324}
5325
5326unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5327{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005328 Mutex::Autolock _l(mLock);
5329 if (initCheck() != NO_ERROR) {
5330 return 0;
5331 }
5332
Dima Zavin799a70e2011-04-18 16:57:27 -07005333 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005334}
5335
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005336uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5337{
5338 Mutex::Autolock _l(mLock);
5339 uint32_t result = 0;
5340 if (getEffectChain_l(sessionId) != 0) {
5341 result = EFFECT_SESSION;
5342 }
5343
5344 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5345 result |= TRACK_SESSION;
5346 }
5347
5348 return result;
5349}
5350
Eric Laurent59bd0da2011-08-01 09:52:20 -07005351AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5352{
5353 Mutex::Autolock _l(mLock);
5354 return mTrack;
5355}
5356
Glenn Kastenaed850d2012-01-26 09:46:34 -08005357AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005358{
5359 Mutex::Autolock _l(mLock);
5360 return mInput;
5361}
5362
5363AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5364{
5365 Mutex::Autolock _l(mLock);
5366 AudioStreamIn *input = mInput;
5367 mInput = NULL;
5368 return input;
5369}
5370
5371// this method must always be called either with ThreadBase mLock held or inside the thread loop
5372audio_stream_t* AudioFlinger::RecordThread::stream()
5373{
5374 if (mInput == NULL) {
5375 return NULL;
5376 }
5377 return &mInput->stream->common;
5378}
5379
5380
Mathias Agopian65ab4712010-07-14 17:59:35 -07005381// ----------------------------------------------------------------------------
5382
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005383audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005384 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005385 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005386 uint32_t *pChannels,
5387 uint32_t *pLatencyMs,
Glenn Kasten18868c52012-03-07 09:15:37 -08005388 audio_policy_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005389{
5390 status_t status;
5391 PlaybackThread *thread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005392 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005393 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005394 uint32_t channels = pChannels ? *pChannels : 0;
5395 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07005396 audio_stream_out_t *outStream;
5397 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005398
Steve Block3856b092011-10-20 11:56:00 +01005399 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07005400 pDevices ? *pDevices : 0,
5401 samplingRate,
5402 format,
5403 channels,
5404 flags);
5405
5406 if (pDevices == NULL || *pDevices == 0) {
5407 return 0;
5408 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005409
Mathias Agopian65ab4712010-07-14 17:59:35 -07005410 Mutex::Autolock _l(mLock);
5411
Dima Zavin799a70e2011-04-18 16:57:27 -07005412 outHwDev = findSuitableHwDev_l(*pDevices);
5413 if (outHwDev == NULL)
5414 return 0;
5415
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005416 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Glenn Kasten58f30212012-01-12 12:27:51 -08005417 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005418 &channels, &samplingRate, &outStream);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005419 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01005420 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005421 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005422 samplingRate,
5423 format,
5424 channels,
5425 status);
5426
Dima Zavin799a70e2011-04-18 16:57:27 -07005427 if (outStream != NULL) {
5428 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005429 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07005430
Dima Zavinfce7a472011-04-19 22:30:36 -07005431 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5432 (format != AUDIO_FORMAT_PCM_16_BIT) ||
5433 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005434 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005435 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005436 } else {
5437 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005438 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005439 }
5440 mPlaybackThreads.add(id, thread);
5441
Glenn Kastena0d68332012-01-27 16:47:15 -08005442 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5443 if (pFormat != NULL) *pFormat = format;
5444 if (pChannels != NULL) *pChannels = channels;
5445 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005446
5447 // notify client processes of the new output creation
5448 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5449 return id;
5450 }
5451
5452 return 0;
5453}
5454
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005455audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
5456 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005457{
5458 Mutex::Autolock _l(mLock);
5459 MixerThread *thread1 = checkMixerThread_l(output1);
5460 MixerThread *thread2 = checkMixerThread_l(output2);
5461
5462 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005463 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005464 return 0;
5465 }
5466
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005467 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005468 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5469 thread->addOutputTrack(thread2);
5470 mPlaybackThreads.add(id, thread);
5471 // notify client processes of the new output creation
5472 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5473 return id;
5474}
5475
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005476status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005477{
5478 // keep strong reference on the playback thread so that
5479 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005480 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005481 {
5482 Mutex::Autolock _l(mLock);
5483 thread = checkPlaybackThread_l(output);
5484 if (thread == NULL) {
5485 return BAD_VALUE;
5486 }
5487
Steve Block3856b092011-10-20 11:56:00 +01005488 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005489
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005490 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005491 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005492 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005493 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5494 dupThread->removeOutputTrack((MixerThread *)thread.get());
5495 }
5496 }
5497 }
Glenn Kastena1117922012-01-26 10:53:32 -08005498 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005499 mPlaybackThreads.removeItem(output);
5500 }
5501 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005502 // The thread entity (active unit of execution) is no longer running here,
5503 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005504
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005505 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005506 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005507 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005508 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005509 out->hwDev->close_output_stream(out->hwDev, out->stream);
5510 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005511 }
5512 return NO_ERROR;
5513}
5514
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005515status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005516{
5517 Mutex::Autolock _l(mLock);
5518 PlaybackThread *thread = checkPlaybackThread_l(output);
5519
5520 if (thread == NULL) {
5521 return BAD_VALUE;
5522 }
5523
Steve Block3856b092011-10-20 11:56:00 +01005524 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005525 thread->suspend();
5526
5527 return NO_ERROR;
5528}
5529
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005530status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005531{
5532 Mutex::Autolock _l(mLock);
5533 PlaybackThread *thread = checkPlaybackThread_l(output);
5534
5535 if (thread == NULL) {
5536 return BAD_VALUE;
5537 }
5538
Steve Block3856b092011-10-20 11:56:00 +01005539 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005540
5541 thread->restore();
5542
5543 return NO_ERROR;
5544}
5545
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005546audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005547 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005548 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005549 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005550 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005551{
5552 status_t status;
5553 RecordThread *thread = NULL;
5554 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005555 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005556 uint32_t channels = pChannels ? *pChannels : 0;
5557 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005558 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005559 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005560 audio_stream_in_t *inStream;
5561 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005562
5563 if (pDevices == NULL || *pDevices == 0) {
5564 return 0;
5565 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005566
Mathias Agopian65ab4712010-07-14 17:59:35 -07005567 Mutex::Autolock _l(mLock);
5568
Dima Zavin799a70e2011-04-18 16:57:27 -07005569 inHwDev = findSuitableHwDev_l(*pDevices);
5570 if (inHwDev == NULL)
5571 return 0;
5572
Glenn Kasten58f30212012-01-12 12:27:51 -08005573 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005574 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005575 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005576 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005577 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005578 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005579 samplingRate,
5580 format,
5581 channels,
5582 acoustics,
5583 status);
5584
5585 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5586 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5587 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005588 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005589 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005590 (samplingRate <= 2 * reqSamplingRate) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08005591 (popcount(channels) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01005592 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005593 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005594 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005595 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005596 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005597 }
5598
Dima Zavin799a70e2011-04-18 16:57:27 -07005599 if (inStream != NULL) {
5600 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5601
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005602 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005603 // Start record thread
5604 // RecorThread require both input and output device indication to forward to audio
5605 // pre processing modules
5606 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5607 thread = new RecordThread(this,
5608 input,
5609 reqSamplingRate,
5610 reqChannels,
5611 id,
5612 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005613 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005614 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005615 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5616 if (pFormat != NULL) *pFormat = format;
5617 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005618
Dima Zavin799a70e2011-04-18 16:57:27 -07005619 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005620
5621 // notify client processes of the new input creation
5622 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5623 return id;
5624 }
5625
5626 return 0;
5627}
5628
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005629status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005630{
5631 // keep strong reference on the record thread so that
5632 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005633 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005634 {
5635 Mutex::Autolock _l(mLock);
5636 thread = checkRecordThread_l(input);
5637 if (thread == NULL) {
5638 return BAD_VALUE;
5639 }
5640
Steve Block3856b092011-10-20 11:56:00 +01005641 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08005642 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005643 mRecordThreads.removeItem(input);
5644 }
5645 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005646 // The thread entity (active unit of execution) is no longer running here,
5647 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005648
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005649 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005650 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005651 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005652 in->hwDev->close_input_stream(in->hwDev, in->stream);
5653 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005654
5655 return NO_ERROR;
5656}
5657
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005658status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005659{
5660 Mutex::Autolock _l(mLock);
5661 MixerThread *dstThread = checkMixerThread_l(output);
5662 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005663 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005664 return BAD_VALUE;
5665 }
5666
Steve Block3856b092011-10-20 11:56:00 +01005667 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005668 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5669
Eric Laurent9f6530f2011-08-30 10:18:54 -07005670 dstThread->setStreamValid(stream, true);
5671
Mathias Agopian65ab4712010-07-14 17:59:35 -07005672 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5673 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08005674 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005675 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005676 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005677 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005678 }
Eric Laurentde070132010-07-13 04:45:46 -07005679 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005680
5681 return NO_ERROR;
5682}
5683
5684
5685int AudioFlinger::newAudioSessionId()
5686{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005687 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005688}
5689
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005690void AudioFlinger::acquireAudioSessionId(int audioSession)
5691{
5692 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005693 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005694 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005695 size_t num = mAudioSessionRefs.size();
5696 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005697 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005698 if (ref->mSessionid == audioSession && ref->mPid == caller) {
5699 ref->mCnt++;
5700 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005701 return;
5702 }
5703 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005704 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5705 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005706}
5707
5708void AudioFlinger::releaseAudioSessionId(int audioSession)
5709{
5710 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005711 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005712 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005713 size_t num = mAudioSessionRefs.size();
5714 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005715 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005716 if (ref->mSessionid == audioSession && ref->mPid == caller) {
5717 ref->mCnt--;
5718 ALOGV(" decremented refcount to %d", ref->mCnt);
5719 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005720 mAudioSessionRefs.removeAt(i);
5721 delete ref;
5722 purgeStaleEffects_l();
5723 }
5724 return;
5725 }
5726 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005727 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005728}
5729
5730void AudioFlinger::purgeStaleEffects_l() {
5731
Steve Block3856b092011-10-20 11:56:00 +01005732 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005733
5734 Vector< sp<EffectChain> > chains;
5735
5736 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5737 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5738 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5739 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005740 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5741 chains.push(ec);
5742 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005743 }
5744 }
5745 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5746 sp<RecordThread> t = mRecordThreads.valueAt(i);
5747 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5748 sp<EffectChain> ec = t->mEffectChains[j];
5749 chains.push(ec);
5750 }
5751 }
5752
5753 for (size_t i = 0; i < chains.size(); i++) {
5754 sp<EffectChain> ec = chains[i];
5755 int sessionid = ec->sessionId();
5756 sp<ThreadBase> t = ec->mThread.promote();
5757 if (t == 0) {
5758 continue;
5759 }
5760 size_t numsessionrefs = mAudioSessionRefs.size();
5761 bool found = false;
5762 for (size_t k = 0; k < numsessionrefs; k++) {
5763 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005764 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005765 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005766 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005767 found = true;
5768 break;
5769 }
5770 }
5771 if (!found) {
5772 // remove all effects from the chain
5773 while (ec->mEffects.size()) {
5774 sp<EffectModule> effect = ec->mEffects[0];
5775 effect->unPin();
5776 Mutex::Autolock _l (t->mLock);
5777 t->removeEffect_l(effect);
5778 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5779 sp<EffectHandle> handle = effect->mHandles[j].promote();
5780 if (handle != 0) {
5781 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005782 if (handle->mHasControl && handle->mEnabled) {
5783 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5784 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005785 }
5786 }
5787 AudioSystem::unregisterEffect(effect->id());
5788 }
5789 }
5790 }
5791 return;
5792}
5793
Mathias Agopian65ab4712010-07-14 17:59:35 -07005794// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005795AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005796{
Glenn Kastena1117922012-01-26 10:53:32 -08005797 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005798}
5799
5800// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005801AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005802{
5803 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08005804 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005805}
5806
5807// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005808AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005809{
Glenn Kastena1117922012-01-26 10:53:32 -08005810 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005811}
5812
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005813uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005814{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005815 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005816}
5817
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08005818AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005819{
5820 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5821 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005822 AudioStreamOut *output = thread->getOutput();
5823 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005824 return thread;
5825 }
5826 }
5827 return NULL;
5828}
5829
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08005830uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005831{
5832 PlaybackThread *thread = primaryPlaybackThread_l();
5833
5834 if (thread == NULL) {
5835 return 0;
5836 }
5837
5838 return thread->device();
5839}
5840
5841
Mathias Agopian65ab4712010-07-14 17:59:35 -07005842// ----------------------------------------------------------------------------
5843// Effect management
5844// ----------------------------------------------------------------------------
5845
5846
Glenn Kastenf587ba52012-01-26 16:25:10 -08005847status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005848{
5849 Mutex::Autolock _l(mLock);
5850 return EffectQueryNumberEffects(numEffects);
5851}
5852
Glenn Kastenf587ba52012-01-26 16:25:10 -08005853status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005854{
5855 Mutex::Autolock _l(mLock);
5856 return EffectQueryEffect(index, descriptor);
5857}
5858
Glenn Kasten5e92a782012-01-30 07:40:52 -08005859status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08005860 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005861{
5862 Mutex::Autolock _l(mLock);
5863 return EffectGetDescriptor(pUuid, descriptor);
5864}
5865
5866
Mathias Agopian65ab4712010-07-14 17:59:35 -07005867sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5868 effect_descriptor_t *pDesc,
5869 const sp<IEffectClient>& effectClient,
5870 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005871 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005872 int sessionId,
5873 status_t *status,
5874 int *id,
5875 int *enabled)
5876{
5877 status_t lStatus = NO_ERROR;
5878 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005879 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005880
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005881 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005882 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005883
5884 if (pDesc == NULL) {
5885 lStatus = BAD_VALUE;
5886 goto Exit;
5887 }
5888
Eric Laurent84e9a102010-09-23 16:10:16 -07005889 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005890 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005891 lStatus = PERMISSION_DENIED;
5892 goto Exit;
5893 }
5894
Dima Zavinfce7a472011-04-19 22:30:36 -07005895 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005896 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08005897 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005898 lStatus = PERMISSION_DENIED;
5899 goto Exit;
5900 }
5901
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005902 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005903 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005904 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005905 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005906 lStatus = BAD_VALUE;
5907 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005908 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005909 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005910 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005911 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005912 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005913 }
5914 }
5915
Mathias Agopian65ab4712010-07-14 17:59:35 -07005916 {
5917 Mutex::Autolock _l(mLock);
5918
Mathias Agopian65ab4712010-07-14 17:59:35 -07005919
5920 if (!EffectIsNullUuid(&pDesc->uuid)) {
5921 // if uuid is specified, request effect descriptor
5922 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5923 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005924 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005925 goto Exit;
5926 }
5927 } else {
5928 // if uuid is not specified, look for an available implementation
5929 // of the required type in effect factory
5930 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005931 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005932 lStatus = BAD_VALUE;
5933 goto Exit;
5934 }
5935 uint32_t numEffects = 0;
5936 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005937 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005938 bool found = false;
5939
5940 lStatus = EffectQueryNumberEffects(&numEffects);
5941 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005942 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005943 goto Exit;
5944 }
5945 for (uint32_t i = 0; i < numEffects; i++) {
5946 lStatus = EffectQueryEffect(i, &desc);
5947 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005948 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005949 continue;
5950 }
5951 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5952 // If matching type found save effect descriptor. If the session is
5953 // 0 and the effect is not auxiliary, continue enumeration in case
5954 // an auxiliary version of this effect type is available
5955 found = true;
5956 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005957 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005958 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5959 break;
5960 }
5961 }
5962 }
5963 if (!found) {
5964 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00005965 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005966 goto Exit;
5967 }
5968 // For same effect type, chose auxiliary version over insert version if
5969 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005970 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005971 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5972 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5973 }
5974 }
5975
5976 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005977 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005978 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5979 lStatus = INVALID_OPERATION;
5980 goto Exit;
5981 }
5982
Eric Laurent59255e42011-07-27 19:49:51 -07005983 // check recording permission for visualizer
5984 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5985 !recordingAllowed()) {
5986 lStatus = PERMISSION_DENIED;
5987 goto Exit;
5988 }
5989
Mathias Agopian65ab4712010-07-14 17:59:35 -07005990 // return effect descriptor
5991 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5992
5993 // If output is not specified try to find a matching audio session ID in one of the
5994 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005995 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5996 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005997 // Note: io is never 0 when creating an effect on an input
5998 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005999 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07006000 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6001 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006002 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07006003 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07006004 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006005 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006006 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006007 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6008 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6009 io = mRecordThreads.keyAt(i);
6010 break;
6011 }
6012 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006013 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006014 // If no output thread contains the requested session ID, default to
6015 // first output. The effect chain will be moved to the correct output
6016 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006017 if (io == 0 && mPlaybackThreads.size()) {
6018 io = mPlaybackThreads.keyAt(0);
6019 }
Steve Block3856b092011-10-20 11:56:00 +01006020 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006021 }
6022 ThreadBase *thread = checkRecordThread_l(io);
6023 if (thread == NULL) {
6024 thread = checkPlaybackThread_l(io);
6025 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00006026 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006027 lStatus = BAD_VALUE;
6028 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07006029 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006030 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006031
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006032 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006033
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006034 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07006035 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6036 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006037 if (handle != 0 && id != NULL) {
6038 *id = handle->id();
6039 }
6040 }
6041
6042Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006043 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006044 *status = lStatus;
6045 }
6046 return handle;
6047}
6048
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006049status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
6050 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07006051{
Steve Block3856b092011-10-20 11:56:00 +01006052 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07006053 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006054 Mutex::Autolock _l(mLock);
6055 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006056 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006057 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006058 }
Eric Laurentde070132010-07-13 04:45:46 -07006059 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6060 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006061 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006062 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006063 }
Eric Laurentde070132010-07-13 04:45:46 -07006064 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6065 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006066 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006067 return BAD_VALUE;
6068 }
6069
6070 Mutex::Autolock _dl(dstThread->mLock);
6071 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07006072 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07006073
Mathias Agopian65ab4712010-07-14 17:59:35 -07006074 return NO_ERROR;
6075}
6076
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006077// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07006078status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07006079 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07006080 AudioFlinger::PlaybackThread *dstThread,
6081 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07006082{
Steve Block3856b092011-10-20 11:56:00 +01006083 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006084 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07006085
Eric Laurent59255e42011-07-27 19:49:51 -07006086 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006087 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006088 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006089 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07006090 return INVALID_OPERATION;
6091 }
6092
Eric Laurent39e94f82010-07-28 01:32:47 -07006093 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07006094 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07006095 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07006096 // removed.
6097 srcThread->removeEffectChain_l(chain);
6098
6099 // transfer all effects one by one so that new effect chain is created on new thread with
6100 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006101 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07006102 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006103 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07006104 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6105 while (effect != 0) {
6106 srcThread->removeEffect_l(effect);
6107 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07006108 // removeEffect_l() has stopped the effect if it was active so it must be restarted
6109 if (effect->state() == EffectModule::ACTIVE ||
6110 effect->state() == EffectModule::STOPPING) {
6111 effect->start();
6112 }
Eric Laurent39e94f82010-07-28 01:32:47 -07006113 // if the move request is not received from audio policy manager, the effect must be
6114 // re-registered with the new strategy and output
6115 if (dstChain == 0) {
6116 dstChain = effect->chain().promote();
6117 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006118 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07006119 srcThread->addEffect_l(effect);
6120 return NO_INIT;
6121 }
6122 strategy = dstChain->strategy();
6123 }
6124 if (reRegister) {
6125 AudioSystem::unregisterEffect(effect->id());
6126 AudioSystem::registerEffect(&effect->desc(),
6127 dstOutput,
6128 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07006129 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07006130 effect->id());
6131 }
Eric Laurentde070132010-07-13 04:45:46 -07006132 effect = chain->getEffectFromId_l(0);
6133 }
6134
6135 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006136}
6137
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006138
Mathias Agopian65ab4712010-07-14 17:59:35 -07006139// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006140sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07006141 const sp<AudioFlinger::Client>& client,
6142 const sp<IEffectClient>& effectClient,
6143 int32_t priority,
6144 int sessionId,
6145 effect_descriptor_t *desc,
6146 int *enabled,
6147 status_t *status
6148 )
6149{
6150 sp<EffectModule> effect;
6151 sp<EffectHandle> handle;
6152 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006153 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07006154 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006155 bool effectCreated = false;
6156 bool effectRegistered = false;
6157
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006158 lStatus = initCheck();
6159 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006160 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006161 goto Exit;
6162 }
6163
6164 // Do not allow effects with session ID 0 on direct output or duplicating threads
6165 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07006166 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006167 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07006168 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006169 lStatus = BAD_VALUE;
6170 goto Exit;
6171 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006172 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08006173 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006174 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006175 desc->name, desc->flags, mType);
6176 lStatus = BAD_VALUE;
6177 goto Exit;
6178 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006179
Steve Block3856b092011-10-20 11:56:00 +01006180 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006181
6182 { // scope for mLock
6183 Mutex::Autolock _l(mLock);
6184
6185 // check for existing effect chain with the requested audio session
6186 chain = getEffectChain_l(sessionId);
6187 if (chain == 0) {
6188 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006189 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006190 chain = new EffectChain(this, sessionId);
6191 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07006192 chain->setStrategy(getStrategyForSession_l(sessionId));
6193 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006194 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07006195 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006196 }
6197
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08006198 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006199
6200 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006201 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006202 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07006203 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006204 if (lStatus != NO_ERROR) {
6205 goto Exit;
6206 }
6207 effectRegistered = true;
6208 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07006209 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006210 lStatus = effect->status();
6211 if (lStatus != NO_ERROR) {
6212 goto Exit;
6213 }
Eric Laurentcab11242010-07-15 12:50:15 -07006214 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006215 if (lStatus != NO_ERROR) {
6216 goto Exit;
6217 }
6218 effectCreated = true;
6219
6220 effect->setDevice(mDevice);
6221 effect->setMode(mAudioFlinger->getMode());
6222 }
6223 // create effect handle and connect it to effect module
6224 handle = new EffectHandle(effect, client, effectClient, priority);
6225 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08006226 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006227 *enabled = (int)effect->isEnabled();
6228 }
6229 }
6230
6231Exit:
6232 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07006233 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006234 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07006235 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006236 }
6237 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07006238 AudioSystem::unregisterEffect(effect->id());
6239 }
6240 if (chainCreated) {
6241 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006242 }
6243 handle.clear();
6244 }
6245
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006246 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006247 *status = lStatus;
6248 }
6249 return handle;
6250}
6251
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006252sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6253{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006254 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08006255 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006256}
6257
Eric Laurentde070132010-07-13 04:45:46 -07006258// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6259// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006260status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07006261{
6262 // check for existing effect chain with the requested audio session
6263 int sessionId = effect->sessionId();
6264 sp<EffectChain> chain = getEffectChain_l(sessionId);
6265 bool chainCreated = false;
6266
6267 if (chain == 0) {
6268 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006269 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006270 chain = new EffectChain(this, sessionId);
6271 addEffectChain_l(chain);
6272 chain->setStrategy(getStrategyForSession_l(sessionId));
6273 chainCreated = true;
6274 }
Steve Block3856b092011-10-20 11:56:00 +01006275 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006276
6277 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006278 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07006279 this, effect->desc().name, chain.get());
6280 return BAD_VALUE;
6281 }
6282
6283 status_t status = chain->addEffect_l(effect);
6284 if (status != NO_ERROR) {
6285 if (chainCreated) {
6286 removeEffectChain_l(chain);
6287 }
6288 return status;
6289 }
6290
6291 effect->setDevice(mDevice);
6292 effect->setMode(mAudioFlinger->getMode());
6293 return NO_ERROR;
6294}
6295
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006296void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07006297
Steve Block3856b092011-10-20 11:56:00 +01006298 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006299 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07006300 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6301 detachAuxEffect_l(effect->id());
6302 }
6303
6304 sp<EffectChain> chain = effect->chain().promote();
6305 if (chain != 0) {
6306 // remove effect chain if removing last effect
6307 if (chain->removeEffect_l(effect) == 0) {
6308 removeEffectChain_l(chain);
6309 }
6310 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00006311 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006312 }
6313}
6314
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006315void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006316 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006317{
6318 effectChains = mEffectChains;
6319 for (size_t i = 0; i < mEffectChains.size(); i++) {
6320 mEffectChains[i]->lock();
6321 }
6322}
6323
6324void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006325 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006326{
6327 for (size_t i = 0; i < effectChains.size(); i++) {
6328 effectChains[i]->unlock();
6329 }
6330}
6331
6332sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6333{
6334 Mutex::Autolock _l(mLock);
6335 return getEffectChain_l(sessionId);
6336}
6337
6338sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6339{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006340 size_t size = mEffectChains.size();
6341 for (size_t i = 0; i < size; i++) {
6342 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08006343 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006344 }
6345 }
Glenn Kasten090f0192012-01-30 13:00:02 -08006346 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006347}
6348
Glenn Kastenf78aee72012-01-04 11:00:47 -08006349void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006350{
6351 Mutex::Autolock _l(mLock);
6352 size_t size = mEffectChains.size();
6353 for (size_t i = 0; i < size; i++) {
6354 mEffectChains[i]->setMode_l(mode);
6355 }
6356}
6357
6358void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006359 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08006360 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07006361
Mathias Agopian65ab4712010-07-14 17:59:35 -07006362 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006363 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006364 // delete the effect module if removing last handle on it
6365 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006366 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006367 removeEffect_l(effect);
6368 AudioSystem::unregisterEffect(effect->id());
6369 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006370 }
6371}
6372
6373status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6374{
6375 int session = chain->sessionId();
6376 int16_t *buffer = mMixBuffer;
6377 bool ownsBuffer = false;
6378
Steve Block3856b092011-10-20 11:56:00 +01006379 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006380 if (session > 0) {
6381 // Only one effect chain can be present in direct output thread and it uses
6382 // the mix buffer as input
6383 if (mType != DIRECT) {
6384 size_t numSamples = mFrameCount * mChannelCount;
6385 buffer = new int16_t[numSamples];
6386 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01006387 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006388 ownsBuffer = true;
6389 }
6390
6391 // Attach all tracks with same session ID to this chain.
6392 for (size_t i = 0; i < mTracks.size(); ++i) {
6393 sp<Track> track = mTracks[i];
6394 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006395 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006396 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006397 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006398 }
6399 }
6400
6401 // indicate all active tracks in the chain
6402 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6403 sp<Track> track = mActiveTracks[i].promote();
6404 if (track == 0) continue;
6405 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006406 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07006407 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006408 }
6409 }
6410 }
6411
6412 chain->setInBuffer(buffer, ownsBuffer);
6413 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006414 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006415 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006416 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6417 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006418 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006419 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6420 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006421 // Effect chain for other sessions are inserted at beginning of effect
6422 // chains list to be processed before output mix effects. Relative order between other
6423 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006424 size_t size = mEffectChains.size();
6425 size_t i = 0;
6426 for (i = 0; i < size; i++) {
6427 if (mEffectChains[i]->sessionId() < session) break;
6428 }
6429 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006430 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006431
6432 return NO_ERROR;
6433}
6434
6435size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6436{
6437 int session = chain->sessionId();
6438
Steve Block3856b092011-10-20 11:56:00 +01006439 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006440
6441 for (size_t i = 0; i < mEffectChains.size(); i++) {
6442 if (chain == mEffectChains[i]) {
6443 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006444 // detach all active tracks from the chain
6445 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6446 sp<Track> track = mActiveTracks[i].promote();
6447 if (track == 0) continue;
6448 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006449 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006450 chain.get(), session);
6451 chain->decActiveTrackCnt();
6452 }
6453 }
6454
Mathias Agopian65ab4712010-07-14 17:59:35 -07006455 // detach all tracks with same session ID from this chain
6456 for (size_t i = 0; i < mTracks.size(); ++i) {
6457 sp<Track> track = mTracks[i];
6458 if (session == track->sessionId()) {
6459 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006460 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006461 }
6462 }
Eric Laurentde070132010-07-13 04:45:46 -07006463 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006464 }
6465 }
6466 return mEffectChains.size();
6467}
6468
Eric Laurentde070132010-07-13 04:45:46 -07006469status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6470 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006471{
6472 Mutex::Autolock _l(mLock);
6473 return attachAuxEffect_l(track, EffectId);
6474}
6475
Eric Laurentde070132010-07-13 04:45:46 -07006476status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6477 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006478{
6479 status_t status = NO_ERROR;
6480
6481 if (EffectId == 0) {
6482 track->setAuxBuffer(0, NULL);
6483 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006484 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6485 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006486 if (effect != 0) {
6487 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6488 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6489 } else {
6490 status = INVALID_OPERATION;
6491 }
6492 } else {
6493 status = BAD_VALUE;
6494 }
6495 }
6496 return status;
6497}
6498
6499void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6500{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006501 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006502 sp<Track> track = mTracks[i];
6503 if (track->auxEffectId() == effectId) {
6504 attachAuxEffect_l(track, 0);
6505 }
6506 }
6507}
6508
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006509status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6510{
6511 // only one chain per input thread
6512 if (mEffectChains.size() != 0) {
6513 return INVALID_OPERATION;
6514 }
Steve Block3856b092011-10-20 11:56:00 +01006515 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006516
6517 chain->setInBuffer(NULL);
6518 chain->setOutBuffer(NULL);
6519
Eric Laurent59255e42011-07-27 19:49:51 -07006520 checkSuspendOnAddEffectChain_l(chain);
6521
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006522 mEffectChains.add(chain);
6523
6524 return NO_ERROR;
6525}
6526
6527size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6528{
Steve Block3856b092011-10-20 11:56:00 +01006529 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006530 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006531 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6532 chain.get(), mEffectChains.size(), this);
6533 if (mEffectChains.size() == 1) {
6534 mEffectChains.removeAt(0);
6535 }
6536 return 0;
6537}
6538
Mathias Agopian65ab4712010-07-14 17:59:35 -07006539// ----------------------------------------------------------------------------
6540// EffectModule implementation
6541// ----------------------------------------------------------------------------
6542
6543#undef LOG_TAG
6544#define LOG_TAG "AudioFlinger::EffectModule"
6545
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006546AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006547 const wp<AudioFlinger::EffectChain>& chain,
6548 effect_descriptor_t *desc,
6549 int id,
6550 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006551 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006552 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006553{
Steve Block3856b092011-10-20 11:56:00 +01006554 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006555 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006556 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006557 return;
6558 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006559
6560 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6561
6562 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006563 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006564
6565 if (mStatus != NO_ERROR) {
6566 return;
6567 }
6568 lStatus = init();
6569 if (lStatus < 0) {
6570 mStatus = lStatus;
6571 goto Error;
6572 }
6573
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006574 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6575 mPinned = true;
6576 }
Steve Block3856b092011-10-20 11:56:00 +01006577 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006578 return;
6579Error:
6580 EffectRelease(mEffectInterface);
6581 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006582 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006583}
6584
6585AudioFlinger::EffectModule::~EffectModule()
6586{
Steve Block3856b092011-10-20 11:56:00 +01006587 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006588 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006589 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6590 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6591 sp<ThreadBase> thread = mThread.promote();
6592 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006593 audio_stream_t *stream = thread->stream();
6594 if (stream != NULL) {
6595 stream->remove_audio_effect(stream, mEffectInterface);
6596 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006597 }
6598 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006599 // release effect engine
6600 EffectRelease(mEffectInterface);
6601 }
6602}
6603
Glenn Kasten435dbe62012-01-30 10:15:48 -08006604status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006605{
6606 status_t status;
6607
6608 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006609 int priority = handle->priority();
6610 size_t size = mHandles.size();
6611 sp<EffectHandle> h;
6612 size_t i;
6613 for (i = 0; i < size; i++) {
6614 h = mHandles[i].promote();
6615 if (h == 0) continue;
6616 if (h->priority() <= priority) break;
6617 }
6618 // if inserted in first place, move effect control from previous owner to this handle
6619 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006620 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006621 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006622 enabled = h->enabled();
6623 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006624 }
Eric Laurent59255e42011-07-27 19:49:51 -07006625 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006626 status = NO_ERROR;
6627 } else {
6628 status = ALREADY_EXISTS;
6629 }
Steve Block3856b092011-10-20 11:56:00 +01006630 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006631 mHandles.insertAt(handle, i);
6632 return status;
6633}
6634
6635size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6636{
6637 Mutex::Autolock _l(mLock);
6638 size_t size = mHandles.size();
6639 size_t i;
6640 for (i = 0; i < size; i++) {
6641 if (mHandles[i] == handle) break;
6642 }
6643 if (i == size) {
6644 return size;
6645 }
Steve Block3856b092011-10-20 11:56:00 +01006646 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006647
6648 bool enabled = false;
6649 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006650 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006651 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006652 enabled = hdl->enabled();
6653 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006654 mHandles.removeAt(i);
6655 size = mHandles.size();
6656 // if removed from first place, move effect control from this handle to next in line
6657 if (i == 0 && size != 0) {
6658 sp<EffectHandle> h = mHandles[0].promote();
6659 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006660 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006661 }
6662 }
6663
Eric Laurentec437d82011-07-26 20:54:46 -07006664 // Prevent calls to process() and other functions on effect interface from now on.
6665 // The effect engine will be released by the destructor when the last strong reference on
6666 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006667 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006668 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006669 }
6670
Mathias Agopian65ab4712010-07-14 17:59:35 -07006671 return size;
6672}
6673
Eric Laurent59255e42011-07-27 19:49:51 -07006674sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6675{
6676 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08006677 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07006678}
6679
Glenn Kasten58123c32012-02-03 10:32:24 -08006680void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006681{
Glenn Kasten90bebef2012-01-27 15:24:38 -08006682 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006683 // keep a strong reference on this EffectModule to avoid calling the
6684 // destructor before we exit
6685 sp<EffectModule> keep(this);
6686 {
6687 sp<ThreadBase> thread = mThread.promote();
6688 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006689 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006690 }
6691 }
6692}
6693
6694void AudioFlinger::EffectModule::updateState() {
6695 Mutex::Autolock _l(mLock);
6696
6697 switch (mState) {
6698 case RESTART:
6699 reset_l();
6700 // FALL THROUGH
6701
6702 case STARTING:
6703 // clear auxiliary effect input buffer for next accumulation
6704 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6705 memset(mConfig.inputCfg.buffer.raw,
6706 0,
6707 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6708 }
6709 start_l();
6710 mState = ACTIVE;
6711 break;
6712 case STOPPING:
6713 stop_l();
6714 mDisableWaitCnt = mMaxDisableWaitCnt;
6715 mState = STOPPED;
6716 break;
6717 case STOPPED:
6718 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6719 // turn off sequence.
6720 if (--mDisableWaitCnt == 0) {
6721 reset_l();
6722 mState = IDLE;
6723 }
6724 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006725 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006726 break;
6727 }
6728}
6729
6730void AudioFlinger::EffectModule::process()
6731{
6732 Mutex::Autolock _l(mLock);
6733
Eric Laurentec437d82011-07-26 20:54:46 -07006734 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006735 mConfig.inputCfg.buffer.raw == NULL ||
6736 mConfig.outputCfg.buffer.raw == NULL) {
6737 return;
6738 }
6739
Eric Laurent8f45bd72010-08-31 13:50:07 -07006740 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006741 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6742 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006743 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006744 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006745 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006746 }
6747
6748 // do the actual processing in the effect engine
6749 int ret = (*mEffectInterface)->process(mEffectInterface,
6750 &mConfig.inputCfg.buffer,
6751 &mConfig.outputCfg.buffer);
6752
6753 // force transition to IDLE state when engine is ready
6754 if (mState == STOPPED && ret == -ENODATA) {
6755 mDisableWaitCnt = 1;
6756 }
6757
6758 // clear auxiliary effect input buffer for next accumulation
6759 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006760 memset(mConfig.inputCfg.buffer.raw, 0,
6761 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006762 }
6763 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006764 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6765 // If an insert effect is idle and input buffer is different from output buffer,
6766 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006767 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006768 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006769 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6770 int16_t *in = mConfig.inputCfg.buffer.s16;
6771 int16_t *out = mConfig.outputCfg.buffer.s16;
6772 for (size_t i = 0; i < frameCnt; i++) {
6773 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006774 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006775 }
6776 }
6777}
6778
6779void AudioFlinger::EffectModule::reset_l()
6780{
6781 if (mEffectInterface == NULL) {
6782 return;
6783 }
6784 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6785}
6786
6787status_t AudioFlinger::EffectModule::configure()
6788{
6789 uint32_t channels;
6790 if (mEffectInterface == NULL) {
6791 return NO_INIT;
6792 }
6793
6794 sp<ThreadBase> thread = mThread.promote();
6795 if (thread == 0) {
6796 return DEAD_OBJECT;
6797 }
6798
6799 // TODO: handle configuration of effects replacing track process
6800 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006801 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006802 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006803 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006804 }
6805
6806 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006807 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006808 } else {
6809 mConfig.inputCfg.channels = channels;
6810 }
6811 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006812 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6813 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006814 mConfig.inputCfg.samplingRate = thread->sampleRate();
6815 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6816 mConfig.inputCfg.bufferProvider.cookie = NULL;
6817 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6818 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6819 mConfig.outputCfg.bufferProvider.cookie = NULL;
6820 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6821 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6822 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6823 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006824 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006825 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006826 // - in other sessions:
6827 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6828 // other effect: overwrites output buffer: input buffer == output buffer
6829 // Auxiliary effect:
6830 // accumulates in output buffer: input buffer != output buffer
6831 // Therefore: accumulate <=> input buffer != output buffer
6832 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6833 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6834 } else {
6835 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6836 }
6837 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6838 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6839 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6840 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6841
Steve Block3856b092011-10-20 11:56:00 +01006842 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006843 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6844
Mathias Agopian65ab4712010-07-14 17:59:35 -07006845 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006846 uint32_t size = sizeof(int);
6847 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006848 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006849 sizeof(effect_config_t),
6850 &mConfig,
6851 &size,
6852 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006853 if (status == 0) {
6854 status = cmdStatus;
6855 }
6856
6857 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6858 (1000 * mConfig.outputCfg.buffer.frameCount);
6859
6860 return status;
6861}
6862
6863status_t AudioFlinger::EffectModule::init()
6864{
6865 Mutex::Autolock _l(mLock);
6866 if (mEffectInterface == NULL) {
6867 return NO_INIT;
6868 }
6869 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006870 uint32_t size = sizeof(status_t);
6871 status_t status = (*mEffectInterface)->command(mEffectInterface,
6872 EFFECT_CMD_INIT,
6873 0,
6874 NULL,
6875 &size,
6876 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006877 if (status == 0) {
6878 status = cmdStatus;
6879 }
6880 return status;
6881}
6882
Eric Laurentec35a142011-10-05 17:42:25 -07006883status_t AudioFlinger::EffectModule::start()
6884{
6885 Mutex::Autolock _l(mLock);
6886 return start_l();
6887}
6888
Mathias Agopian65ab4712010-07-14 17:59:35 -07006889status_t AudioFlinger::EffectModule::start_l()
6890{
6891 if (mEffectInterface == NULL) {
6892 return NO_INIT;
6893 }
6894 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006895 uint32_t size = sizeof(status_t);
6896 status_t status = (*mEffectInterface)->command(mEffectInterface,
6897 EFFECT_CMD_ENABLE,
6898 0,
6899 NULL,
6900 &size,
6901 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006902 if (status == 0) {
6903 status = cmdStatus;
6904 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006905 if (status == 0 &&
6906 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6907 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6908 sp<ThreadBase> thread = mThread.promote();
6909 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006910 audio_stream_t *stream = thread->stream();
6911 if (stream != NULL) {
6912 stream->add_audio_effect(stream, mEffectInterface);
6913 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006914 }
6915 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006916 return status;
6917}
6918
Eric Laurentec437d82011-07-26 20:54:46 -07006919status_t AudioFlinger::EffectModule::stop()
6920{
6921 Mutex::Autolock _l(mLock);
6922 return stop_l();
6923}
6924
Mathias Agopian65ab4712010-07-14 17:59:35 -07006925status_t AudioFlinger::EffectModule::stop_l()
6926{
6927 if (mEffectInterface == NULL) {
6928 return NO_INIT;
6929 }
6930 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006931 uint32_t size = sizeof(status_t);
6932 status_t status = (*mEffectInterface)->command(mEffectInterface,
6933 EFFECT_CMD_DISABLE,
6934 0,
6935 NULL,
6936 &size,
6937 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006938 if (status == 0) {
6939 status = cmdStatus;
6940 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006941 if (status == 0 &&
6942 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6943 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6944 sp<ThreadBase> thread = mThread.promote();
6945 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006946 audio_stream_t *stream = thread->stream();
6947 if (stream != NULL) {
6948 stream->remove_audio_effect(stream, mEffectInterface);
6949 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006950 }
6951 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006952 return status;
6953}
6954
Eric Laurent25f43952010-07-28 05:40:18 -07006955status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6956 uint32_t cmdSize,
6957 void *pCmdData,
6958 uint32_t *replySize,
6959 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006960{
6961 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006962// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006963
Eric Laurentec437d82011-07-26 20:54:46 -07006964 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006965 return NO_INIT;
6966 }
Eric Laurent25f43952010-07-28 05:40:18 -07006967 status_t status = (*mEffectInterface)->command(mEffectInterface,
6968 cmdCode,
6969 cmdSize,
6970 pCmdData,
6971 replySize,
6972 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006973 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006974 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006975 for (size_t i = 1; i < mHandles.size(); i++) {
6976 sp<EffectHandle> h = mHandles[i].promote();
6977 if (h != 0) {
6978 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6979 }
6980 }
6981 }
6982 return status;
6983}
6984
6985status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6986{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006987
Mathias Agopian65ab4712010-07-14 17:59:35 -07006988 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006989 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006990
6991 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006992 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6993 if (enabled && status != NO_ERROR) {
6994 return status;
6995 }
6996
Mathias Agopian65ab4712010-07-14 17:59:35 -07006997 switch (mState) {
6998 // going from disabled to enabled
6999 case IDLE:
7000 mState = STARTING;
7001 break;
7002 case STOPPED:
7003 mState = RESTART;
7004 break;
7005 case STOPPING:
7006 mState = ACTIVE;
7007 break;
7008
7009 // going from enabled to disabled
7010 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007011 mState = STOPPED;
7012 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007013 case STARTING:
7014 mState = IDLE;
7015 break;
7016 case ACTIVE:
7017 mState = STOPPING;
7018 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007019 case DESTROYED:
7020 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007021 }
7022 for (size_t i = 1; i < mHandles.size(); i++) {
7023 sp<EffectHandle> h = mHandles[i].promote();
7024 if (h != 0) {
7025 h->setEnabled(enabled);
7026 }
7027 }
7028 }
7029 return NO_ERROR;
7030}
7031
Glenn Kastenc59c0042012-02-02 14:06:11 -08007032bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007033{
7034 switch (mState) {
7035 case RESTART:
7036 case STARTING:
7037 case ACTIVE:
7038 return true;
7039 case IDLE:
7040 case STOPPING:
7041 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07007042 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07007043 default:
7044 return false;
7045 }
7046}
7047
Glenn Kastenc59c0042012-02-02 14:06:11 -08007048bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07007049{
7050 switch (mState) {
7051 case RESTART:
7052 case ACTIVE:
7053 case STOPPING:
7054 case STOPPED:
7055 return true;
7056 case IDLE:
7057 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07007058 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007059 default:
7060 return false;
7061 }
7062}
7063
Mathias Agopian65ab4712010-07-14 17:59:35 -07007064status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7065{
7066 Mutex::Autolock _l(mLock);
7067 status_t status = NO_ERROR;
7068
7069 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7070 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07007071 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07007072 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7073 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007074 status_t cmdStatus;
7075 uint32_t volume[2];
7076 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07007077 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007078 volume[0] = *left;
7079 volume[1] = *right;
7080 if (controller) {
7081 pVolume = volume;
7082 }
Eric Laurent25f43952010-07-28 05:40:18 -07007083 status = (*mEffectInterface)->command(mEffectInterface,
7084 EFFECT_CMD_SET_VOLUME,
7085 size,
7086 volume,
7087 &size,
7088 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007089 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7090 *left = volume[0];
7091 *right = volume[1];
7092 }
7093 }
7094 return status;
7095}
7096
7097status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7098{
7099 Mutex::Autolock _l(mLock);
7100 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007101 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7102 // audio pre processing modules on RecordThread can receive both output and
7103 // input device indication in the same call
7104 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7105 if (dev) {
7106 status_t cmdStatus;
7107 uint32_t size = sizeof(status_t);
7108
7109 status = (*mEffectInterface)->command(mEffectInterface,
7110 EFFECT_CMD_SET_DEVICE,
7111 sizeof(uint32_t),
7112 &dev,
7113 &size,
7114 &cmdStatus);
7115 if (status == NO_ERROR) {
7116 status = cmdStatus;
7117 }
7118 }
7119 dev = device & AUDIO_DEVICE_IN_ALL;
7120 if (dev) {
7121 status_t cmdStatus;
7122 uint32_t size = sizeof(status_t);
7123
7124 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7125 EFFECT_CMD_SET_INPUT_DEVICE,
7126 sizeof(uint32_t),
7127 &dev,
7128 &size,
7129 &cmdStatus);
7130 if (status2 == NO_ERROR) {
7131 status2 = cmdStatus;
7132 }
7133 if (status == NO_ERROR) {
7134 status = status2;
7135 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007136 }
7137 }
7138 return status;
7139}
7140
Glenn Kastenf78aee72012-01-04 11:00:47 -08007141status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007142{
7143 Mutex::Autolock _l(mLock);
7144 status_t status = NO_ERROR;
7145 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007146 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007147 uint32_t size = sizeof(status_t);
7148 status = (*mEffectInterface)->command(mEffectInterface,
7149 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08007150 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07007151 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07007152 &size,
7153 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007154 if (status == NO_ERROR) {
7155 status = cmdStatus;
7156 }
7157 }
7158 return status;
7159}
7160
Eric Laurent59255e42011-07-27 19:49:51 -07007161void AudioFlinger::EffectModule::setSuspended(bool suspended)
7162{
7163 Mutex::Autolock _l(mLock);
7164 mSuspended = suspended;
7165}
Glenn Kastena3a85482012-01-04 11:01:11 -08007166
7167bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07007168{
7169 Mutex::Autolock _l(mLock);
7170 return mSuspended;
7171}
7172
Mathias Agopian65ab4712010-07-14 17:59:35 -07007173status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7174{
7175 const size_t SIZE = 256;
7176 char buffer[SIZE];
7177 String8 result;
7178
7179 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7180 result.append(buffer);
7181
7182 bool locked = tryLock(mLock);
7183 // failed to lock - AudioFlinger is probably deadlocked
7184 if (!locked) {
7185 result.append("\t\tCould not lock Fx mutex:\n");
7186 }
7187
7188 result.append("\t\tSession Status State Engine:\n");
7189 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7190 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7191 result.append(buffer);
7192
7193 result.append("\t\tDescriptor:\n");
7194 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7195 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7196 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7197 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7198 result.append(buffer);
7199 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7200 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7201 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7202 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7203 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07007204 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007205 mDescriptor.apiVersion,
7206 mDescriptor.flags);
7207 result.append(buffer);
7208 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7209 mDescriptor.name);
7210 result.append(buffer);
7211 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7212 mDescriptor.implementor);
7213 result.append(buffer);
7214
7215 result.append("\t\t- Input configuration:\n");
7216 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7217 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7218 (uint32_t)mConfig.inputCfg.buffer.raw,
7219 mConfig.inputCfg.buffer.frameCount,
7220 mConfig.inputCfg.samplingRate,
7221 mConfig.inputCfg.channels,
7222 mConfig.inputCfg.format);
7223 result.append(buffer);
7224
7225 result.append("\t\t- Output configuration:\n");
7226 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7227 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7228 (uint32_t)mConfig.outputCfg.buffer.raw,
7229 mConfig.outputCfg.buffer.frameCount,
7230 mConfig.outputCfg.samplingRate,
7231 mConfig.outputCfg.channels,
7232 mConfig.outputCfg.format);
7233 result.append(buffer);
7234
7235 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7236 result.append(buffer);
7237 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7238 for (size_t i = 0; i < mHandles.size(); ++i) {
7239 sp<EffectHandle> handle = mHandles[i].promote();
7240 if (handle != 0) {
7241 handle->dump(buffer, SIZE);
7242 result.append(buffer);
7243 }
7244 }
7245
7246 result.append("\n");
7247
7248 write(fd, result.string(), result.length());
7249
7250 if (locked) {
7251 mLock.unlock();
7252 }
7253
7254 return NO_ERROR;
7255}
7256
7257// ----------------------------------------------------------------------------
7258// EffectHandle implementation
7259// ----------------------------------------------------------------------------
7260
7261#undef LOG_TAG
7262#define LOG_TAG "AudioFlinger::EffectHandle"
7263
7264AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7265 const sp<AudioFlinger::Client>& client,
7266 const sp<IEffectClient>& effectClient,
7267 int32_t priority)
7268 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007269 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007270 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007271{
Steve Block3856b092011-10-20 11:56:00 +01007272 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007273
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007274 if (client == 0) {
7275 return;
7276 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007277 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7278 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7279 if (mCblkMemory != 0) {
7280 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7281
Glenn Kastena0d68332012-01-27 16:47:15 -08007282 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007283 new(mCblk) effect_param_cblk_t();
7284 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007285 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007286 } else {
Steve Block29357bc2012-01-06 19:20:56 +00007287 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007288 return;
7289 }
7290}
7291
7292AudioFlinger::EffectHandle::~EffectHandle()
7293{
Steve Block3856b092011-10-20 11:56:00 +01007294 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007295 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01007296 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007297}
7298
7299status_t AudioFlinger::EffectHandle::enable()
7300{
Steve Block3856b092011-10-20 11:56:00 +01007301 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007302 if (!mHasControl) return INVALID_OPERATION;
7303 if (mEffect == 0) return DEAD_OBJECT;
7304
Eric Laurentdb7c0792011-08-10 10:37:50 -07007305 if (mEnabled) {
7306 return NO_ERROR;
7307 }
7308
Eric Laurent59255e42011-07-27 19:49:51 -07007309 mEnabled = true;
7310
7311 sp<ThreadBase> thread = mEffect->thread().promote();
7312 if (thread != 0) {
7313 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7314 }
7315
7316 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7317 if (mEffect->suspended()) {
7318 return NO_ERROR;
7319 }
7320
Eric Laurentdb7c0792011-08-10 10:37:50 -07007321 status_t status = mEffect->setEnabled(true);
7322 if (status != NO_ERROR) {
7323 if (thread != 0) {
7324 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7325 }
7326 mEnabled = false;
7327 }
7328 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007329}
7330
7331status_t AudioFlinger::EffectHandle::disable()
7332{
Steve Block3856b092011-10-20 11:56:00 +01007333 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007334 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07007335 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007336
Eric Laurentdb7c0792011-08-10 10:37:50 -07007337 if (!mEnabled) {
7338 return NO_ERROR;
7339 }
Eric Laurent59255e42011-07-27 19:49:51 -07007340 mEnabled = false;
7341
7342 if (mEffect->suspended()) {
7343 return NO_ERROR;
7344 }
7345
7346 status_t status = mEffect->setEnabled(false);
7347
7348 sp<ThreadBase> thread = mEffect->thread().promote();
7349 if (thread != 0) {
7350 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7351 }
7352
7353 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007354}
7355
7356void AudioFlinger::EffectHandle::disconnect()
7357{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007358 disconnect(true);
7359}
7360
Glenn Kasten58123c32012-02-03 10:32:24 -08007361void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007362{
Glenn Kasten58123c32012-02-03 10:32:24 -08007363 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007364 if (mEffect == 0) {
7365 return;
7366 }
Glenn Kasten58123c32012-02-03 10:32:24 -08007367 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07007368
Eric Laurenta85a74a2011-10-19 11:44:54 -07007369 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007370 sp<ThreadBase> thread = mEffect->thread().promote();
7371 if (thread != 0) {
7372 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7373 }
Eric Laurent59255e42011-07-27 19:49:51 -07007374 }
7375
Mathias Agopian65ab4712010-07-14 17:59:35 -07007376 // release sp on module => module destructor can be called now
7377 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007378 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08007379 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08007380 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007381 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7382 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08007383 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007384 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07007385 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7386 mClient.clear();
7387 }
7388}
7389
Eric Laurent25f43952010-07-28 05:40:18 -07007390status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7391 uint32_t cmdSize,
7392 void *pCmdData,
7393 uint32_t *replySize,
7394 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007395{
Steve Block3856b092011-10-20 11:56:00 +01007396// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07007397// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007398
7399 // only get parameter command is permitted for applications not controlling the effect
7400 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7401 return INVALID_OPERATION;
7402 }
7403 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007404 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007405
7406 // handle commands that are not forwarded transparently to effect engine
7407 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7408 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7409 // no risk to block the whole media server process or mixer threads is we are stuck here
7410 Mutex::Autolock _l(mCblk->lock);
7411 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7412 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7413 mCblk->serverIndex = 0;
7414 mCblk->clientIndex = 0;
7415 return BAD_VALUE;
7416 }
7417 status_t status = NO_ERROR;
7418 while (mCblk->serverIndex < mCblk->clientIndex) {
7419 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007420 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007421 int *p = (int *)(mBuffer + mCblk->serverIndex);
7422 int size = *p++;
7423 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007424 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007425 break;
7426 }
7427 effect_param_t *param = (effect_param_t *)p;
7428 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007429 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007430 mCblk->serverIndex += size;
7431 continue;
7432 }
Eric Laurent25f43952010-07-28 05:40:18 -07007433 uint32_t psize = sizeof(effect_param_t) +
7434 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7435 param->vsize;
7436 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7437 psize,
7438 p,
7439 &rsize,
7440 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007441 // stop at first error encountered
7442 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007443 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007444 *(int *)pReplyData = reply;
7445 break;
7446 } else if (reply != NO_ERROR) {
7447 *(int *)pReplyData = reply;
7448 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007449 }
7450 mCblk->serverIndex += size;
7451 }
7452 mCblk->serverIndex = 0;
7453 mCblk->clientIndex = 0;
7454 return status;
7455 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007456 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007457 return enable();
7458 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007459 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007460 return disable();
7461 }
7462
7463 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7464}
7465
Eric Laurent59255e42011-07-27 19:49:51 -07007466void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007467{
Steve Block3856b092011-10-20 11:56:00 +01007468 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007469
7470 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007471 mEnabled = enabled;
7472
Mathias Agopian65ab4712010-07-14 17:59:35 -07007473 if (signal && mEffectClient != 0) {
7474 mEffectClient->controlStatusChanged(hasControl);
7475 }
7476}
7477
Eric Laurent25f43952010-07-28 05:40:18 -07007478void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7479 uint32_t cmdSize,
7480 void *pCmdData,
7481 uint32_t replySize,
7482 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007483{
7484 if (mEffectClient != 0) {
7485 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7486 }
7487}
7488
7489
7490
7491void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7492{
7493 if (mEffectClient != 0) {
7494 mEffectClient->enableStatusChanged(enabled);
7495 }
7496}
7497
7498status_t AudioFlinger::EffectHandle::onTransact(
7499 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7500{
7501 return BnEffect::onTransact(code, data, reply, flags);
7502}
7503
7504
7505void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7506{
Glenn Kastena0d68332012-01-27 16:47:15 -08007507 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007508
7509 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08007510 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007511 mPriority,
7512 mHasControl,
7513 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007514 mCblk ? mCblk->clientIndex : 0,
7515 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007516 );
7517
7518 if (locked) {
7519 mCblk->lock.unlock();
7520 }
7521}
7522
7523#undef LOG_TAG
7524#define LOG_TAG "AudioFlinger::EffectChain"
7525
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007526AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007527 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007528 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007529 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7530 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007531{
Dima Zavinfce7a472011-04-19 22:30:36 -07007532 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007533 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007534 return;
7535 }
7536 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7537 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007538}
7539
7540AudioFlinger::EffectChain::~EffectChain()
7541{
7542 if (mOwnInBuffer) {
7543 delete mInBuffer;
7544 }
7545
7546}
7547
Eric Laurent59255e42011-07-27 19:49:51 -07007548// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007549sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007550{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007551 size_t size = mEffects.size();
7552
7553 for (size_t i = 0; i < size; i++) {
7554 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007555 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007556 }
7557 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007558 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007559}
7560
Eric Laurent59255e42011-07-27 19:49:51 -07007561// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007562sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007563{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007564 size_t size = mEffects.size();
7565
7566 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007567 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7568 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007569 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007570 }
7571 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007572 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007573}
7574
Eric Laurent59255e42011-07-27 19:49:51 -07007575// getEffectFromType_l() must be called with ThreadBase::mLock held
7576sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7577 const effect_uuid_t *type)
7578{
Eric Laurent59255e42011-07-27 19:49:51 -07007579 size_t size = mEffects.size();
7580
7581 for (size_t i = 0; i < size; i++) {
7582 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007583 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007584 }
7585 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007586 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007587}
7588
Mathias Agopian65ab4712010-07-14 17:59:35 -07007589// Must be called with EffectChain::mLock locked
7590void AudioFlinger::EffectChain::process_l()
7591{
Eric Laurentdac69112010-09-28 14:09:57 -07007592 sp<ThreadBase> thread = mThread.promote();
7593 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007594 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007595 return;
7596 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007597 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7598 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007599 // always process effects unless no more tracks are on the session and the effect tail
7600 // has been rendered
7601 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007602 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007603 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007604
Eric Laurent544fe9b2011-11-11 15:42:52 -08007605 if (!tracksOnSession && mTailBufferCount == 0) {
7606 doProcess = false;
7607 }
7608
7609 if (activeTrackCnt() == 0) {
7610 // if no track is active and the effect tail has not been rendered,
7611 // the input buffer must be cleared here as the mixer process will not do it
7612 if (tracksOnSession || mTailBufferCount > 0) {
7613 size_t numSamples = thread->frameCount() * thread->channelCount();
7614 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7615 if (mTailBufferCount > 0) {
7616 mTailBufferCount--;
7617 }
7618 }
7619 }
Eric Laurentdac69112010-09-28 14:09:57 -07007620 }
7621
Mathias Agopian65ab4712010-07-14 17:59:35 -07007622 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007623 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007624 for (size_t i = 0; i < size; i++) {
7625 mEffects[i]->process();
7626 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007627 }
7628 for (size_t i = 0; i < size; i++) {
7629 mEffects[i]->updateState();
7630 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007631}
7632
Eric Laurentcab11242010-07-15 12:50:15 -07007633// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007634status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007635{
7636 effect_descriptor_t desc = effect->desc();
7637 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7638
7639 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007640 effect->setChain(this);
7641 sp<ThreadBase> thread = mThread.promote();
7642 if (thread == 0) {
7643 return NO_INIT;
7644 }
7645 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007646
7647 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7648 // Auxiliary effects are inserted at the beginning of mEffects vector as
7649 // they are processed first and accumulated in chain input buffer
7650 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007651
Mathias Agopian65ab4712010-07-14 17:59:35 -07007652 // the input buffer for auxiliary effect contains mono samples in
7653 // 32 bit format. This is to avoid saturation in AudoMixer
7654 // accumulation stage. Saturation is done in EffectModule::process() before
7655 // calling the process in effect engine
7656 size_t numSamples = thread->frameCount();
7657 int32_t *buffer = new int32_t[numSamples];
7658 memset(buffer, 0, numSamples * sizeof(int32_t));
7659 effect->setInBuffer((int16_t *)buffer);
7660 // auxiliary effects output samples to chain input buffer for further processing
7661 // by insert effects
7662 effect->setOutBuffer(mInBuffer);
7663 } else {
7664 // Insert effects are inserted at the end of mEffects vector as they are processed
7665 // after track and auxiliary effects.
7666 // Insert effect order as a function of indicated preference:
7667 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7668 // another effect is present
7669 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7670 // last effect claiming first position
7671 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7672 // first effect claiming last position
7673 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7674 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7675 // already present
7676
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007677 size_t size = mEffects.size();
7678 size_t idx_insert = size;
7679 ssize_t idx_insert_first = -1;
7680 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007681
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007682 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007683 effect_descriptor_t d = mEffects[i]->desc();
7684 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7685 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7686 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7687 // check invalid effect chaining combinations
7688 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7689 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007690 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007691 return INVALID_OPERATION;
7692 }
7693 // remember position of first insert effect and by default
7694 // select this as insert position for new effect
7695 if (idx_insert == size) {
7696 idx_insert = i;
7697 }
7698 // remember position of last insert effect claiming
7699 // first position
7700 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7701 idx_insert_first = i;
7702 }
7703 // remember position of first insert effect claiming
7704 // last position
7705 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7706 idx_insert_last == -1) {
7707 idx_insert_last = i;
7708 }
7709 }
7710 }
7711
7712 // modify idx_insert from first position if needed
7713 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7714 if (idx_insert_last != -1) {
7715 idx_insert = idx_insert_last;
7716 } else {
7717 idx_insert = size;
7718 }
7719 } else {
7720 if (idx_insert_first != -1) {
7721 idx_insert = idx_insert_first + 1;
7722 }
7723 }
7724
7725 // always read samples from chain input buffer
7726 effect->setInBuffer(mInBuffer);
7727
7728 // if last effect in the chain, output samples to chain
7729 // output buffer, otherwise to chain input buffer
7730 if (idx_insert == size) {
7731 if (idx_insert != 0) {
7732 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7733 mEffects[idx_insert-1]->configure();
7734 }
7735 effect->setOutBuffer(mOutBuffer);
7736 } else {
7737 effect->setOutBuffer(mInBuffer);
7738 }
7739 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007740
Steve Block3856b092011-10-20 11:56:00 +01007741 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007742 }
7743 effect->configure();
7744 return NO_ERROR;
7745}
7746
Eric Laurentcab11242010-07-15 12:50:15 -07007747// removeEffect_l() must be called with PlaybackThread::mLock held
7748size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007749{
7750 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007751 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007752 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7753
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007754 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007755 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007756 // calling stop here will remove pre-processing effect from the audio HAL.
7757 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7758 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007759 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7760 mEffects[i]->state() == EffectModule::STOPPING) {
7761 mEffects[i]->stop();
7762 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007763 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7764 delete[] effect->inBuffer();
7765 } else {
7766 if (i == size - 1 && i != 0) {
7767 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7768 mEffects[i - 1]->configure();
7769 }
7770 }
7771 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007772 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007773 break;
7774 }
7775 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007776
7777 return mEffects.size();
7778}
7779
Eric Laurentcab11242010-07-15 12:50:15 -07007780// setDevice_l() must be called with PlaybackThread::mLock held
7781void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007782{
7783 size_t size = mEffects.size();
7784 for (size_t i = 0; i < size; i++) {
7785 mEffects[i]->setDevice(device);
7786 }
7787}
7788
Eric Laurentcab11242010-07-15 12:50:15 -07007789// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007790void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007791{
7792 size_t size = mEffects.size();
7793 for (size_t i = 0; i < size; i++) {
7794 mEffects[i]->setMode(mode);
7795 }
7796}
7797
Eric Laurentcab11242010-07-15 12:50:15 -07007798// setVolume_l() must be called with PlaybackThread::mLock held
7799bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007800{
7801 uint32_t newLeft = *left;
7802 uint32_t newRight = *right;
7803 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007804 int ctrlIdx = -1;
7805 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007806
Eric Laurentcab11242010-07-15 12:50:15 -07007807 // first update volume controller
7808 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007809 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007810 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7811 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007812 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007813 break;
7814 }
7815 }
7816
7817 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007818 if (hasControl) {
7819 *left = mNewLeftVolume;
7820 *right = mNewRightVolume;
7821 }
7822 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007823 }
7824
7825 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007826 mLeftVolume = newLeft;
7827 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007828
7829 // second get volume update from volume controller
7830 if (ctrlIdx >= 0) {
7831 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007832 mNewLeftVolume = newLeft;
7833 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007834 }
7835 // then indicate volume to all other effects in chain.
7836 // Pass altered volume to effects before volume controller
7837 // and requested volume to effects after controller
7838 uint32_t lVol = newLeft;
7839 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007840
Mathias Agopian65ab4712010-07-14 17:59:35 -07007841 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007842 if ((int)i == ctrlIdx) continue;
7843 // this also works for ctrlIdx == -1 when there is no volume controller
7844 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007845 lVol = *left;
7846 rVol = *right;
7847 }
7848 mEffects[i]->setVolume(&lVol, &rVol, false);
7849 }
7850 *left = newLeft;
7851 *right = newRight;
7852
7853 return hasControl;
7854}
7855
Mathias Agopian65ab4712010-07-14 17:59:35 -07007856status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7857{
7858 const size_t SIZE = 256;
7859 char buffer[SIZE];
7860 String8 result;
7861
7862 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7863 result.append(buffer);
7864
7865 bool locked = tryLock(mLock);
7866 // failed to lock - AudioFlinger is probably deadlocked
7867 if (!locked) {
7868 result.append("\tCould not lock mutex:\n");
7869 }
7870
Eric Laurentcab11242010-07-15 12:50:15 -07007871 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7872 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007873 mEffects.size(),
7874 (uint32_t)mInBuffer,
7875 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007876 mActiveTrackCnt);
7877 result.append(buffer);
7878 write(fd, result.string(), result.size());
7879
7880 for (size_t i = 0; i < mEffects.size(); ++i) {
7881 sp<EffectModule> effect = mEffects[i];
7882 if (effect != 0) {
7883 effect->dump(fd, args);
7884 }
7885 }
7886
7887 if (locked) {
7888 mLock.unlock();
7889 }
7890
7891 return NO_ERROR;
7892}
7893
Eric Laurent59255e42011-07-27 19:49:51 -07007894// must be called with ThreadBase::mLock held
7895void AudioFlinger::EffectChain::setEffectSuspended_l(
7896 const effect_uuid_t *type, bool suspend)
7897{
7898 sp<SuspendedEffectDesc> desc;
7899 // use effect type UUID timelow as key as there is no real risk of identical
7900 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007901 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007902 if (suspend) {
7903 if (index >= 0) {
7904 desc = mSuspendedEffects.valueAt(index);
7905 } else {
7906 desc = new SuspendedEffectDesc();
7907 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7908 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007909 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007910 }
7911 if (desc->mRefCount++ == 0) {
7912 sp<EffectModule> effect = getEffectIfEnabled(type);
7913 if (effect != 0) {
7914 desc->mEffect = effect;
7915 effect->setSuspended(true);
7916 effect->setEnabled(false);
7917 }
7918 }
7919 } else {
7920 if (index < 0) {
7921 return;
7922 }
7923 desc = mSuspendedEffects.valueAt(index);
7924 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007925 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007926 desc->mRefCount = 1;
7927 }
7928 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007929 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007930 if (desc->mEffect != 0) {
7931 sp<EffectModule> effect = desc->mEffect.promote();
7932 if (effect != 0) {
7933 effect->setSuspended(false);
7934 sp<EffectHandle> handle = effect->controlHandle();
7935 if (handle != 0) {
7936 effect->setEnabled(handle->enabled());
7937 }
7938 }
7939 desc->mEffect.clear();
7940 }
7941 mSuspendedEffects.removeItemsAt(index);
7942 }
7943 }
7944}
7945
7946// must be called with ThreadBase::mLock held
7947void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7948{
7949 sp<SuspendedEffectDesc> desc;
7950
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007951 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07007952 if (suspend) {
7953 if (index >= 0) {
7954 desc = mSuspendedEffects.valueAt(index);
7955 } else {
7956 desc = new SuspendedEffectDesc();
7957 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007958 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007959 }
7960 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08007961 Vector< sp<EffectModule> > effects;
7962 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07007963 for (size_t i = 0; i < effects.size(); i++) {
7964 setEffectSuspended_l(&effects[i]->desc().type, true);
7965 }
7966 }
7967 } else {
7968 if (index < 0) {
7969 return;
7970 }
7971 desc = mSuspendedEffects.valueAt(index);
7972 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007973 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007974 desc->mRefCount = 1;
7975 }
7976 if (--desc->mRefCount == 0) {
7977 Vector<const effect_uuid_t *> types;
7978 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7979 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7980 continue;
7981 }
7982 types.add(&mSuspendedEffects.valueAt(i)->mType);
7983 }
7984 for (size_t i = 0; i < types.size(); i++) {
7985 setEffectSuspended_l(types[i], false);
7986 }
Steve Block3856b092011-10-20 11:56:00 +01007987 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007988 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7989 }
7990 }
7991}
7992
Eric Laurent6bffdb82011-09-23 08:40:41 -07007993
7994// The volume effect is used for automated tests only
7995#ifndef OPENSL_ES_H_
7996static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7997 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7998const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7999#endif //OPENSL_ES_H_
8000
Eric Laurentdb7c0792011-08-10 10:37:50 -07008001bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
8002{
8003 // auxiliary effects and visualizer are never suspended on output mix
8004 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8005 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07008006 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8007 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008008 return false;
8009 }
8010 return true;
8011}
8012
Glenn Kastend0539712012-01-30 12:56:03 -08008013void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07008014{
Glenn Kastend0539712012-01-30 12:56:03 -08008015 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07008016 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08008017 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8018 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07008019 }
Eric Laurent59255e42011-07-27 19:49:51 -07008020 }
Eric Laurent59255e42011-07-27 19:49:51 -07008021}
8022
8023sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8024 const effect_uuid_t *type)
8025{
Glenn Kasten090f0192012-01-30 13:00:02 -08008026 sp<EffectModule> effect = getEffectFromType_l(type);
8027 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008028}
8029
8030void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8031 bool enabled)
8032{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008033 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008034 if (enabled) {
8035 if (index < 0) {
8036 // if the effect is not suspend check if all effects are suspended
8037 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8038 if (index < 0) {
8039 return;
8040 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07008041 if (!isEffectEligibleForSuspend(effect->desc())) {
8042 return;
8043 }
Eric Laurent59255e42011-07-27 19:49:51 -07008044 setEffectSuspended_l(&effect->desc().type, enabled);
8045 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07008046 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008047 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07008048 return;
8049 }
Eric Laurent59255e42011-07-27 19:49:51 -07008050 }
Steve Block3856b092011-10-20 11:56:00 +01008051 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008052 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008053 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8054 // if effect is requested to suspended but was not yet enabled, supend it now.
8055 if (desc->mEffect == 0) {
8056 desc->mEffect = effect;
8057 effect->setEnabled(false);
8058 effect->setSuspended(true);
8059 }
8060 } else {
8061 if (index < 0) {
8062 return;
8063 }
Steve Block3856b092011-10-20 11:56:00 +01008064 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008065 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008066 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8067 desc->mEffect.clear();
8068 effect->setSuspended(false);
8069 }
8070}
8071
Mathias Agopian65ab4712010-07-14 17:59:35 -07008072#undef LOG_TAG
8073#define LOG_TAG "AudioFlinger"
8074
8075// ----------------------------------------------------------------------------
8076
8077status_t AudioFlinger::onTransact(
8078 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8079{
8080 return BnAudioFlinger::onTransact(code, data, reply, flags);
8081}
8082
Mathias Agopian65ab4712010-07-14 17:59:35 -07008083}; // namespace android