blob: 86bb7f9ebe4840e3e979cc9b50ab059a0b641889 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070034#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035
Dima Zavinfce7a472011-04-19 22:30:36 -070036#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080038#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039
Glenn Kastend3cee2f2012-03-13 17:55:35 -070040#undef ADD_BATTERY_DATA
41
42#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080043#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080044#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070045#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070046
47#include <private/media/AudioTrackShared.h>
48#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070049
Dima Zavin64760242011-05-11 14:15:23 -070050#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070051#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
53#include "AudioMixer.h"
54#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080055#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Mathias Agopian65ab4712010-07-14 17:59:35 -070057#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070058#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070059#include <audio_effects/effect_ns.h>
60#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061
Glenn Kasten3b21c502011-12-15 09:52:39 -080062#include <audio_utils/primitives.h>
63
Eric Laurentfeb0db62011-07-22 09:04:31 -070064#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080065
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070066// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080067#ifdef DEBUG_CPU_USAGE
68#include <cpustats/CentralTendencyStatistics.h>
69#include <cpustats/ThreadCpuUsage.h>
70#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070071
John Grossman4ff14ba2012-02-08 16:37:41 -080072#include <common_time/cc_helper.h>
73#include <common_time/local_clock.h>
74
Mathias Agopian65ab4712010-07-14 17:59:35 -070075// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070076
Eric Laurentde070132010-07-13 04:45:46 -070077
Mathias Agopian65ab4712010-07-14 17:59:35 -070078namespace android {
79
Glenn Kastenec1d6b52011-12-12 09:04:45 -080080static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
81static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070082
Mathias Agopian65ab4712010-07-14 17:59:35 -070083static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -080084static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070085
86// retry counts for buffer fill timeout
87// 50 * ~20msecs = 1 second
88static const int8_t kMaxTrackRetries = 50;
89static const int8_t kMaxTrackStartupRetries = 50;
90// allow less retry attempts on direct output thread.
91// direct outputs can be a scarce resource in audio hardware and should
92// be released as quickly as possible.
93static const int8_t kMaxTrackRetriesDirect = 2;
94
95static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -080096static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070097
Glenn Kasten7dede872011-12-13 11:04:14 -080098// don't warn about blocked writes or record buffer overflows more often than this
99static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700100
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700101// RecordThread loop sleep time upon application overrun or audio HAL read error
102static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103
Glenn Kasten7dede872011-12-13 11:04:14 -0800104// maximum time to wait for setParameters to complete
105static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700106
Eric Laurent7cafbb32011-11-22 18:50:29 -0800107// minimum sleep time for the mixer thread loop when tracks are active but in underrun
108static const uint32_t kMinThreadSleepTimeUs = 5000;
109// maximum divider applied to the active sleep time in the mixer thread loop
110static const uint32_t kMaxThreadSleepTimeShift = 2;
111
John Grossman4ff14ba2012-02-08 16:37:41 -0800112nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800113
Mathias Agopian65ab4712010-07-14 17:59:35 -0700114// ----------------------------------------------------------------------------
115
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700116#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800117// To collect the amplifier usage
118static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800119 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
120 if (service == NULL) {
121 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800122 return;
123 }
124
125 service->addBatteryData(params);
126}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700127#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800128
Dima Zavin799a70e2011-04-18 16:57:27 -0700129static int load_audio_interface(const char *if_name, const hw_module_t **mod,
130 audio_hw_device_t **dev)
131{
132 int rc;
133
134 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
135 if (rc)
136 goto out;
137
138 rc = audio_hw_device_open(*mod, dev);
Steve Block29357bc2012-01-06 19:20:56 +0000139 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin799a70e2011-04-18 16:57:27 -0700140 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
141 if (rc)
142 goto out;
143
144 return 0;
145
146out:
147 *mod = NULL;
148 *dev = NULL;
149 return rc;
150}
151
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800152static const char * const audio_interfaces[] = {
Dima Zavin799a70e2011-04-18 16:57:27 -0700153 "primary",
154 "a2dp",
155 "usb",
156};
157#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
158
Mathias Agopian65ab4712010-07-14 17:59:35 -0700159// ----------------------------------------------------------------------------
160
161AudioFlinger::AudioFlinger()
162 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800163 mPrimaryHardwareDev(NULL),
164 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
165 mMasterVolume(1.0f),
166 mMasterVolumeSupportLvl(MVS_NONE),
167 mMasterMute(false),
168 mNextUniqueId(1),
169 mMode(AUDIO_MODE_INVALID),
170 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700171{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700172}
173
174void AudioFlinger::onFirstRef()
175{
Dima Zavin799a70e2011-04-18 16:57:27 -0700176 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700177
Eric Laurent93575202011-01-18 18:39:02 -0800178 Mutex::Autolock _l(mLock);
179
Dima Zavin799a70e2011-04-18 16:57:27 -0700180 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800181 char val_str[PROPERTY_VALUE_MAX] = { 0 };
182 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
183 uint32_t int_val;
184 if (1 == sscanf(val_str, "%u", &int_val)) {
185 mStandbyTimeInNsecs = milliseconds(int_val);
186 ALOGI("Using %u mSec as standby time.", int_val);
187 } else {
188 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
189 ALOGI("Using default %u mSec as standby time.",
190 (uint32_t)(mStandbyTimeInNsecs / 1000000));
191 }
192 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700193
Dima Zavin799a70e2011-04-18 16:57:27 -0700194 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
195 const hw_module_t *mod;
196 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700197
Dima Zavin799a70e2011-04-18 16:57:27 -0700198 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
199 if (rc)
200 continue;
201
Steve Blockdf64d152012-01-04 20:05:49 +0000202 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700203 mod->name, mod->id);
Dima Zavin799a70e2011-04-18 16:57:27 -0700204 mAudioHwDevs.push(dev);
205
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800206 if (mPrimaryHardwareDev == NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700207 mPrimaryHardwareDev = dev;
Steve Blockdf64d152012-01-04 20:05:49 +0000208 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700209 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700210 }
211 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700212
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800213 if (mPrimaryHardwareDev == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000214 ALOGE("Primary audio interface not found");
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800215 // proceed, all later accesses to mPrimaryHardwareDev verify it's safe with initCheck()
Dima Zavin799a70e2011-04-18 16:57:27 -0700216 }
217
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800218 // Currently (mPrimaryHardwareDev == NULL) == (mAudioHwDevs.size() == 0), but the way the
219 // primary HW dev is selected can change so these conditions might not always be equivalent.
220 // When that happens, re-visit all the code that assumes this.
221
222 AutoMutex lock(mHardwareLock);
223
John Grossman4ff14ba2012-02-08 16:37:41 -0800224 // Determine the level of master volume support the primary audio HAL has,
225 // and set the initial master volume at the same time.
226 float initialVolume = 1.0;
227 mMasterVolumeSupportLvl = MVS_NONE;
228 if (0 == mPrimaryHardwareDev->init_check(mPrimaryHardwareDev)) {
229 audio_hw_device_t *dev = mPrimaryHardwareDev;
230
231 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
232 if ((NULL != dev->get_master_volume) &&
233 (NO_ERROR == dev->get_master_volume(dev, &initialVolume))) {
234 mMasterVolumeSupportLvl = MVS_FULL;
235 } else {
236 mMasterVolumeSupportLvl = MVS_SETONLY;
237 initialVolume = 1.0;
238 }
239
240 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
241 if ((NULL == dev->set_master_volume) ||
242 (NO_ERROR != dev->set_master_volume(dev, initialVolume))) {
243 mMasterVolumeSupportLvl = MVS_NONE;
244 }
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800245 mHardwareStatus = AUDIO_HW_IDLE;
John Grossman4ff14ba2012-02-08 16:37:41 -0800246 }
247
248 // Set the mode for each audio HAL, and try to set the initial volume (if
249 // supported) for all of the non-primary audio HALs.
Dima Zavin799a70e2011-04-18 16:57:27 -0700250 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
251 audio_hw_device_t *dev = mAudioHwDevs[i];
252
253 mHardwareStatus = AUDIO_HW_INIT;
254 rc = dev->init_check(dev);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800255 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700256 if (rc == 0) {
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800257 mMode = AUDIO_MODE_NORMAL; // assigned multiple times with same value
Dima Zavin799a70e2011-04-18 16:57:27 -0700258 mHardwareStatus = AUDIO_HW_SET_MODE;
259 dev->set_mode(dev, mMode);
John Grossman4ff14ba2012-02-08 16:37:41 -0800260
261 if ((dev != mPrimaryHardwareDev) &&
262 (NULL != dev->set_master_volume)) {
263 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
264 dev->set_master_volume(dev, initialVolume);
265 }
266
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800267 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700268 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700269 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800270
271 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
272 ? initialVolume
273 : 1.0;
274 mMasterVolume = initialVolume;
275 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700276}
277
278AudioFlinger::~AudioFlinger()
279{
Dima Zavin799a70e2011-04-18 16:57:27 -0700280
Mathias Agopian65ab4712010-07-14 17:59:35 -0700281 while (!mRecordThreads.isEmpty()) {
282 // closeInput() will remove first entry from mRecordThreads
283 closeInput(mRecordThreads.keyAt(0));
284 }
285 while (!mPlaybackThreads.isEmpty()) {
286 // closeOutput() will remove first entry from mPlaybackThreads
287 closeOutput(mPlaybackThreads.keyAt(0));
288 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700289
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800290 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
291 // no mHardwareLock needed, as there are no other references to this
292 audio_hw_device_close(mAudioHwDevs[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700293 }
294}
295
Dima Zavin799a70e2011-04-18 16:57:27 -0700296audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
297{
298 /* first matching HW device is returned */
299 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
300 audio_hw_device_t *dev = mAudioHwDevs[i];
301 if ((dev->get_supported_devices(dev) & devices) == devices)
302 return dev;
303 }
304 return NULL;
305}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700306
307status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
308{
309 const size_t SIZE = 256;
310 char buffer[SIZE];
311 String8 result;
312
313 result.append("Clients:\n");
314 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800315 sp<Client> client = mClients.valueAt(i).promote();
316 if (client != 0) {
317 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
318 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700319 }
320 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700321
322 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800323 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700324 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
325 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800326 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700327 result.append(buffer);
328 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700329 write(fd, result.string(), result.size());
330 return NO_ERROR;
331}
332
333
334status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
335{
336 const size_t SIZE = 256;
337 char buffer[SIZE];
338 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800339 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700340
John Grossman4ff14ba2012-02-08 16:37:41 -0800341 snprintf(buffer, SIZE, "Hardware status: %d\n"
342 "Standby Time mSec: %u\n",
343 hardwareStatus,
344 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700345 result.append(buffer);
346 write(fd, result.string(), result.size());
347 return NO_ERROR;
348}
349
350status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
351{
352 const size_t SIZE = 256;
353 char buffer[SIZE];
354 String8 result;
355 snprintf(buffer, SIZE, "Permission Denial: "
356 "can't dump AudioFlinger from pid=%d, uid=%d\n",
357 IPCThreadState::self()->getCallingPid(),
358 IPCThreadState::self()->getCallingUid());
359 result.append(buffer);
360 write(fd, result.string(), result.size());
361 return NO_ERROR;
362}
363
364static bool tryLock(Mutex& mutex)
365{
366 bool locked = false;
367 for (int i = 0; i < kDumpLockRetries; ++i) {
368 if (mutex.tryLock() == NO_ERROR) {
369 locked = true;
370 break;
371 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800372 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700373 }
374 return locked;
375}
376
377status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
378{
Glenn Kasten44deb052012-02-05 18:09:08 -0800379 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700380 dumpPermissionDenial(fd, args);
381 } else {
382 // get state of hardware lock
383 bool hardwareLocked = tryLock(mHardwareLock);
384 if (!hardwareLocked) {
385 String8 result(kHardwareLockedString);
386 write(fd, result.string(), result.size());
387 } else {
388 mHardwareLock.unlock();
389 }
390
391 bool locked = tryLock(mLock);
392
393 // failed to lock - AudioFlinger is probably deadlocked
394 if (!locked) {
395 String8 result(kDeadlockedString);
396 write(fd, result.string(), result.size());
397 }
398
399 dumpClients(fd, args);
400 dumpInternals(fd, args);
401
402 // dump playback threads
403 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
404 mPlaybackThreads.valueAt(i)->dump(fd, args);
405 }
406
407 // dump record threads
408 for (size_t i = 0; i < mRecordThreads.size(); i++) {
409 mRecordThreads.valueAt(i)->dump(fd, args);
410 }
411
Dima Zavin799a70e2011-04-18 16:57:27 -0700412 // dump all hardware devs
413 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
414 audio_hw_device_t *dev = mAudioHwDevs[i];
415 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700416 }
417 if (locked) mLock.unlock();
418 }
419 return NO_ERROR;
420}
421
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800422sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
423{
424 // If pid is already in the mClients wp<> map, then use that entry
425 // (for which promote() is always != 0), otherwise create a new entry and Client.
426 sp<Client> client = mClients.valueFor(pid).promote();
427 if (client == 0) {
428 client = new Client(this, pid);
429 mClients.add(pid, client);
430 }
431
432 return client;
433}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700434
435// IAudioFlinger interface
436
437
438sp<IAudioTrack> AudioFlinger::createTrack(
439 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800440 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700441 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800442 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700443 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444 int frameCount,
Glenn Kasten5cf034d2012-02-21 10:35:56 -0800445 // FIXME dead, remove from IAudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700446 uint32_t flags,
447 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800448 audio_io_handle_t output,
John Grossman4ff14ba2012-02-08 16:37:41 -0800449 bool isTimed,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700450 int *sessionId,
451 status_t *status)
452{
453 sp<PlaybackThread::Track> track;
454 sp<TrackHandle> trackHandle;
455 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700456 status_t lStatus;
457 int lSessionId;
458
Glenn Kasten263709e2012-01-06 08:40:01 -0800459 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
460 // but if someone uses binder directly they could bypass that and cause us to crash
461 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000462 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700463 lStatus = BAD_VALUE;
464 goto Exit;
465 }
466
467 {
468 Mutex::Autolock _l(mLock);
469 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700470 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700471 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000472 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700473 lStatus = BAD_VALUE;
474 goto Exit;
475 }
476
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800477 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700478
Steve Block3856b092011-10-20 11:56:00 +0100479 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700480 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700481 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700482 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
483 if (mPlaybackThreads.keyAt(i) != output) {
484 // prevent same audio session on different output threads
485 uint32_t sessions = t->hasAudioSession(*sessionId);
486 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000487 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700488 lStatus = BAD_VALUE;
489 goto Exit;
490 }
491 // check if an effect with same session ID is waiting for a track to be created
492 if (sessions & PlaybackThread::EFFECT_SESSION) {
493 effectThread = t.get();
494 }
Eric Laurentde070132010-07-13 04:45:46 -0700495 }
496 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700497 lSessionId = *sessionId;
498 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700499 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700500 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700501 if (sessionId != NULL) {
502 *sessionId = lSessionId;
503 }
504 }
Steve Block3856b092011-10-20 11:56:00 +0100505 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700506
507 track = thread->createTrack_l(client, streamType, sampleRate, format,
John Grossman4ff14ba2012-02-08 16:37:41 -0800508 channelMask, frameCount, sharedBuffer, lSessionId, isTimed, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700509
510 // move effect chain to this output thread if an effect on same session was waiting
511 // for a track to be created
512 if (lStatus == NO_ERROR && effectThread != NULL) {
513 Mutex::Autolock _dl(thread->mLock);
514 Mutex::Autolock _sl(effectThread->mLock);
515 moveEffectChain_l(lSessionId, effectThread, thread, true);
516 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700517 }
518 if (lStatus == NO_ERROR) {
519 trackHandle = new TrackHandle(track);
520 } else {
521 // remove local strong reference to Client before deleting the Track so that the Client
522 // destructor is called by the TrackBase destructor with mLock held
523 client.clear();
524 track.clear();
525 }
526
527Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700528 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700529 *status = lStatus;
530 }
531 return trackHandle;
532}
533
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800534uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700535{
536 Mutex::Autolock _l(mLock);
537 PlaybackThread *thread = checkPlaybackThread_l(output);
538 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000539 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700540 return 0;
541 }
542 return thread->sampleRate();
543}
544
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800545int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700546{
547 Mutex::Autolock _l(mLock);
548 PlaybackThread *thread = checkPlaybackThread_l(output);
549 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000550 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700551 return 0;
552 }
553 return thread->channelCount();
554}
555
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800556audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700557{
558 Mutex::Autolock _l(mLock);
559 PlaybackThread *thread = checkPlaybackThread_l(output);
560 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000561 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800562 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700563 }
564 return thread->format();
565}
566
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800567size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700568{
569 Mutex::Autolock _l(mLock);
570 PlaybackThread *thread = checkPlaybackThread_l(output);
571 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000572 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700573 return 0;
574 }
575 return thread->frameCount();
576}
577
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800578uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700579{
580 Mutex::Autolock _l(mLock);
581 PlaybackThread *thread = checkPlaybackThread_l(output);
582 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000583 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700584 return 0;
585 }
586 return thread->latency();
587}
588
589status_t AudioFlinger::setMasterVolume(float value)
590{
Eric Laurenta1884f92011-08-23 08:25:03 -0700591 status_t ret = initCheck();
592 if (ret != NO_ERROR) {
593 return ret;
594 }
595
Mathias Agopian65ab4712010-07-14 17:59:35 -0700596 // check calling permissions
597 if (!settingsAllowed()) {
598 return PERMISSION_DENIED;
599 }
600
John Grossman4ff14ba2012-02-08 16:37:41 -0800601 float swmv = value;
602
Mathias Agopian65ab4712010-07-14 17:59:35 -0700603 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800604 if (MVS_NONE != mMasterVolumeSupportLvl) {
605 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
606 AutoMutex lock(mHardwareLock);
607 audio_hw_device_t *dev = mAudioHwDevs[i];
608
609 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
610 if (NULL != dev->set_master_volume) {
611 dev->set_master_volume(dev, value);
612 }
613 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800614 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800615
616 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700617 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700618
Eric Laurent93575202011-01-18 18:39:02 -0800619 Mutex::Autolock _l(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -0800620 mMasterVolume = value;
621 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800622 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700623 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700624
625 return NO_ERROR;
626}
627
Glenn Kastenf78aee72012-01-04 11:00:47 -0800628status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700629{
Eric Laurenta1884f92011-08-23 08:25:03 -0700630 status_t ret = initCheck();
631 if (ret != NO_ERROR) {
632 return ret;
633 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700634
635 // check calling permissions
636 if (!settingsAllowed()) {
637 return PERMISSION_DENIED;
638 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800639 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000640 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700641 return BAD_VALUE;
642 }
643
644 { // scope for the lock
645 AutoMutex lock(mHardwareLock);
646 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700647 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700648 mHardwareStatus = AUDIO_HW_IDLE;
649 }
650
651 if (NO_ERROR == ret) {
652 Mutex::Autolock _l(mLock);
653 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800654 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700655 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700656 }
657
658 return ret;
659}
660
661status_t AudioFlinger::setMicMute(bool state)
662{
Eric Laurenta1884f92011-08-23 08:25:03 -0700663 status_t ret = initCheck();
664 if (ret != NO_ERROR) {
665 return ret;
666 }
667
Mathias Agopian65ab4712010-07-14 17:59:35 -0700668 // check calling permissions
669 if (!settingsAllowed()) {
670 return PERMISSION_DENIED;
671 }
672
673 AutoMutex lock(mHardwareLock);
674 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700675 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700676 mHardwareStatus = AUDIO_HW_IDLE;
677 return ret;
678}
679
680bool AudioFlinger::getMicMute() const
681{
Eric Laurenta1884f92011-08-23 08:25:03 -0700682 status_t ret = initCheck();
683 if (ret != NO_ERROR) {
684 return false;
685 }
686
Dima Zavinfce7a472011-04-19 22:30:36 -0700687 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800688 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700689 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700690 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700691 mHardwareStatus = AUDIO_HW_IDLE;
692 return state;
693}
694
695status_t AudioFlinger::setMasterMute(bool muted)
696{
697 // check calling permissions
698 if (!settingsAllowed()) {
699 return PERMISSION_DENIED;
700 }
701
Eric Laurent93575202011-01-18 18:39:02 -0800702 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800703 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700704 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800705 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700706 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700707
708 return NO_ERROR;
709}
710
711float AudioFlinger::masterVolume() const
712{
Glenn Kasten98067102011-12-13 11:47:54 -0800713 Mutex::Autolock _l(mLock);
714 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700715}
716
John Grossman4ff14ba2012-02-08 16:37:41 -0800717float AudioFlinger::masterVolumeSW() const
718{
719 Mutex::Autolock _l(mLock);
720 return masterVolumeSW_l();
721}
722
Mathias Agopian65ab4712010-07-14 17:59:35 -0700723bool AudioFlinger::masterMute() const
724{
Glenn Kasten98067102011-12-13 11:47:54 -0800725 Mutex::Autolock _l(mLock);
726 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700727}
728
John Grossman4ff14ba2012-02-08 16:37:41 -0800729float AudioFlinger::masterVolume_l() const
730{
731 if (MVS_FULL == mMasterVolumeSupportLvl) {
732 float ret_val;
733 AutoMutex lock(mHardwareLock);
734
735 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800736 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
737 (NULL != mPrimaryHardwareDev->get_master_volume),
738 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800739
740 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
741 mHardwareStatus = AUDIO_HW_IDLE;
742 return ret_val;
743 }
744
745 return mMasterVolume;
746}
747
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800748status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
749 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700750{
751 // check calling permissions
752 if (!settingsAllowed()) {
753 return PERMISSION_DENIED;
754 }
755
Glenn Kasten263709e2012-01-06 08:40:01 -0800756 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000757 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700758 return BAD_VALUE;
759 }
760
761 AutoMutex lock(mLock);
762 PlaybackThread *thread = NULL;
763 if (output) {
764 thread = checkPlaybackThread_l(output);
765 if (thread == NULL) {
766 return BAD_VALUE;
767 }
768 }
769
770 mStreamTypes[stream].volume = value;
771
772 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800773 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700774 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700775 }
776 } else {
777 thread->setStreamVolume(stream, value);
778 }
779
780 return NO_ERROR;
781}
782
Glenn Kastenfff6d712012-01-12 16:38:12 -0800783status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700784{
785 // check calling permissions
786 if (!settingsAllowed()) {
787 return PERMISSION_DENIED;
788 }
789
Glenn Kasten263709e2012-01-06 08:40:01 -0800790 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700791 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000792 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700793 return BAD_VALUE;
794 }
795
Eric Laurent93575202011-01-18 18:39:02 -0800796 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700797 mStreamTypes[stream].mute = muted;
798 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700799 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700800
801 return NO_ERROR;
802}
803
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800804float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805{
Glenn Kasten263709e2012-01-06 08:40:01 -0800806 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700807 return 0.0f;
808 }
809
810 AutoMutex lock(mLock);
811 float volume;
812 if (output) {
813 PlaybackThread *thread = checkPlaybackThread_l(output);
814 if (thread == NULL) {
815 return 0.0f;
816 }
817 volume = thread->streamVolume(stream);
818 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800819 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700820 }
821
822 return volume;
823}
824
Glenn Kastenfff6d712012-01-12 16:38:12 -0800825bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700826{
Glenn Kasten263709e2012-01-06 08:40:01 -0800827 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700828 return true;
829 }
830
Glenn Kasten6637baa2012-01-09 09:40:36 -0800831 AutoMutex lock(mLock);
832 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833}
834
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800835status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700836{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800837 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700838 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
839 // check calling permissions
840 if (!settingsAllowed()) {
841 return PERMISSION_DENIED;
842 }
843
Mathias Agopian65ab4712010-07-14 17:59:35 -0700844 // ioHandle == 0 means the parameters are global to the audio hardware interface
845 if (ioHandle == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700846 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800847 {
848 AutoMutex lock(mHardwareLock);
849 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700850 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
851 audio_hw_device_t *dev = mAudioHwDevs[i];
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800852 status_t result = dev->set_parameters(dev, keyValuePairs.string());
Dima Zavin799a70e2011-04-18 16:57:27 -0700853 final_result = result ?: final_result;
854 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700855 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800856 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700857 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
858 AudioParameter param = AudioParameter(keyValuePairs);
859 String8 value;
860 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
861 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700862 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
863 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700864 for (size_t i = 0; i < mRecordThreads.size(); i++) {
865 sp<RecordThread> thread = mRecordThreads.valueAt(i);
866 RecordThread::RecordTrack *track = thread->track();
867 if (track != NULL) {
868 audio_devices_t device = (audio_devices_t)(
869 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700870 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700871 thread->setEffectSuspended(FX_IID_AEC,
872 suspend,
873 track->sessionId());
874 thread->setEffectSuspended(FX_IID_NS,
875 suspend,
876 track->sessionId());
877 }
878 }
Eric Laurentbee53372011-08-29 12:42:48 -0700879 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700880 }
881 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700882 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700883 }
884
885 // hold a strong ref on thread in case closeOutput() or closeInput() is called
886 // and the thread is exited once the lock is released
887 sp<ThreadBase> thread;
888 {
889 Mutex::Autolock _l(mLock);
890 thread = checkPlaybackThread_l(ioHandle);
891 if (thread == NULL) {
892 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800893 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700894 // indicate output device change to all input threads for pre processing
895 AudioParameter param = AudioParameter(keyValuePairs);
896 int value;
897 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
898 for (size_t i = 0; i < mRecordThreads.size(); i++) {
899 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
900 }
901 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700902 }
903 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800904 if (thread != 0) {
905 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700906 }
907 return BAD_VALUE;
908}
909
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800910String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700911{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800912// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700913// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
914
915 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700916 String8 out_s8;
917
Dima Zavin799a70e2011-04-18 16:57:27 -0700918 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800919 char *s;
920 {
921 AutoMutex lock(mHardwareLock);
922 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700923 audio_hw_device_t *dev = mAudioHwDevs[i];
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800924 s = dev->get_parameters(dev, keys.string());
925 mHardwareStatus = AUDIO_HW_IDLE;
926 }
John Grossmanef7740b2012-02-09 11:28:36 -0800927 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700928 free(s);
929 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700930 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700931 }
932
933 Mutex::Autolock _l(mLock);
934
935 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
936 if (playbackThread != NULL) {
937 return playbackThread->getParameters(keys);
938 }
939 RecordThread *recordThread = checkRecordThread_l(ioHandle);
940 if (recordThread != NULL) {
941 return recordThread->getParameters(keys);
942 }
943 return String8("");
944}
945
Glenn Kastenf587ba52012-01-26 16:25:10 -0800946size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700947{
Eric Laurenta1884f92011-08-23 08:25:03 -0700948 status_t ret = initCheck();
949 if (ret != NO_ERROR) {
950 return 0;
951 }
952
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800953 AutoMutex lock(mHardwareLock);
954 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
955 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
956 mHardwareStatus = AUDIO_HW_IDLE;
957 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700958}
959
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800960unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700961{
962 if (ioHandle == 0) {
963 return 0;
964 }
965
966 Mutex::Autolock _l(mLock);
967
968 RecordThread *recordThread = checkRecordThread_l(ioHandle);
969 if (recordThread != NULL) {
970 return recordThread->getInputFramesLost();
971 }
972 return 0;
973}
974
975status_t AudioFlinger::setVoiceVolume(float value)
976{
Eric Laurenta1884f92011-08-23 08:25:03 -0700977 status_t ret = initCheck();
978 if (ret != NO_ERROR) {
979 return ret;
980 }
981
Mathias Agopian65ab4712010-07-14 17:59:35 -0700982 // check calling permissions
983 if (!settingsAllowed()) {
984 return PERMISSION_DENIED;
985 }
986
987 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800988 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700989 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700990 mHardwareStatus = AUDIO_HW_IDLE;
991
992 return ret;
993}
994
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800995status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
996 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700997{
998 status_t status;
999
1000 Mutex::Autolock _l(mLock);
1001
1002 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1003 if (playbackThread != NULL) {
1004 return playbackThread->getRenderPosition(halFrames, dspFrames);
1005 }
1006
1007 return BAD_VALUE;
1008}
1009
1010void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1011{
1012
1013 Mutex::Autolock _l(mLock);
1014
Glenn Kastenbb001922012-02-03 11:10:26 -08001015 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001016 if (mNotificationClients.indexOfKey(pid) < 0) {
1017 sp<NotificationClient> notificationClient = new NotificationClient(this,
1018 client,
1019 pid);
Steve Block3856b092011-10-20 11:56:00 +01001020 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001021
1022 mNotificationClients.add(pid, notificationClient);
1023
1024 sp<IBinder> binder = client->asBinder();
1025 binder->linkToDeath(notificationClient);
1026
1027 // the config change is always sent from playback or record threads to avoid deadlock
1028 // with AudioSystem::gLock
1029 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1030 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1031 }
1032
1033 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1034 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1035 }
1036 }
1037}
1038
1039void AudioFlinger::removeNotificationClient(pid_t pid)
1040{
1041 Mutex::Autolock _l(mLock);
1042
Glenn Kastena3b09252012-01-20 09:19:01 -08001043 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001044
Steve Block3856b092011-10-20 11:56:00 +01001045 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001046 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001047 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001048 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001049 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001050 ALOGV(" pid %d @ %d", ref->mPid, i);
1051 if (ref->mPid == pid) {
1052 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001053 mAudioSessionRefs.removeAt(i);
1054 delete ref;
1055 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001056 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001057 } else {
1058 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001059 }
1060 }
1061 if (removed) {
1062 purgeStaleEffects_l();
1063 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001064}
1065
1066// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001067void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001068{
1069 size_t size = mNotificationClients.size();
1070 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001071 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1072 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001073 }
1074}
1075
1076// removeClient_l() must be called with AudioFlinger::mLock held
1077void AudioFlinger::removeClient_l(pid_t pid)
1078{
Steve Block3856b092011-10-20 11:56:00 +01001079 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001080 mClients.removeItem(pid);
1081}
1082
1083
1084// ----------------------------------------------------------------------------
1085
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001086AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1087 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001088 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001089 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001090 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
1091 // mChannelMask
1092 mChannelCount(0),
1093 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1094 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001095 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001096 mDevice(device),
1097 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001098{
1099}
1100
1101AudioFlinger::ThreadBase::~ThreadBase()
1102{
1103 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001104 // do not lock the mutex in destructor
1105 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001106 if (mPowerManager != 0) {
1107 sp<IBinder> binder = mPowerManager->asBinder();
1108 binder->unlinkToDeath(mDeathRecipient);
1109 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001110}
1111
1112void AudioFlinger::ThreadBase::exit()
1113{
Steve Block3856b092011-10-20 11:56:00 +01001114 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001115 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001116 // This lock prevents the following race in thread (uniprocessor for illustration):
1117 // if (!exitPending()) {
1118 // // context switch from here to exit()
1119 // // exit() calls requestExit(), what exitPending() observes
1120 // // exit() calls signal(), which is dropped since no waiters
1121 // // context switch back from exit() to here
1122 // mWaitWorkCV.wait(...);
1123 // // now thread is hung
1124 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001125 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001126 requestExit();
1127 mWaitWorkCV.signal();
1128 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001129 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1130 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001131 requestExitAndWait();
1132}
1133
Mathias Agopian65ab4712010-07-14 17:59:35 -07001134status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1135{
1136 status_t status;
1137
Steve Block3856b092011-10-20 11:56:00 +01001138 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001139 Mutex::Autolock _l(mLock);
1140
1141 mNewParameters.add(keyValuePairs);
1142 mWaitWorkCV.signal();
1143 // wait condition with timeout in case the thread loop has exited
1144 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001145 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001146 status = mParamStatus;
1147 mWaitWorkCV.signal();
1148 } else {
1149 status = TIMED_OUT;
1150 }
1151 return status;
1152}
1153
1154void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1155{
1156 Mutex::Autolock _l(mLock);
1157 sendConfigEvent_l(event, param);
1158}
1159
1160// sendConfigEvent_l() must be called with ThreadBase::mLock held
1161void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1162{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001163 ConfigEvent configEvent;
1164 configEvent.mEvent = event;
1165 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001166 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001167 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001168 mWaitWorkCV.signal();
1169}
1170
1171void AudioFlinger::ThreadBase::processConfigEvents()
1172{
1173 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001174 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001175 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001176 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001177 mConfigEvents.removeAt(0);
1178 // release mLock before locking AudioFlinger mLock: lock order is always
1179 // AudioFlinger then ThreadBase to avoid cross deadlock
1180 mLock.unlock();
1181 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001182 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001183 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001184 mLock.lock();
1185 }
1186 mLock.unlock();
1187}
1188
1189status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1190{
1191 const size_t SIZE = 256;
1192 char buffer[SIZE];
1193 String8 result;
1194
1195 bool locked = tryLock(mLock);
1196 if (!locked) {
1197 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1198 write(fd, buffer, strlen(buffer));
1199 }
1200
Eric Laurent612bbb52012-03-14 15:03:26 -07001201 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1202 result.append(buffer);
1203 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1204 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001205 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1206 result.append(buffer);
1207 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1208 result.append(buffer);
1209 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1210 result.append(buffer);
1211 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1212 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001213 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1214 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001215 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1216 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001217 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001218 result.append(buffer);
1219
1220 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1221 result.append(buffer);
1222 result.append(" Index Command");
1223 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1224 snprintf(buffer, SIZE, "\n %02d ", i);
1225 result.append(buffer);
1226 result.append(mNewParameters[i]);
1227 }
1228
1229 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1230 result.append(buffer);
1231 snprintf(buffer, SIZE, " Index event param\n");
1232 result.append(buffer);
1233 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001234 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001235 result.append(buffer);
1236 }
1237 result.append("\n");
1238
1239 write(fd, result.string(), result.size());
1240
1241 if (locked) {
1242 mLock.unlock();
1243 }
1244 return NO_ERROR;
1245}
1246
Eric Laurent1d2bff02011-07-24 17:49:51 -07001247status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1248{
1249 const size_t SIZE = 256;
1250 char buffer[SIZE];
1251 String8 result;
1252
1253 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1254 write(fd, buffer, strlen(buffer));
1255
1256 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1257 sp<EffectChain> chain = mEffectChains[i];
1258 if (chain != 0) {
1259 chain->dump(fd, args);
1260 }
1261 }
1262 return NO_ERROR;
1263}
1264
Eric Laurentfeb0db62011-07-22 09:04:31 -07001265void AudioFlinger::ThreadBase::acquireWakeLock()
1266{
1267 Mutex::Autolock _l(mLock);
1268 acquireWakeLock_l();
1269}
1270
1271void AudioFlinger::ThreadBase::acquireWakeLock_l()
1272{
1273 if (mPowerManager == 0) {
1274 // use checkService() to avoid blocking if power service is not up yet
1275 sp<IBinder> binder =
1276 defaultServiceManager()->checkService(String16("power"));
1277 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001278 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001279 } else {
1280 mPowerManager = interface_cast<IPowerManager>(binder);
1281 binder->linkToDeath(mDeathRecipient);
1282 }
1283 }
1284 if (mPowerManager != 0) {
1285 sp<IBinder> binder = new BBinder();
1286 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1287 binder,
1288 String16(mName));
1289 if (status == NO_ERROR) {
1290 mWakeLockToken = binder;
1291 }
Steve Block3856b092011-10-20 11:56:00 +01001292 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001293 }
1294}
1295
1296void AudioFlinger::ThreadBase::releaseWakeLock()
1297{
1298 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001299 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001300}
1301
1302void AudioFlinger::ThreadBase::releaseWakeLock_l()
1303{
1304 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001305 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001306 if (mPowerManager != 0) {
1307 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1308 }
1309 mWakeLockToken.clear();
1310 }
1311}
1312
1313void AudioFlinger::ThreadBase::clearPowerManager()
1314{
1315 Mutex::Autolock _l(mLock);
1316 releaseWakeLock_l();
1317 mPowerManager.clear();
1318}
1319
1320void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1321{
1322 sp<ThreadBase> thread = mThread.promote();
1323 if (thread != 0) {
1324 thread->clearPowerManager();
1325 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001326 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001327}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001328
Eric Laurent59255e42011-07-27 19:49:51 -07001329void AudioFlinger::ThreadBase::setEffectSuspended(
1330 const effect_uuid_t *type, bool suspend, int sessionId)
1331{
1332 Mutex::Autolock _l(mLock);
1333 setEffectSuspended_l(type, suspend, sessionId);
1334}
1335
1336void AudioFlinger::ThreadBase::setEffectSuspended_l(
1337 const effect_uuid_t *type, bool suspend, int sessionId)
1338{
Glenn Kasten090f0192012-01-30 13:00:02 -08001339 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001340 if (chain != 0) {
1341 if (type != NULL) {
1342 chain->setEffectSuspended_l(type, suspend);
1343 } else {
1344 chain->setEffectSuspendedAll_l(suspend);
1345 }
1346 }
1347
1348 updateSuspendedSessions_l(type, suspend, sessionId);
1349}
1350
1351void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1352{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001353 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001354 if (index < 0) {
1355 return;
1356 }
1357
1358 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1359 mSuspendedSessions.editValueAt(index);
1360
1361 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001362 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001363 for (int j = 0; j < desc->mRefCount; j++) {
1364 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1365 chain->setEffectSuspendedAll_l(true);
1366 } else {
Steve Block3856b092011-10-20 11:56:00 +01001367 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001368 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001369 chain->setEffectSuspended_l(&desc->mType, true);
1370 }
1371 }
1372 }
1373}
1374
Eric Laurent59255e42011-07-27 19:49:51 -07001375void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1376 bool suspend,
1377 int sessionId)
1378{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001379 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001380
1381 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1382
1383 if (suspend) {
1384 if (index >= 0) {
1385 sessionEffects = mSuspendedSessions.editValueAt(index);
1386 } else {
1387 mSuspendedSessions.add(sessionId, sessionEffects);
1388 }
1389 } else {
1390 if (index < 0) {
1391 return;
1392 }
1393 sessionEffects = mSuspendedSessions.editValueAt(index);
1394 }
1395
1396
1397 int key = EffectChain::kKeyForSuspendAll;
1398 if (type != NULL) {
1399 key = type->timeLow;
1400 }
1401 index = sessionEffects.indexOfKey(key);
1402
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001403 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001404 if (suspend) {
1405 if (index >= 0) {
1406 desc = sessionEffects.valueAt(index);
1407 } else {
1408 desc = new SuspendedSessionDesc();
1409 if (type != NULL) {
1410 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1411 }
1412 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001413 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001414 }
1415 desc->mRefCount++;
1416 } else {
1417 if (index < 0) {
1418 return;
1419 }
1420 desc = sessionEffects.valueAt(index);
1421 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001422 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001423 sessionEffects.removeItemsAt(index);
1424 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001425 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001426 sessionId);
1427 mSuspendedSessions.removeItem(sessionId);
1428 }
1429 }
1430 }
1431 if (!sessionEffects.isEmpty()) {
1432 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1433 }
1434}
1435
1436void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1437 bool enabled,
1438 int sessionId)
1439{
1440 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001441 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1442}
Eric Laurent59255e42011-07-27 19:49:51 -07001443
Eric Laurenta85a74a2011-10-19 11:44:54 -07001444void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1445 bool enabled,
1446 int sessionId)
1447{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001448 if (mType != RECORD) {
1449 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1450 // another session. This gives the priority to well behaved effect control panels
1451 // and applications not using global effects.
1452 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1453 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1454 }
1455 }
Eric Laurent59255e42011-07-27 19:49:51 -07001456
1457 sp<EffectChain> chain = getEffectChain_l(sessionId);
1458 if (chain != 0) {
1459 chain->checkSuspendOnEffectEnabled(effect, enabled);
1460 }
1461}
1462
Mathias Agopian65ab4712010-07-14 17:59:35 -07001463// ----------------------------------------------------------------------------
1464
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001465AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1466 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001467 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001468 uint32_t device,
1469 type_t type)
1470 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001471 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1472 // Assumes constructor is called by AudioFlinger with it's mLock held,
1473 // but it would be safer to explicitly pass initial masterMute as parameter
1474 mMasterMute(audioFlinger->masterMute_l()),
1475 // mStreamTypes[] initialized in constructor body
1476 mOutput(output),
1477 // Assumes constructor is called by AudioFlinger with it's mLock held,
1478 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001479 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001480 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001481 mMixerStatus(MIXER_IDLE),
Glenn Kasten66fcab92012-02-24 14:59:21 -08001482 mPrevMixerStatus(MIXER_IDLE),
1483 standbyDelay(AudioFlinger::mStandbyTimeInNsecs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001484{
Glenn Kasten480b4682012-02-28 12:30:08 -08001485 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001486
Mathias Agopian65ab4712010-07-14 17:59:35 -07001487 readOutputParameters();
1488
Glenn Kasten263709e2012-01-06 08:40:01 -08001489 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001490 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1491 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1492 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001493 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1494 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001495 // initialized by stream_type_t default constructor
1496 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001497 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001498 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1499 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001500}
1501
1502AudioFlinger::PlaybackThread::~PlaybackThread()
1503{
1504 delete [] mMixBuffer;
1505}
1506
1507status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1508{
1509 dumpInternals(fd, args);
1510 dumpTracks(fd, args);
1511 dumpEffectChains(fd, args);
1512 return NO_ERROR;
1513}
1514
1515status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1516{
1517 const size_t SIZE = 256;
1518 char buffer[SIZE];
1519 String8 result;
1520
1521 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1522 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001523 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 -07001524 for (size_t i = 0; i < mTracks.size(); ++i) {
1525 sp<Track> track = mTracks[i];
1526 if (track != 0) {
1527 track->dump(buffer, SIZE);
1528 result.append(buffer);
1529 }
1530 }
1531
1532 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1533 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001534 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 -07001535 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001536 sp<Track> track = mActiveTracks[i].promote();
1537 if (track != 0) {
1538 track->dump(buffer, SIZE);
1539 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001540 }
1541 }
1542 write(fd, result.string(), result.size());
1543 return NO_ERROR;
1544}
1545
Mathias Agopian65ab4712010-07-14 17:59:35 -07001546status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1547{
1548 const size_t SIZE = 256;
1549 char buffer[SIZE];
1550 String8 result;
1551
1552 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1553 result.append(buffer);
1554 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1555 result.append(buffer);
1556 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1557 result.append(buffer);
1558 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1559 result.append(buffer);
1560 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1561 result.append(buffer);
1562 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1563 result.append(buffer);
1564 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1565 result.append(buffer);
1566 write(fd, result.string(), result.size());
1567
1568 dumpBase(fd, args);
1569
1570 return NO_ERROR;
1571}
1572
1573// Thread virtuals
1574status_t AudioFlinger::PlaybackThread::readyToRun()
1575{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001576 status_t status = initCheck();
1577 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001578 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001579 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001580 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001581 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001582 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001583}
1584
1585void AudioFlinger::PlaybackThread::onFirstRef()
1586{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001587 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001588}
1589
1590// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001591sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001592 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001593 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001594 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001595 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001596 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001597 int frameCount,
1598 const sp<IMemory>& sharedBuffer,
1599 int sessionId,
John Grossman4ff14ba2012-02-08 16:37:41 -08001600 bool isTimed,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001601 status_t *status)
1602{
1603 sp<Track> track;
1604 status_t lStatus;
1605
1606 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001607 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1608 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001609 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001610 "for output %p with format %d",
1611 sampleRate, format, channelMask, mOutput, mFormat);
1612 lStatus = BAD_VALUE;
1613 goto Exit;
1614 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001615 }
1616 } else {
1617 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1618 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001619 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001620 lStatus = BAD_VALUE;
1621 goto Exit;
1622 }
1623 }
1624
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001625 lStatus = initCheck();
1626 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001627 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001628 goto Exit;
1629 }
1630
1631 { // scope for mLock
1632 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001633
1634 // all tracks in same audio session must share the same routing strategy otherwise
1635 // conflicts will happen when tracks are moved from one output to another by audio policy
1636 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001637 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001638 for (size_t i = 0; i < mTracks.size(); ++i) {
1639 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001640 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001641 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001642 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001643 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001644 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001645 lStatus = BAD_VALUE;
1646 goto Exit;
1647 }
1648 }
1649 }
1650
John Grossman4ff14ba2012-02-08 16:37:41 -08001651 if (!isTimed) {
1652 track = new Track(this, client, streamType, sampleRate, format,
1653 channelMask, frameCount, sharedBuffer, sessionId);
1654 } else {
1655 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1656 channelMask, frameCount, sharedBuffer, sessionId);
1657 }
1658 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001659 lStatus = NO_MEMORY;
1660 goto Exit;
1661 }
1662 mTracks.add(track);
1663
1664 sp<EffectChain> chain = getEffectChain_l(sessionId);
1665 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001666 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001667 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001668 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001669 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001670 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001671
1672 // invalidate track immediately if the stream type was moved to another thread since
1673 // createTrack() was called by the client process.
1674 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001675 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001676 this, streamType);
Eric Laurent9f6530f2011-08-30 10:18:54 -07001677 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1678 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001679 }
1680 lStatus = NO_ERROR;
1681
1682Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001683 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001684 *status = lStatus;
1685 }
1686 return track;
1687}
1688
1689uint32_t AudioFlinger::PlaybackThread::latency() const
1690{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001691 Mutex::Autolock _l(mLock);
1692 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001693 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001694 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695 return 0;
1696 }
1697}
1698
Glenn Kasten6637baa2012-01-09 09:40:36 -08001699void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001700{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001701 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001702 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001703}
1704
Glenn Kasten6637baa2012-01-09 09:40:36 -08001705void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001706{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001707 Mutex::Autolock _l(mLock);
1708 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001709}
1710
Glenn Kasten6637baa2012-01-09 09:40:36 -08001711void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001712{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001713 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001714 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001715}
1716
Glenn Kasten6637baa2012-01-09 09:40:36 -08001717void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001718{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001719 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001720 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001721}
1722
Glenn Kastenfff6d712012-01-12 16:38:12 -08001723float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001724{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001725 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001726 return mStreamTypes[stream].volume;
1727}
1728
Mathias Agopian65ab4712010-07-14 17:59:35 -07001729// addTrack_l() must be called with ThreadBase::mLock held
1730status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1731{
1732 status_t status = ALREADY_EXISTS;
1733
1734 // set retry count for buffer fill
1735 track->mRetryCount = kMaxTrackStartupRetries;
1736 if (mActiveTracks.indexOf(track) < 0) {
1737 // the track is newly added, make sure it fills up all its
1738 // buffers before playing. This is to ensure the client will
1739 // effectively get the latency it requested.
1740 track->mFillingUpStatus = Track::FS_FILLING;
1741 track->mResetDone = false;
1742 mActiveTracks.add(track);
1743 if (track->mainBuffer() != mMixBuffer) {
1744 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1745 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001746 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001747 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001748 }
1749 }
1750
1751 status = NO_ERROR;
1752 }
1753
Steve Block3856b092011-10-20 11:56:00 +01001754 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001755 mWaitWorkCV.broadcast();
1756
1757 return status;
1758}
1759
1760// destroyTrack_l() must be called with ThreadBase::mLock held
1761void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1762{
1763 track->mState = TrackBase::TERMINATED;
1764 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001765 removeTrack_l(track);
1766 }
1767}
1768
1769void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1770{
1771 mTracks.remove(track);
1772 deleteTrackName_l(track->name());
1773 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1774 if (chain != 0) {
1775 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001776 }
1777}
1778
1779String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1780{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001781 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001782 char *s;
1783
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001784 Mutex::Autolock _l(mLock);
1785 if (initCheck() != NO_ERROR) {
1786 return out_s8;
1787 }
1788
Dima Zavin799a70e2011-04-18 16:57:27 -07001789 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001790 out_s8 = String8(s);
1791 free(s);
1792 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001793}
1794
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001795// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001796void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1797 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001798 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001799
Steve Block3856b092011-10-20 11:56:00 +01001800 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001801
1802 switch (event) {
1803 case AudioSystem::OUTPUT_OPENED:
1804 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001805 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001806 desc.samplingRate = mSampleRate;
1807 desc.format = mFormat;
1808 desc.frameCount = mFrameCount;
1809 desc.latency = latency();
1810 param2 = &desc;
1811 break;
1812
1813 case AudioSystem::STREAM_CONFIG_CHANGED:
1814 param2 = &param;
1815 case AudioSystem::OUTPUT_CLOSED:
1816 default:
1817 break;
1818 }
1819 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1820}
1821
1822void AudioFlinger::PlaybackThread::readOutputParameters()
1823{
Dima Zavin799a70e2011-04-18 16:57:27 -07001824 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001825 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1826 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001827 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001828 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001829 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001830
1831 // FIXME - Current mixer implementation only supports stereo output: Always
1832 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001833 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001834 mMixBuffer = new int16_t[mFrameCount * 2];
1835 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1836
Eric Laurentde070132010-07-13 04:45:46 -07001837 // force reconfiguration of effect chains and engines to take new buffer size and audio
1838 // parameters into account
1839 // Note that mLock is not held when readOutputParameters() is called from the constructor
1840 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1841 // matter.
1842 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1843 Vector< sp<EffectChain> > effectChains = mEffectChains;
1844 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001845 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001846 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001847}
1848
1849status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1850{
Glenn Kastena0d68332012-01-27 16:47:15 -08001851 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001852 return BAD_VALUE;
1853 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001854 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001855 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856 return INVALID_OPERATION;
1857 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001858 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001859
Dima Zavin799a70e2011-04-18 16:57:27 -07001860 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861}
1862
Eric Laurent39e94f82010-07-28 01:32:47 -07001863uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001864{
1865 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001866 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001867 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001868 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001869 }
1870
1871 for (size_t i = 0; i < mTracks.size(); ++i) {
1872 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001873 if (sessionId == track->sessionId() &&
1874 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001875 result |= TRACK_SESSION;
1876 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001877 }
1878 }
1879
Eric Laurent39e94f82010-07-28 01:32:47 -07001880 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001881}
1882
Eric Laurentde070132010-07-13 04:45:46 -07001883uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1884{
Dima Zavinfce7a472011-04-19 22:30:36 -07001885 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001886 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001887 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1888 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001889 }
1890 for (size_t i = 0; i < mTracks.size(); i++) {
1891 sp<Track> track = mTracks[i];
1892 if (sessionId == track->sessionId() &&
1893 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001894 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07001895 }
1896 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001897 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001898}
1899
Mathias Agopian65ab4712010-07-14 17:59:35 -07001900
Glenn Kastenaed850d2012-01-26 09:46:34 -08001901AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001902{
1903 Mutex::Autolock _l(mLock);
1904 return mOutput;
1905}
1906
1907AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1908{
1909 Mutex::Autolock _l(mLock);
1910 AudioStreamOut *output = mOutput;
1911 mOutput = NULL;
1912 return output;
1913}
1914
1915// this method must always be called either with ThreadBase mLock held or inside the thread loop
1916audio_stream_t* AudioFlinger::PlaybackThread::stream()
1917{
1918 if (mOutput == NULL) {
1919 return NULL;
1920 }
1921 return &mOutput->stream->common;
1922}
1923
Eric Laurent162b40b2011-12-05 09:47:19 -08001924uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1925{
1926 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1927 // decoding and transfer time. So sleeping for half of the latency would likely cause
1928 // underruns
1929 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1930 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1931 } else {
1932 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1933 }
1934}
1935
Mathias Agopian65ab4712010-07-14 17:59:35 -07001936// ----------------------------------------------------------------------------
1937
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001938AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001939 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten000f0e32012-03-01 17:10:56 -08001940 : PlaybackThread(audioFlinger, output, id, device, type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001941{
Glenn Kasten000f0e32012-03-01 17:10:56 -08001942 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001943 // FIXME - Current mixer implementation only supports stereo output
1944 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001945 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001946 }
1947}
1948
1949AudioFlinger::MixerThread::~MixerThread()
1950{
1951 delete mAudioMixer;
1952}
1953
Glenn Kasten83efdd02012-02-24 07:21:32 -08001954class CpuStats {
1955public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08001956 CpuStats();
1957 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08001958#ifdef DEBUG_CPU_USAGE
1959private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08001960 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
1961 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
1962
1963 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
1964
1965 int mCpuNum; // thread's current CPU number
1966 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08001967#endif
1968};
1969
Glenn Kasten190a46f2012-03-06 11:27:10 -08001970CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08001971#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08001972 : mCpuNum(-1), mCpukHz(-1)
1973#endif
1974{
1975}
1976
1977void CpuStats::sample(const String8 &title) {
1978#ifdef DEBUG_CPU_USAGE
1979 // get current thread's delta CPU time in wall clock ns
1980 double wcNs;
1981 bool valid = mCpuUsage.sampleAndEnable(wcNs);
1982
1983 // record sample for wall clock statistics
1984 if (valid) {
1985 mWcStats.sample(wcNs);
1986 }
1987
1988 // get the current CPU number
1989 int cpuNum = sched_getcpu();
1990
1991 // get the current CPU frequency in kHz
1992 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
1993
1994 // check if either CPU number or frequency changed
1995 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
1996 mCpuNum = cpuNum;
1997 mCpukHz = cpukHz;
1998 // ignore sample for purposes of cycles
1999 valid = false;
2000 }
2001
2002 // if no change in CPU number or frequency, then record sample for cycle statistics
2003 if (valid && mCpukHz > 0) {
2004 double cycles = wcNs * cpukHz * 0.000001;
2005 mHzStats.sample(cycles);
2006 }
2007
2008 unsigned n = mWcStats.n();
2009 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002010 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002011 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002012 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2013 double perLoop = elapsed / (double) n;
2014 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002015 double perLoop1k = perLoop * 0.001;
2016 double mean = mWcStats.mean();
2017 double stddev = mWcStats.stddev();
2018 double minimum = mWcStats.minimum();
2019 double maximum = mWcStats.maximum();
2020 double meanCycles = mHzStats.mean();
2021 double stddevCycles = mHzStats.stddev();
2022 double minCycles = mHzStats.minimum();
2023 double maxCycles = mHzStats.maximum();
2024 mCpuUsage.resetElapsed();
2025 mWcStats.reset();
2026 mHzStats.reset();
2027 ALOGD("CPU usage for %s over past %.1f secs\n"
2028 " (%u mixer loops at %.1f mean ms per loop):\n"
2029 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2030 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2031 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2032 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002033 elapsed * .000000001, n, perLoop * .000001,
2034 mean * .001,
2035 stddev * .001,
2036 minimum * .001,
2037 maximum * .001,
2038 mean / perLoop100,
2039 stddev / perLoop100,
2040 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002041 maximum / perLoop100,
2042 meanCycles / perLoop1k,
2043 stddevCycles / perLoop1k,
2044 minCycles / perLoop1k,
2045 maxCycles / perLoop1k);
2046
Glenn Kasten83efdd02012-02-24 07:21:32 -08002047 }
2048 }
2049#endif
2050};
2051
Glenn Kasten37d825e2012-02-24 07:21:48 -08002052void AudioFlinger::PlaybackThread::checkSilentMode_l()
2053{
2054 if (!mMasterMute) {
2055 char value[PROPERTY_VALUE_MAX];
2056 if (property_get("ro.audio.silent", value, "0") > 0) {
2057 char *endptr;
2058 unsigned long ul = strtoul(value, &endptr, 0);
2059 if (*endptr == '\0' && ul != 0) {
2060 ALOGD("Silence is golden");
2061 // The setprop command will not allow a property to be changed after
2062 // the first time it is set, so we don't have to worry about un-muting.
2063 setMasterMute_l(true);
2064 }
2065 }
2066 }
2067}
2068
Glenn Kasten000f0e32012-03-01 17:10:56 -08002069bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002070{
2071 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002072
Glenn Kasten000f0e32012-03-01 17:10:56 -08002073 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002074
2075 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002076 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002077if (mType == MIXER) {
2078 longStandbyExit = false;
2079}
Glenn Kasten688a6402012-02-29 07:57:06 -08002080
Glenn Kasten000f0e32012-03-01 17:10:56 -08002081 // DUPLICATING
2082 // FIXME could this be made local to while loop?
2083 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002084
Glenn Kasten66fcab92012-02-24 14:59:21 -08002085 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002086 sleepTime = idleSleepTime;
2087
2088if (mType == MIXER) {
2089 sleepTimeShift = 0;
2090}
2091
Glenn Kasten83efdd02012-02-24 07:21:32 -08002092 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002093 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002094
Eric Laurentfeb0db62011-07-22 09:04:31 -07002095 acquireWakeLock();
2096
Mathias Agopian65ab4712010-07-14 17:59:35 -07002097 while (!exitPending())
2098 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002099 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002100
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002101 Vector< sp<EffectChain> > effectChains;
2102
Mathias Agopian65ab4712010-07-14 17:59:35 -07002103 processConfigEvents();
2104
Mathias Agopian65ab4712010-07-14 17:59:35 -07002105 { // scope for mLock
2106
2107 Mutex::Autolock _l(mLock);
2108
2109 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002110 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002111 }
2112
Glenn Kastenfa26a852012-03-06 11:28:04 -08002113 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002114
Mathias Agopian65ab4712010-07-14 17:59:35 -07002115 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002116 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002117 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002118 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002119
2120 threadLoop_standby();
2121
Mathias Agopian65ab4712010-07-14 17:59:35 -07002122 mStandby = true;
2123 mBytesWritten = 0;
2124 }
2125
Glenn Kasten3e074702012-02-28 18:40:35 -08002126 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002127 // we're about to wait, flush the binder command buffer
2128 IPCThreadState::self()->flushCommands();
2129
Glenn Kastenfa26a852012-03-06 11:28:04 -08002130 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002131
Mathias Agopian65ab4712010-07-14 17:59:35 -07002132 if (exitPending()) break;
2133
Eric Laurentfeb0db62011-07-22 09:04:31 -07002134 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002135 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002136 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002137 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002138 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002139 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002140
Eric Laurent27741442012-01-17 19:20:12 -08002141 mPrevMixerStatus = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002142
Glenn Kasten37d825e2012-02-24 07:21:48 -08002143 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002144
Glenn Kasten000f0e32012-03-01 17:10:56 -08002145 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002146 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002147 if (mType == MIXER) {
2148 sleepTimeShift = 0;
2149 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002150
Mathias Agopian65ab4712010-07-14 17:59:35 -07002151 continue;
2152 }
2153 }
2154
Glenn Kastenfec279f2012-03-08 07:47:15 -08002155 mixer_state newMixerStatus = prepareTracks_l(&tracksToRemove);
2156 // Shift in the new status; this could be a queue if it's
2157 // useful to filter the mixer status over several cycles.
2158 mPrevMixerStatus = mMixerStatus;
2159 mMixerStatus = newMixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002160
2161 // prevent any changes in effect chain list and in each effect chain
2162 // during mixing and effect process as the audio buffers could be deleted
2163 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002164 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002165 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002166
Glenn Kastenfec279f2012-03-08 07:47:15 -08002167 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002168 threadLoop_mix();
2169 } else {
2170 threadLoop_sleepTime();
2171 }
2172
2173 if (mSuspended > 0) {
2174 sleepTime = suspendSleepTimeUs();
2175 }
2176
2177 // only process effects if we're going to write
2178 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002179 for (size_t i = 0; i < effectChains.size(); i ++) {
2180 effectChains[i]->process_l();
2181 }
2182 }
2183
2184 // enable changes in effect chain
2185 unlockEffectChains(effectChains);
2186
2187 // sleepTime == 0 means we must write to audio hardware
2188 if (sleepTime == 0) {
2189
2190 threadLoop_write();
2191
2192if (mType == MIXER) {
2193 // write blocked detection
2194 nsecs_t now = systemTime();
2195 nsecs_t delta = now - mLastWriteTime;
2196 if (!mStandby && delta > maxPeriod) {
2197 mNumDelayedWrites++;
2198 if ((now - lastWarning) > kWarningThrottleNs) {
2199 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2200 ns2ms(delta), mNumDelayedWrites, this);
2201 lastWarning = now;
2202 }
2203 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2204 // a different threshold. Or completely removed for what it is worth anyway...
2205 if (mStandby) {
2206 longStandbyExit = true;
2207 }
2208 }
2209}
2210
2211 mStandby = false;
2212 } else {
2213 usleep(sleepTime);
2214 }
2215
2216 // finally let go of removed track(s), without the lock held
2217 // since we can't guarantee the destructors won't acquire that
2218 // same lock.
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002219 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002220
Glenn Kastenfa26a852012-03-06 11:28:04 -08002221 // FIXME I don't understand the need for this here;
2222 // it was in the original code but maybe the
2223 // assignment in saveOutputTracks() makes this unnecessary?
2224 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002225
2226 // Effect chains will be actually deleted here if they were removed from
2227 // mEffectChains list during mixing or effects processing
2228 effectChains.clear();
2229
2230 // FIXME Note that the above .clear() is no longer necessary since effectChains
2231 // is now local to this block, but will keep it for now (at least until merge done).
2232 }
2233
2234if (mType == MIXER || mType == DIRECT) {
2235 // put output stream into standby mode
2236 if (!mStandby) {
2237 mOutput->stream->common.standby(&mOutput->stream->common);
2238 }
2239}
2240if (mType == DUPLICATING) {
2241 // for DuplicatingThread, standby mode is handled by the outputTracks
2242}
2243
2244 releaseWakeLock();
2245
2246 ALOGV("Thread %p type %d exiting", this, mType);
2247 return false;
2248}
2249
2250// shared by MIXER and DIRECT, overridden by DUPLICATING
2251void AudioFlinger::PlaybackThread::threadLoop_write()
2252{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002253 // FIXME rewrite to reduce number of system calls
2254 mLastWriteTime = systemTime();
2255 mInWrite = true;
2256 mBytesWritten += mixBufferSize;
2257 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2258 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2259 mNumWrites++;
2260 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002261}
2262
2263// shared by MIXER and DIRECT, overridden by DUPLICATING
2264void AudioFlinger::PlaybackThread::threadLoop_standby()
2265{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002266 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2267 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002268}
2269
2270void AudioFlinger::MixerThread::threadLoop_mix()
2271{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002272 // obtain the presentation timestamp of the next output buffer
2273 int64_t pts;
2274 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002275
Glenn Kasten952eeb22012-03-06 11:30:57 -08002276 if (NULL != mOutput->stream->get_next_write_timestamp) {
2277 status = mOutput->stream->get_next_write_timestamp(
2278 mOutput->stream, &pts);
2279 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002280
Glenn Kasten952eeb22012-03-06 11:30:57 -08002281 if (status != NO_ERROR) {
2282 pts = AudioBufferProvider::kInvalidPTS;
2283 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002284
Glenn Kasten952eeb22012-03-06 11:30:57 -08002285 // mix buffers...
2286 mAudioMixer->process(pts);
2287 // increase sleep time progressively when application underrun condition clears.
2288 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2289 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2290 // such that we would underrun the audio HAL.
2291 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2292 sleepTimeShift--;
2293 }
2294 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002295 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002296 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002297}
2298
2299void AudioFlinger::MixerThread::threadLoop_sleepTime()
2300{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002301 // If no tracks are ready, sleep once for the duration of an output
2302 // buffer size, then write 0s to the output
2303 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002304 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002305 sleepTime = activeSleepTime >> sleepTimeShift;
2306 if (sleepTime < kMinThreadSleepTimeUs) {
2307 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002308 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002309 // reduce sleep time in case of consecutive application underruns to avoid
2310 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2311 // duration we would end up writing less data than needed by the audio HAL if
2312 // the condition persists.
2313 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2314 sleepTimeShift++;
2315 }
2316 } else {
2317 sleepTime = idleSleepTime;
2318 }
2319 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002320 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002321 memset (mMixBuffer, 0, mixBufferSize);
2322 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002323 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002324 }
2325 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002326}
2327
2328// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002329AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002330 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002331{
2332
Glenn Kasten29c23c32012-01-26 13:37:52 -08002333 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002334 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002335 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002336 size_t mixedTracks = 0;
2337 size_t tracksWithEffect = 0;
2338
2339 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002340 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002341
Eric Laurent571d49c2010-08-11 05:20:11 -07002342 if (masterMute) {
2343 masterVolume = 0;
2344 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002345 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002346 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002347 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002348 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002349 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002350 masterVolume = (float)((v + (1 << 23)) >> 24);
2351 chain.clear();
2352 }
2353
2354 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002355 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002356 if (t == 0) continue;
2357
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002358 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002359 Track* const track = t.get();
2360 audio_track_cblk_t* cblk = track->cblk();
2361
2362 // The first time a track is added we wait
2363 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002364 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002365 // make sure that we have enough frames to mix one full buffer.
2366 // enforce this condition only once to enable draining the buffer in case the client
2367 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002368 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002369 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002370 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002371 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002372 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002373 if (t->sampleRate() == (int)mSampleRate) {
2374 minFrames = mFrameCount;
2375 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002376 // +1 for rounding and +1 for additional sample needed for interpolation
2377 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2378 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07002379 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08002380 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2381 // the minimum track buffer size is normally twice the number of frames necessary
2382 // to fill one buffer and the resampler should not leave more than one buffer worth
2383 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002384 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002385 }
2386 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002387 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002388 !track->isPaused() && !track->isTerminated())
2389 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002390 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002391
2392 mixedTracks++;
2393
2394 // track->mainBuffer() != mMixBuffer means there is an effect chain
2395 // connected to the track
2396 chain.clear();
2397 if (track->mainBuffer() != mMixBuffer) {
2398 chain = getEffectChain_l(track->sessionId());
2399 // Delegate volume control to effect in track effect chain if needed
2400 if (chain != 0) {
2401 tracksWithEffect++;
2402 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002403 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002404 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002405 }
2406 }
2407
2408
2409 int param = AudioMixer::VOLUME;
2410 if (track->mFillingUpStatus == Track::FS_FILLED) {
2411 // no ramp for the first volume setting
2412 track->mFillingUpStatus = Track::FS_ACTIVE;
2413 if (track->mState == TrackBase::RESUMING) {
2414 track->mState = TrackBase::ACTIVE;
2415 param = AudioMixer::RAMP_VOLUME;
2416 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002417 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002418 } else if (cblk->server != 0) {
2419 // If the track is stopped before the first frame was mixed,
2420 // do not apply ramp
2421 param = AudioMixer::RAMP_VOLUME;
2422 }
2423
2424 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002425 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002426 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002427 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002428 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002429 if (track->isPausing()) {
2430 track->setPaused();
2431 }
2432 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002433
Mathias Agopian65ab4712010-07-14 17:59:35 -07002434 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002435 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002436 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002437 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002438 vl = vlr & 0xFFFF;
2439 vr = vlr >> 16;
2440 // track volumes come from shared memory, so can't be trusted and must be clamped
2441 if (vl > MAX_GAIN_INT) {
2442 ALOGV("Track left volume out of range: %04X", vl);
2443 vl = MAX_GAIN_INT;
2444 }
2445 if (vr > MAX_GAIN_INT) {
2446 ALOGV("Track right volume out of range: %04X", vr);
2447 vr = MAX_GAIN_INT;
2448 }
2449 // now apply the master volume and stream type volume
2450 vl = (uint32_t)(v * vl) << 12;
2451 vr = (uint32_t)(v * vr) << 12;
2452 // assuming master volume and stream type volume each go up to 1.0,
2453 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002454
Glenn Kasten05632a52012-01-03 14:22:33 -08002455 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2456 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002457 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002458 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002459 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002460 }
2461 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002462 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002463 // Delegate volume control to effect in track effect chain if needed
2464 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2465 // Do not ramp volume if volume is controlled by effect
2466 param = AudioMixer::VOLUME;
2467 track->mHasVolumeController = true;
2468 } else {
2469 // force no volume ramp when volume controller was just disabled or removed
2470 // from effect chain to avoid volume spike
2471 if (track->mHasVolumeController) {
2472 param = AudioMixer::VOLUME;
2473 }
2474 track->mHasVolumeController = false;
2475 }
2476
2477 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002478 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002479 vl = (vl + (1 << 11)) >> 12;
2480 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2481 vr = (vr + (1 << 11)) >> 12;
2482 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002483
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002484 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 -07002485
Mathias Agopian65ab4712010-07-14 17:59:35 -07002486 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002487 mAudioMixer->setBufferProvider(name, track);
2488 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002489
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002490 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2491 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2492 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002493 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002494 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002495 AudioMixer::TRACK,
2496 AudioMixer::FORMAT, (void *)track->format());
2497 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002498 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002499 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002500 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002501 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002502 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002503 AudioMixer::RESAMPLE,
2504 AudioMixer::SAMPLE_RATE,
2505 (void *)(cblk->sampleRate));
2506 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002507 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002508 AudioMixer::TRACK,
2509 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2510 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002511 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002512 AudioMixer::TRACK,
2513 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2514
2515 // reset retry count
2516 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002517
Eric Laurent27741442012-01-17 19:20:12 -08002518 // If one track is ready, set the mixer ready if:
2519 // - the mixer was not ready during previous round OR
2520 // - no other track is not ready
2521 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2522 mixerStatus != MIXER_TRACKS_ENABLED) {
2523 mixerStatus = MIXER_TRACKS_READY;
2524 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002525 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002526 //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 -07002527 if (track->isStopped()) {
2528 track->reset();
2529 }
2530 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2531 // We have consumed all the buffers of this track.
2532 // Remove it from the list of active tracks.
2533 tracksToRemove->add(track);
2534 } else {
2535 // No buffers for this track. Give it a few chances to
2536 // fill a buffer, then remove it from active list.
2537 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002538 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002539 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002540 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002541 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002542 // If one track is not ready, mark the mixer also not ready if:
2543 // - the mixer was ready during previous round OR
2544 // - no other track is ready
2545 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2546 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002547 mixerStatus = MIXER_TRACKS_ENABLED;
2548 }
2549 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002550 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002551 }
2552 }
2553
2554 // remove all the tracks that need to be...
2555 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002556 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002557 for (size_t i=0 ; i<count ; i++) {
2558 const sp<Track>& track = tracksToRemove->itemAt(i);
2559 mActiveTracks.remove(track);
2560 if (track->mainBuffer() != mMixBuffer) {
2561 chain = getEffectChain_l(track->sessionId());
2562 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002563 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002564 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002565 }
2566 }
2567 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002568 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002569 }
2570 }
2571 }
2572
2573 // mix buffer must be cleared if all tracks are connected to an
2574 // effect chain as in this case the mixer will not write to
2575 // mix buffer and track effects will accumulate into it
2576 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2577 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2578 }
2579
2580 return mixerStatus;
2581}
2582
Glenn Kasten66fcab92012-02-24 14:59:21 -08002583/*
2584The derived values that are cached:
2585 - mixBufferSize from frame count * frame size
2586 - activeSleepTime from activeSleepTimeUs()
2587 - idleSleepTime from idleSleepTimeUs()
2588 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2589 - maxPeriod from frame count and sample rate (MIXER only)
2590
2591The parameters that affect these derived values are:
2592 - frame count
2593 - frame size
2594 - sample rate
2595 - device type: A2DP or not
2596 - device latency
2597 - format: PCM or not
2598 - active sleep time
2599 - idle sleep time
2600*/
2601
2602void AudioFlinger::PlaybackThread::cacheParameters_l()
2603{
2604 mixBufferSize = mFrameCount * mFrameSize;
2605 activeSleepTime = activeSleepTimeUs();
2606 idleSleepTime = idleSleepTimeUs();
2607}
2608
Glenn Kastenfff6d712012-01-12 16:38:12 -08002609void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002610{
Steve Block3856b092011-10-20 11:56:00 +01002611 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002612 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002613 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002614
Mathias Agopian65ab4712010-07-14 17:59:35 -07002615 size_t size = mTracks.size();
2616 for (size_t i = 0; i < size; i++) {
2617 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08002618 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002619 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002620 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002621 }
2622 }
2623}
2624
Glenn Kastenfff6d712012-01-12 16:38:12 -08002625void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002626{
Steve Block3856b092011-10-20 11:56:00 +01002627 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002628 this, streamType, valid);
2629 Mutex::Autolock _l(mLock);
2630
2631 mStreamTypes[streamType].valid = valid;
2632}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002633
2634// getTrackName_l() must be called with ThreadBase::mLock held
2635int AudioFlinger::MixerThread::getTrackName_l()
2636{
2637 return mAudioMixer->getTrackName();
2638}
2639
2640// deleteTrackName_l() must be called with ThreadBase::mLock held
2641void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2642{
Steve Block3856b092011-10-20 11:56:00 +01002643 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002644 mAudioMixer->deleteTrackName(name);
2645}
2646
2647// checkForNewParameters_l() must be called with ThreadBase::mLock held
2648bool AudioFlinger::MixerThread::checkForNewParameters_l()
2649{
2650 bool reconfig = false;
2651
2652 while (!mNewParameters.isEmpty()) {
2653 status_t status = NO_ERROR;
2654 String8 keyValuePair = mNewParameters[0];
2655 AudioParameter param = AudioParameter(keyValuePair);
2656 int value;
2657
2658 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2659 reconfig = true;
2660 }
2661 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002662 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002663 status = BAD_VALUE;
2664 } else {
2665 reconfig = true;
2666 }
2667 }
2668 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002669 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002670 status = BAD_VALUE;
2671 } else {
2672 reconfig = true;
2673 }
2674 }
2675 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2676 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002677 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002678 // if frame count is changed after track creation
2679 if (!mTracks.isEmpty()) {
2680 status = INVALID_OPERATION;
2681 } else {
2682 reconfig = true;
2683 }
2684 }
2685 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07002686#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08002687 // when changing the audio output device, call addBatteryData to notify
2688 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002689 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002690 uint32_t params = 0;
2691 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002692 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002693 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2694 }
2695
2696 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002697 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002698 // check if any other device (except speaker) is on
2699 if (value & deviceWithoutSpeaker ) {
2700 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2701 }
2702
2703 if (params != 0) {
2704 addBatteryData(params);
2705 }
2706 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07002707#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08002708
Mathias Agopian65ab4712010-07-14 17:59:35 -07002709 // forward device change to effects that have requested to be
2710 // aware of attached audio device.
2711 mDevice = (uint32_t)value;
2712 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002713 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002714 }
2715 }
2716
2717 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002718 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002719 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002720 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002721 mOutput->stream->common.standby(&mOutput->stream->common);
2722 mStandby = true;
2723 mBytesWritten = 0;
2724 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002725 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002726 }
2727 if (status == NO_ERROR && reconfig) {
2728 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002729 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2730 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002731 readOutputParameters();
2732 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2733 for (size_t i = 0; i < mTracks.size() ; i++) {
2734 int name = getTrackName_l();
2735 if (name < 0) break;
2736 mTracks[i]->mName = name;
2737 // limit track sample rate to 2 x new output sample rate
2738 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2739 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2740 }
2741 }
2742 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2743 }
2744 }
2745
2746 mNewParameters.removeAt(0);
2747
2748 mParamStatus = status;
2749 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002750 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2751 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002752 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002753 }
2754 return reconfig;
2755}
2756
2757status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2758{
2759 const size_t SIZE = 256;
2760 char buffer[SIZE];
2761 String8 result;
2762
2763 PlaybackThread::dumpInternals(fd, args);
2764
2765 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2766 result.append(buffer);
2767 write(fd, result.string(), result.size());
2768 return NO_ERROR;
2769}
2770
Mathias Agopian65ab4712010-07-14 17:59:35 -07002771uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2772{
Eric Laurent60e18242010-07-29 06:50:24 -07002773 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002774}
2775
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002776uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2777{
2778 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2779}
2780
Glenn Kasten66fcab92012-02-24 14:59:21 -08002781void AudioFlinger::MixerThread::cacheParameters_l()
2782{
2783 PlaybackThread::cacheParameters_l();
2784
2785 // FIXME: Relaxed timing because of a certain device that can't meet latency
2786 // Should be reduced to 2x after the vendor fixes the driver issue
2787 // increase threshold again due to low power audio mode. The way this warning
2788 // threshold is calculated and its usefulness should be reconsidered anyway.
2789 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
2790}
2791
Mathias Agopian65ab4712010-07-14 17:59:35 -07002792// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002793AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2794 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002795 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002796 // mLeftVolFloat, mRightVolFloat
2797 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002798{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002799}
2800
2801AudioFlinger::DirectOutputThread::~DirectOutputThread()
2802{
2803}
2804
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002805AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
2806 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08002807)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002808{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002809 sp<Track> trackToRemove;
2810
Glenn Kastenfec279f2012-03-08 07:47:15 -08002811 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002812
Glenn Kasten952eeb22012-03-06 11:30:57 -08002813 // find out which tracks need to be processed
2814 if (mActiveTracks.size() != 0) {
2815 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08002816 // The track died recently
2817 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002818
Glenn Kasten952eeb22012-03-06 11:30:57 -08002819 Track* const track = t.get();
2820 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002821
Glenn Kasten952eeb22012-03-06 11:30:57 -08002822 // The first time a track is added we wait
2823 // for all its buffers to be filled before processing it
2824 if (cblk->framesReady() && track->isReady() &&
2825 !track->isPaused() && !track->isTerminated())
2826 {
2827 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002828
Glenn Kasten952eeb22012-03-06 11:30:57 -08002829 if (track->mFillingUpStatus == Track::FS_FILLED) {
2830 track->mFillingUpStatus = Track::FS_ACTIVE;
2831 mLeftVolFloat = mRightVolFloat = 0;
2832 mLeftVolShort = mRightVolShort = 0;
2833 if (track->mState == TrackBase::RESUMING) {
2834 track->mState = TrackBase::ACTIVE;
2835 rampVolume = true;
2836 }
2837 } else if (cblk->server != 0) {
2838 // If the track is stopped before the first frame was mixed,
2839 // do not apply ramp
2840 rampVolume = true;
2841 }
2842 // compute volume for this track
2843 float left, right;
2844 if (track->isMuted() || mMasterMute || track->isPausing() ||
2845 mStreamTypes[track->streamType()].mute) {
2846 left = right = 0;
2847 if (track->isPausing()) {
2848 track->setPaused();
2849 }
2850 } else {
2851 float typeVolume = mStreamTypes[track->streamType()].volume;
2852 float v = mMasterVolume * typeVolume;
2853 uint32_t vlr = cblk->getVolumeLR();
2854 float v_clamped = v * (vlr & 0xFFFF);
2855 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2856 left = v_clamped/MAX_GAIN;
2857 v_clamped = v * (vlr >> 16);
2858 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2859 right = v_clamped/MAX_GAIN;
2860 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002861
Glenn Kasten952eeb22012-03-06 11:30:57 -08002862 if (left != mLeftVolFloat || right != mRightVolFloat) {
2863 mLeftVolFloat = left;
2864 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002865
Glenn Kasten952eeb22012-03-06 11:30:57 -08002866 // If audio HAL implements volume control,
2867 // force software volume to nominal value
2868 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
2869 left = 1.0f;
2870 right = 1.0f;
2871 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002872
Glenn Kasten952eeb22012-03-06 11:30:57 -08002873 // Convert volumes from float to 8.24
2874 uint32_t vl = (uint32_t)(left * (1 << 24));
2875 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002876
Glenn Kasten952eeb22012-03-06 11:30:57 -08002877 // Delegate volume control to effect in track effect chain if needed
2878 // only one effect chain can be present on DirectOutputThread, so if
2879 // there is one, the track is connected to it
2880 if (!mEffectChains.isEmpty()) {
2881 // Do not ramp volume if volume is controlled by effect
2882 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002883 rampVolume = false;
2884 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002885 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002886
Glenn Kasten952eeb22012-03-06 11:30:57 -08002887 // Convert volumes from 8.24 to 4.12 format
2888 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2889 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2890 leftVol = (uint16_t)v_clamped;
2891 v_clamped = (vr + (1 << 11)) >> 12;
2892 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2893 rightVol = (uint16_t)v_clamped;
2894 } else {
2895 leftVol = mLeftVolShort;
2896 rightVol = mRightVolShort;
2897 rampVolume = false;
2898 }
2899
2900 // reset retry count
2901 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002902 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002903 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002904 } else {
2905 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2906 if (track->isStopped()) {
2907 track->reset();
2908 }
2909 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2910 // We have consumed all the buffers of this track.
2911 // Remove it from the list of active tracks.
2912 trackToRemove = track;
2913 } else {
2914 // No buffers for this track. Give it a few chances to
2915 // fill a buffer, then remove it from active list.
2916 if (--(track->mRetryCount) <= 0) {
2917 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2918 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002919 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002920 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002921 }
2922 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002923 }
2924 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002925
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002926 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08002927 // remove all the tracks that need to be...
2928 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002929 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002930 mActiveTracks.remove(trackToRemove);
2931 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002932 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08002933 trackToRemove->sessionId());
2934 mEffectChains[0]->decActiveTrackCnt();
2935 }
2936 if (trackToRemove->isTerminated()) {
2937 removeTrack_l(trackToRemove);
2938 }
2939 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002940
Glenn Kastenfec279f2012-03-08 07:47:15 -08002941 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002942}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002943
Glenn Kasten000f0e32012-03-01 17:10:56 -08002944void AudioFlinger::DirectOutputThread::threadLoop_mix()
2945{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002946 AudioBufferProvider::Buffer buffer;
2947 size_t frameCount = mFrameCount;
2948 int8_t *curBuf = (int8_t *)mMixBuffer;
2949 // output audio to hardware
2950 while (frameCount) {
2951 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002952 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002953 if (CC_UNLIKELY(buffer.raw == NULL)) {
2954 memset(curBuf, 0, frameCount * mFrameSize);
2955 break;
2956 }
2957 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2958 frameCount -= buffer.frameCount;
2959 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002960 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002961 }
2962 sleepTime = 0;
2963 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002964 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08002965
2966 // apply volume
2967
2968 // Do not apply volume on compressed audio
2969 if (!audio_is_linear_pcm(mFormat)) {
2970 return;
2971 }
2972
2973 // convert to signed 16 bit before volume calculation
2974 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
2975 size_t count = mFrameCount * mChannelCount;
2976 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2977 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002978 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08002979 *dst-- = (int16_t)(*src--^0x80) << 8;
2980 }
2981 }
2982
2983 frameCount = mFrameCount;
2984 int16_t *out = mMixBuffer;
2985 if (rampVolume) {
2986 if (mChannelCount == 1) {
2987 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2988 int32_t vlInc = d / (int32_t)frameCount;
2989 int32_t vl = ((int32_t)mLeftVolShort << 16);
2990 do {
2991 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2992 out++;
2993 vl += vlInc;
2994 } while (--frameCount);
2995
2996 } else {
2997 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2998 int32_t vlInc = d / (int32_t)frameCount;
2999 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
3000 int32_t vrInc = d / (int32_t)frameCount;
3001 int32_t vl = ((int32_t)mLeftVolShort << 16);
3002 int32_t vr = ((int32_t)mRightVolShort << 16);
3003 do {
3004 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3005 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3006 out += 2;
3007 vl += vlInc;
3008 vr += vrInc;
3009 } while (--frameCount);
3010 }
3011 } else {
3012 if (mChannelCount == 1) {
3013 do {
3014 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3015 out++;
3016 } while (--frameCount);
3017 } else {
3018 do {
3019 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3020 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3021 out += 2;
3022 } while (--frameCount);
3023 }
3024 }
3025
3026 // convert back to unsigned 8 bit after volume calculation
3027 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3028 size_t count = mFrameCount * mChannelCount;
3029 int16_t *src = mMixBuffer;
3030 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003031 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003032 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3033 }
3034 }
3035
3036 mLeftVolShort = leftVol;
3037 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003038}
3039
3040void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3041{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003042 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003043 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003044 sleepTime = activeSleepTime;
3045 } else {
3046 sleepTime = idleSleepTime;
3047 }
3048 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3049 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
3050 sleepTime = 0;
3051 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003052}
3053
3054// getTrackName_l() must be called with ThreadBase::mLock held
3055int AudioFlinger::DirectOutputThread::getTrackName_l()
3056{
3057 return 0;
3058}
3059
3060// deleteTrackName_l() must be called with ThreadBase::mLock held
3061void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3062{
3063}
3064
3065// checkForNewParameters_l() must be called with ThreadBase::mLock held
3066bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3067{
3068 bool reconfig = false;
3069
3070 while (!mNewParameters.isEmpty()) {
3071 status_t status = NO_ERROR;
3072 String8 keyValuePair = mNewParameters[0];
3073 AudioParameter param = AudioParameter(keyValuePair);
3074 int value;
3075
3076 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3077 // do not accept frame count changes if tracks are open as the track buffer
3078 // size depends on frame count and correct behavior would not be garantied
3079 // if frame count is changed after track creation
3080 if (!mTracks.isEmpty()) {
3081 status = INVALID_OPERATION;
3082 } else {
3083 reconfig = true;
3084 }
3085 }
3086 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003087 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003088 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003089 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003090 mOutput->stream->common.standby(&mOutput->stream->common);
3091 mStandby = true;
3092 mBytesWritten = 0;
3093 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003094 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003095 }
3096 if (status == NO_ERROR && reconfig) {
3097 readOutputParameters();
3098 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3099 }
3100 }
3101
3102 mNewParameters.removeAt(0);
3103
3104 mParamStatus = status;
3105 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003106 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3107 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003108 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003109 }
3110 return reconfig;
3111}
3112
3113uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
3114{
3115 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003116 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003117 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003118 } else {
3119 time = 10000;
3120 }
3121 return time;
3122}
3123
3124uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
3125{
3126 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003127 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003128 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003129 } else {
3130 time = 10000;
3131 }
3132 return time;
3133}
3134
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003135uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
3136{
3137 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003138 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003139 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3140 } else {
3141 time = 10000;
3142 }
3143 return time;
3144}
3145
Glenn Kasten66fcab92012-02-24 14:59:21 -08003146void AudioFlinger::DirectOutputThread::cacheParameters_l()
3147{
3148 PlaybackThread::cacheParameters_l();
3149
3150 // use shorter standby delay as on normal output to release
3151 // hardware resources as soon as possible
3152 standbyDelay = microseconds(activeSleepTime*2);
3153}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003154
Mathias Agopian65ab4712010-07-14 17:59:35 -07003155// ----------------------------------------------------------------------------
3156
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003157AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003158 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003159 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3160 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003161{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003162 addOutputTrack(mainThread);
3163}
3164
3165AudioFlinger::DuplicatingThread::~DuplicatingThread()
3166{
3167 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3168 mOutputTracks[i]->destroy();
3169 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003170}
3171
Glenn Kasten000f0e32012-03-01 17:10:56 -08003172void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003173{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003174 // mix buffers...
3175 if (outputsReady(outputTracks)) {
3176 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3177 } else {
3178 memset(mMixBuffer, 0, mixBufferSize);
3179 }
3180 sleepTime = 0;
3181 writeFrames = mFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003182}
3183
3184void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3185{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003186 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003187 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003188 sleepTime = activeSleepTime;
3189 } else {
3190 sleepTime = idleSleepTime;
3191 }
3192 } else if (mBytesWritten != 0) {
3193 // flush remaining overflow buffers in output tracks
3194 for (size_t i = 0; i < outputTracks.size(); i++) {
3195 if (outputTracks[i]->isActive()) {
3196 sleepTime = 0;
3197 writeFrames = 0;
3198 memset(mMixBuffer, 0, mixBufferSize);
3199 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003200 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003201 }
3202 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003203}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003204
Glenn Kasten000f0e32012-03-01 17:10:56 -08003205void AudioFlinger::DuplicatingThread::threadLoop_write()
3206{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003207 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003208 for (size_t i = 0; i < outputTracks.size(); i++) {
3209 outputTracks[i]->write(mMixBuffer, writeFrames);
3210 }
3211 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003212}
Glenn Kasten688a6402012-02-29 07:57:06 -08003213
Glenn Kasten000f0e32012-03-01 17:10:56 -08003214void AudioFlinger::DuplicatingThread::threadLoop_standby()
3215{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003216 // DuplicatingThread implements standby by stopping all tracks
3217 for (size_t i = 0; i < outputTracks.size(); i++) {
3218 outputTracks[i]->stop();
3219 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220}
3221
Glenn Kastenfa26a852012-03-06 11:28:04 -08003222void AudioFlinger::DuplicatingThread::saveOutputTracks()
3223{
3224 outputTracks = mOutputTracks;
3225}
3226
3227void AudioFlinger::DuplicatingThread::clearOutputTracks()
3228{
3229 outputTracks.clear();
3230}
3231
Mathias Agopian65ab4712010-07-14 17:59:35 -07003232void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3233{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003234 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003235 // FIXME explain this formula
Mathias Agopian65ab4712010-07-14 17:59:35 -07003236 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003237 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003238 this,
3239 mSampleRate,
3240 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003241 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003242 frameCount);
3243 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003244 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003245 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003246 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003247 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003248 }
3249}
3250
3251void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3252{
3253 Mutex::Autolock _l(mLock);
3254 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003255 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003256 mOutputTracks[i]->destroy();
3257 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003258 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003259 return;
3260 }
3261 }
Steve Block3856b092011-10-20 11:56:00 +01003262 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003263}
3264
Glenn Kasten438b0362012-03-06 11:24:48 -08003265// caller must hold mLock
3266void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003267{
3268 mWaitTimeMs = UINT_MAX;
3269 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3270 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003271 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003272 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3273 if (waitTimeMs < mWaitTimeMs) {
3274 mWaitTimeMs = waitTimeMs;
3275 }
3276 }
3277 }
3278}
3279
3280
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003281bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003282{
3283 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003284 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003285 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003286 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003287 return false;
3288 }
3289 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3290 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003291 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003292 return false;
3293 }
3294 }
3295 return true;
3296}
3297
3298uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3299{
3300 return (mWaitTimeMs * 1000) / 2;
3301}
3302
Glenn Kasten66fcab92012-02-24 14:59:21 -08003303void AudioFlinger::DuplicatingThread::cacheParameters_l()
3304{
3305 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3306 updateWaitTime_l();
3307
3308 MixerThread::cacheParameters_l();
3309}
3310
Mathias Agopian65ab4712010-07-14 17:59:35 -07003311// ----------------------------------------------------------------------------
3312
3313// TrackBase constructor must be called with AudioFlinger::mLock held
3314AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003315 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003316 const sp<Client>& client,
3317 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003318 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003319 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003320 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003321 const sp<IMemory>& sharedBuffer,
3322 int sessionId)
3323 : RefBase(),
3324 mThread(thread),
3325 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003326 mCblk(NULL),
3327 // mBuffer
3328 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003329 mFrameCount(0),
3330 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003331 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003332 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003333 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003334 // mChannelCount
3335 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003336{
Steve Block3856b092011-10-20 11:56:00 +01003337 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003338
Steve Blockb8a80522011-12-20 16:23:08 +00003339 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003340 size_t size = sizeof(audio_track_cblk_t);
3341 uint8_t channelCount = popcount(channelMask);
3342 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3343 if (sharedBuffer == 0) {
3344 size += bufferSize;
3345 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003346
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003347 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003348 mCblkMemory = client->heap()->allocate(size);
3349 if (mCblkMemory != 0) {
3350 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003351 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003352 new(mCblk) audio_track_cblk_t();
3353 // clear all buffers
3354 mCblk->frameCount = frameCount;
3355 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003356 mChannelCount = channelCount;
3357 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003358 if (sharedBuffer == 0) {
3359 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3360 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3361 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003362 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003363 mCblk->flags = CBLK_UNDERRUN_ON;
3364 } else {
3365 mBuffer = sharedBuffer->pointer();
3366 }
3367 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3368 }
3369 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003370 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003371 client->heap()->dump("AudioTrack");
3372 return;
3373 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003374 } else {
3375 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07003376 // construct the shared structure in-place.
3377 new(mCblk) audio_track_cblk_t();
3378 // clear all buffers
3379 mCblk->frameCount = frameCount;
3380 mCblk->sampleRate = sampleRate;
3381 mChannelCount = channelCount;
3382 mChannelMask = channelMask;
3383 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3384 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3385 // Force underrun condition to avoid false underrun callback until first data is
3386 // written to buffer (other flags are cleared)
3387 mCblk->flags = CBLK_UNDERRUN_ON;
3388 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003389 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003390}
3391
3392AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3393{
Glenn Kastena0d68332012-01-27 16:47:15 -08003394 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003395 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003396 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003397 } else {
3398 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003399 }
3400 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003401 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003402 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003403 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003404 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003405 // If the client's reference count drops to zero, the associated destructor
3406 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3407 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003408 mClient.clear();
3409 }
3410}
3411
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003412// AudioBufferProvider interface
3413// getNextBuffer() = 0;
3414// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07003415void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3416{
Glenn Kastene0feee32011-12-13 11:53:26 -08003417 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003418 mFrameCount = buffer->frameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003419 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003420 buffer->frameCount = 0;
3421}
3422
3423bool AudioFlinger::ThreadBase::TrackBase::step() {
3424 bool result;
3425 audio_track_cblk_t* cblk = this->cblk();
3426
3427 result = cblk->stepServer(mFrameCount);
3428 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003429 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003430 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003431 }
3432 return result;
3433}
3434
3435void AudioFlinger::ThreadBase::TrackBase::reset() {
3436 audio_track_cblk_t* cblk = this->cblk();
3437
3438 cblk->user = 0;
3439 cblk->server = 0;
3440 cblk->userBase = 0;
3441 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003442 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01003443 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003444}
3445
Mathias Agopian65ab4712010-07-14 17:59:35 -07003446int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3447 return (int)mCblk->sampleRate;
3448}
3449
Mathias Agopian65ab4712010-07-14 17:59:35 -07003450void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3451 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003452 size_t frameSize = cblk->frameSize;
3453 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3454 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003455
3456 // Check validity of returned pointer in case the track control block would have been corrupted.
3457 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003458 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003459 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 -07003460 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003461 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003462 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003463 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003464 }
3465
3466 return bufferStart;
3467}
3468
3469// ----------------------------------------------------------------------------
3470
3471// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3472AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003473 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003474 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003475 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003476 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003477 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003478 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003479 int frameCount,
3480 const sp<IMemory>& sharedBuffer,
3481 int sessionId)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003482 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003483 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3484 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003485{
3486 if (mCblk != NULL) {
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003487 if (thread != NULL) {
3488 mName = thread->getTrackName_l();
3489 mMainBuffer = thread->mixBuffer();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003490 }
Glenn Kasten23d82a92012-02-03 11:10:00 -08003491 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003492 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003493 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003494 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003495 mStreamType = streamType;
3496 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3497 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003498 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003499 }
3500}
3501
3502AudioFlinger::PlaybackThread::Track::~Track()
3503{
Steve Block3856b092011-10-20 11:56:00 +01003504 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003505 sp<ThreadBase> thread = mThread.promote();
3506 if (thread != 0) {
3507 Mutex::Autolock _l(thread->mLock);
3508 mState = TERMINATED;
3509 }
3510}
3511
3512void AudioFlinger::PlaybackThread::Track::destroy()
3513{
3514 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3515 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08003516 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003517 // we must acquire a strong reference on this Track before locking mLock
3518 // here so that the destructor is called only when exiting this function.
3519 // On the other hand, as long as Track::destroy() is only called by
3520 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3521 // this Track with its member mTrack.
3522 sp<Track> keep(this);
3523 { // scope for mLock
3524 sp<ThreadBase> thread = mThread.promote();
3525 if (thread != 0) {
3526 if (!isOutputTrack()) {
3527 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08003528 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003529
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003530#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003531 // to track the speaker usage
3532 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003533#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003534 }
3535 AudioSystem::releaseOutput(thread->id());
3536 }
3537 Mutex::Autolock _l(thread->mLock);
3538 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3539 playbackThread->destroyTrack_l(this);
3540 }
3541 }
3542}
3543
3544void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3545{
Glenn Kasten83d86532012-01-17 14:39:34 -08003546 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003547 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 -07003548 mName - AudioMixer::TRACK0,
Glenn Kasten44deb052012-02-05 18:09:08 -08003549 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003550 mStreamType,
3551 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003552 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003553 mSessionId,
3554 mFrameCount,
3555 mState,
3556 mMute,
3557 mFillingUpStatus,
3558 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003559 vlr & 0xFFFF,
3560 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003561 mCblk->server,
3562 mCblk->user,
3563 (int)mMainBuffer,
3564 (int)mAuxBuffer);
3565}
3566
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003567// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08003568status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003569 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003570{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003571 audio_track_cblk_t* cblk = this->cblk();
3572 uint32_t framesReady;
3573 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003574
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003575 // Check if last stepServer failed, try to step now
3576 if (mStepServerFailed) {
3577 if (!step()) goto getNextBuffer_exit;
3578 ALOGV("stepServer recovered");
3579 mStepServerFailed = false;
3580 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003581
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003582 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003583
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003584 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003585 uint32_t s = cblk->server;
3586 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3587
3588 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3589 if (framesReq > framesReady) {
3590 framesReq = framesReady;
3591 }
3592 if (s + framesReq > bufferEnd) {
3593 framesReq = bufferEnd - s;
3594 }
3595
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003596 buffer->raw = getBuffer(s, framesReq);
3597 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003598
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003599 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003600 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003601 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003602
3603getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003604 buffer->raw = NULL;
3605 buffer->frameCount = 0;
3606 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3607 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003608}
3609
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003610uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08003611 return mCblk->framesReady();
3612}
3613
Mathias Agopian65ab4712010-07-14 17:59:35 -07003614bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003615 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003616
John Grossman4ff14ba2012-02-08 16:37:41 -08003617 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003618 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3619 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003620 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003621 return true;
3622 }
3623 return false;
3624}
3625
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003626status_t AudioFlinger::PlaybackThread::Track::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003627{
3628 status_t status = NO_ERROR;
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003629 ALOGV("start(%d), calling pid %d session %d tid %d",
3630 mName, IPCThreadState::self()->getCallingPid(), mSessionId, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003631 sp<ThreadBase> thread = mThread.promote();
3632 if (thread != 0) {
3633 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003634 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003635 // here the track could be either new, or restarted
3636 // in both cases "unstop" the track
3637 if (mState == PAUSED) {
3638 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003639 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003640 } else {
3641 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003642 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003643 }
3644
3645 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3646 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003647 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003648 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003649
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003650#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003651 // to track the speaker usage
3652 if (status == NO_ERROR) {
3653 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3654 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003655#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003656 }
3657 if (status == NO_ERROR) {
3658 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3659 playbackThread->addTrack_l(this);
3660 } else {
3661 mState = state;
3662 }
3663 } else {
3664 status = BAD_VALUE;
3665 }
3666 return status;
3667}
3668
3669void AudioFlinger::PlaybackThread::Track::stop()
3670{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003671 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003672 sp<ThreadBase> thread = mThread.promote();
3673 if (thread != 0) {
3674 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003675 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003676 if (mState > STOPPED) {
3677 mState = STOPPED;
3678 // If the track is not active (PAUSED and buffers full), flush buffers
3679 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3680 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3681 reset();
3682 }
Steve Block3856b092011-10-20 11:56:00 +01003683 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003684 }
3685 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3686 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003687 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003688 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003689
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003690#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003691 // to track the speaker usage
3692 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003693#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003694 }
3695 }
3696}
3697
3698void AudioFlinger::PlaybackThread::Track::pause()
3699{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003700 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003701 sp<ThreadBase> thread = mThread.promote();
3702 if (thread != 0) {
3703 Mutex::Autolock _l(thread->mLock);
3704 if (mState == ACTIVE || mState == RESUMING) {
3705 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003706 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003707 if (!isOutputTrack()) {
3708 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003709 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003710 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003711
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003712#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003713 // to track the speaker usage
3714 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003715#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003716 }
3717 }
3718 }
3719}
3720
3721void AudioFlinger::PlaybackThread::Track::flush()
3722{
Steve Block3856b092011-10-20 11:56:00 +01003723 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003724 sp<ThreadBase> thread = mThread.promote();
3725 if (thread != 0) {
3726 Mutex::Autolock _l(thread->mLock);
3727 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3728 return;
3729 }
3730 // No point remaining in PAUSED state after a flush => go to
3731 // STOPPED state
3732 mState = STOPPED;
3733
Eric Laurent38ccae22011-03-28 18:37:07 -07003734 // do not reset the track if it is still in the process of being stopped or paused.
3735 // this will be done by prepareTracks_l() when the track is stopped.
3736 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3737 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3738 reset();
3739 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003740 }
3741}
3742
3743void AudioFlinger::PlaybackThread::Track::reset()
3744{
3745 // Do not reset twice to avoid discarding data written just after a flush and before
3746 // the audioflinger thread detects the track is stopped.
3747 if (!mResetDone) {
3748 TrackBase::reset();
3749 // Force underrun condition to avoid false underrun callback until first data is
3750 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003751 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3752 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003753 mFillingUpStatus = FS_FILLING;
3754 mResetDone = true;
3755 }
3756}
3757
3758void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3759{
3760 mMute = muted;
3761}
3762
Mathias Agopian65ab4712010-07-14 17:59:35 -07003763status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3764{
3765 status_t status = DEAD_OBJECT;
3766 sp<ThreadBase> thread = mThread.promote();
3767 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003768 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3769 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003770 }
3771 return status;
3772}
3773
3774void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3775{
3776 mAuxEffectId = EffectId;
3777 mAuxBuffer = buffer;
3778}
3779
John Grossman4ff14ba2012-02-08 16:37:41 -08003780// timed audio tracks
3781
3782sp<AudioFlinger::PlaybackThread::TimedTrack>
3783AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003784 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003785 const sp<Client>& client,
3786 audio_stream_type_t streamType,
3787 uint32_t sampleRate,
3788 audio_format_t format,
3789 uint32_t channelMask,
3790 int frameCount,
3791 const sp<IMemory>& sharedBuffer,
3792 int sessionId) {
3793 if (!client->reserveTimedTrack())
3794 return NULL;
3795
3796 sp<TimedTrack> track = new TimedTrack(
3797 thread, client, streamType, sampleRate, format, channelMask, frameCount,
3798 sharedBuffer, sessionId);
3799
3800 if (track == NULL) {
3801 client->releaseTimedTrack();
3802 return NULL;
3803 }
3804
3805 return track;
3806}
3807
3808AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003809 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003810 const sp<Client>& client,
3811 audio_stream_type_t streamType,
3812 uint32_t sampleRate,
3813 audio_format_t format,
3814 uint32_t channelMask,
3815 int frameCount,
3816 const sp<IMemory>& sharedBuffer,
3817 int sessionId)
3818 : Track(thread, client, streamType, sampleRate, format, channelMask,
3819 frameCount, sharedBuffer, sessionId),
3820 mTimedSilenceBuffer(NULL),
3821 mTimedSilenceBufferSize(0),
3822 mTimedAudioOutputOnTime(false),
3823 mMediaTimeTransformValid(false)
3824{
3825 LocalClock lc;
3826 mLocalTimeFreq = lc.getLocalFreq();
3827
3828 mLocalTimeToSampleTransform.a_zero = 0;
3829 mLocalTimeToSampleTransform.b_zero = 0;
3830 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3831 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3832 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3833 &mLocalTimeToSampleTransform.a_to_b_denom);
3834}
3835
3836AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3837 mClient->releaseTimedTrack();
3838 delete [] mTimedSilenceBuffer;
3839}
3840
3841status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3842 size_t size, sp<IMemory>* buffer) {
3843
3844 Mutex::Autolock _l(mTimedBufferQueueLock);
3845
3846 trimTimedBufferQueue_l();
3847
3848 // lazily initialize the shared memory heap for timed buffers
3849 if (mTimedMemoryDealer == NULL) {
3850 const int kTimedBufferHeapSize = 512 << 10;
3851
3852 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3853 "AudioFlingerTimed");
3854 if (mTimedMemoryDealer == NULL)
3855 return NO_MEMORY;
3856 }
3857
3858 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3859 if (newBuffer == NULL) {
3860 newBuffer = mTimedMemoryDealer->allocate(size);
3861 if (newBuffer == NULL)
3862 return NO_MEMORY;
3863 }
3864
3865 *buffer = newBuffer;
3866 return NO_ERROR;
3867}
3868
3869// caller must hold mTimedBufferQueueLock
3870void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
3871 int64_t mediaTimeNow;
3872 {
3873 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3874 if (!mMediaTimeTransformValid)
3875 return;
3876
3877 int64_t targetTimeNow;
3878 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
3879 ? mCCHelper.getCommonTime(&targetTimeNow)
3880 : mCCHelper.getLocalTime(&targetTimeNow);
3881
3882 if (OK != res)
3883 return;
3884
3885 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
3886 &mediaTimeNow)) {
3887 return;
3888 }
3889 }
3890
3891 size_t trimIndex;
3892 for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
3893 if (mTimedBufferQueue[trimIndex].pts() > mediaTimeNow)
3894 break;
3895 }
3896
3897 if (trimIndex) {
3898 mTimedBufferQueue.removeItemsAt(0, trimIndex);
3899 }
3900}
3901
3902status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
3903 const sp<IMemory>& buffer, int64_t pts) {
3904
3905 {
3906 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3907 if (!mMediaTimeTransformValid)
3908 return INVALID_OPERATION;
3909 }
3910
3911 Mutex::Autolock _l(mTimedBufferQueueLock);
3912
3913 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
3914
3915 return NO_ERROR;
3916}
3917
3918status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
3919 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
3920
3921 ALOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
3922 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
3923 target);
3924
3925 if (!(target == TimedAudioTrack::LOCAL_TIME ||
3926 target == TimedAudioTrack::COMMON_TIME)) {
3927 return BAD_VALUE;
3928 }
3929
3930 Mutex::Autolock lock(mMediaTimeTransformLock);
3931 mMediaTimeTransform = xform;
3932 mMediaTimeTransformTarget = target;
3933 mMediaTimeTransformValid = true;
3934
3935 return NO_ERROR;
3936}
3937
3938#define min(a, b) ((a) < (b) ? (a) : (b))
3939
3940// implementation of getNextBuffer for tracks whose buffers have timestamps
3941status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
3942 AudioBufferProvider::Buffer* buffer, int64_t pts)
3943{
3944 if (pts == AudioBufferProvider::kInvalidPTS) {
3945 buffer->raw = 0;
3946 buffer->frameCount = 0;
3947 return INVALID_OPERATION;
3948 }
3949
John Grossman4ff14ba2012-02-08 16:37:41 -08003950 Mutex::Autolock _l(mTimedBufferQueueLock);
3951
3952 while (true) {
3953
3954 // if we have no timed buffers, then fail
3955 if (mTimedBufferQueue.isEmpty()) {
3956 buffer->raw = 0;
3957 buffer->frameCount = 0;
3958 return NOT_ENOUGH_DATA;
3959 }
3960
3961 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
3962
3963 // calculate the PTS of the head of the timed buffer queue expressed in
3964 // local time
3965 int64_t headLocalPTS;
3966 {
3967 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3968
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003969 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08003970
3971 if (mMediaTimeTransform.a_to_b_denom == 0) {
3972 // the transform represents a pause, so yield silence
3973 timedYieldSilence(buffer->frameCount, buffer);
3974 return NO_ERROR;
3975 }
3976
3977 int64_t transformedPTS;
3978 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
3979 &transformedPTS)) {
3980 // the transform failed. this shouldn't happen, but if it does
3981 // then just drop this buffer
3982 ALOGW("timedGetNextBuffer transform failed");
3983 buffer->raw = 0;
3984 buffer->frameCount = 0;
3985 mTimedBufferQueue.removeAt(0);
3986 return NO_ERROR;
3987 }
3988
3989 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
3990 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
3991 &headLocalPTS)) {
3992 buffer->raw = 0;
3993 buffer->frameCount = 0;
3994 return INVALID_OPERATION;
3995 }
3996 } else {
3997 headLocalPTS = transformedPTS;
3998 }
3999 }
4000
4001 // adjust the head buffer's PTS to reflect the portion of the head buffer
4002 // that has already been consumed
4003 int64_t effectivePTS = headLocalPTS +
4004 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4005
4006 // Calculate the delta in samples between the head of the input buffer
4007 // queue and the start of the next output buffer that will be written.
4008 // If the transformation fails because of over or underflow, it means
4009 // that the sample's position in the output stream is so far out of
4010 // whack that it should just be dropped.
4011 int64_t sampleDelta;
4012 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4013 ALOGV("*** head buffer is too far from PTS: dropped buffer");
4014 mTimedBufferQueue.removeAt(0);
4015 continue;
4016 }
4017 if (!mLocalTimeToSampleTransform.doForwardTransform(
4018 (effectivePTS - pts) << 32, &sampleDelta)) {
4019 ALOGV("*** too late during sample rate transform: dropped buffer");
4020 mTimedBufferQueue.removeAt(0);
4021 continue;
4022 }
4023
4024 ALOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
4025 __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
4026 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
4027 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
4028
4029 // if the delta between the ideal placement for the next input sample and
4030 // the current output position is within this threshold, then we will
4031 // concatenate the next input samples to the previous output
4032 const int64_t kSampleContinuityThreshold =
4033 (static_cast<int64_t>(sampleRate()) << 32) / 10;
4034
4035 // if this is the first buffer of audio that we're emitting from this track
4036 // then it should be almost exactly on time.
4037 const int64_t kSampleStartupThreshold = 1LL << 32;
4038
4039 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
4040 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
4041 // the next input is close enough to being on time, so concatenate it
4042 // with the last output
4043 timedYieldSamples(buffer);
4044
4045 ALOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4046 return NO_ERROR;
4047 } else if (sampleDelta > 0) {
4048 // the gap between the current output position and the proper start of
4049 // the next input sample is too big, so fill it with silence
4050 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4051
4052 timedYieldSilence(framesUntilNextInput, buffer);
4053 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4054 return NO_ERROR;
4055 } else {
4056 // the next input sample is late
4057 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4058 size_t onTimeSamplePosition =
4059 head.position() + lateFrames * mCblk->frameSize;
4060
4061 if (onTimeSamplePosition > head.buffer()->size()) {
4062 // all the remaining samples in the head are too late, so
4063 // drop it and move on
4064 ALOGV("*** too late: dropped buffer");
4065 mTimedBufferQueue.removeAt(0);
4066 continue;
4067 } else {
4068 // skip over the late samples
4069 head.setPosition(onTimeSamplePosition);
4070
4071 // yield the available samples
4072 timedYieldSamples(buffer);
4073
4074 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4075 return NO_ERROR;
4076 }
4077 }
4078 }
4079}
4080
4081// Yield samples from the timed buffer queue head up to the given output
4082// buffer's capacity.
4083//
4084// Caller must hold mTimedBufferQueueLock
4085void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples(
4086 AudioBufferProvider::Buffer* buffer) {
4087
4088 const TimedBuffer& head = mTimedBufferQueue[0];
4089
4090 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4091 head.position());
4092
4093 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4094 mCblk->frameSize);
4095 size_t framesRequested = buffer->frameCount;
4096 buffer->frameCount = min(framesLeftInHead, framesRequested);
4097
4098 mTimedAudioOutputOnTime = true;
4099}
4100
4101// Yield samples of silence up to the given output buffer's capacity
4102//
4103// Caller must hold mTimedBufferQueueLock
4104void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence(
4105 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4106
4107 // lazily allocate a buffer filled with silence
4108 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4109 delete [] mTimedSilenceBuffer;
4110 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4111 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4112 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4113 }
4114
4115 buffer->raw = mTimedSilenceBuffer;
4116 size_t framesRequested = buffer->frameCount;
4117 buffer->frameCount = min(numFrames, framesRequested);
4118
4119 mTimedAudioOutputOnTime = false;
4120}
4121
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004122// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004123void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4124 AudioBufferProvider::Buffer* buffer) {
4125
4126 Mutex::Autolock _l(mTimedBufferQueueLock);
4127
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004128 // If the buffer which was just released is part of the buffer at the head
4129 // of the queue, be sure to update the amt of the buffer which has been
4130 // consumed. If the buffer being returned is not part of the head of the
4131 // queue, its either because the buffer is part of the silence buffer, or
4132 // because the head of the timed queue was trimmed after the mixer called
4133 // getNextBuffer but before the mixer called releaseBuffer.
4134 if ((buffer->raw != mTimedSilenceBuffer) && mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004135 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004136
4137 void* start = head.buffer()->pointer();
Glenn Kastenf063b492012-02-17 16:24:10 -08004138 void* end = (char *) head.buffer()->pointer() + head.buffer()->size();
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004139
4140 if ((buffer->raw >= start) && (buffer->raw <= end)) {
4141 head.setPosition(head.position() +
4142 (buffer->frameCount * mCblk->frameSize));
4143 if (static_cast<size_t>(head.position()) >= head.buffer()->size()) {
4144 mTimedBufferQueue.removeAt(0);
4145 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004146 }
4147 }
4148
4149 buffer->raw = 0;
4150 buffer->frameCount = 0;
4151}
4152
4153uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4154 Mutex::Autolock _l(mTimedBufferQueueLock);
4155
4156 uint32_t frames = 0;
4157 for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4158 const TimedBuffer& tb = mTimedBufferQueue[i];
4159 frames += (tb.buffer()->size() - tb.position()) / mCblk->frameSize;
4160 }
4161
4162 return frames;
4163}
4164
4165AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4166 : mPTS(0), mPosition(0) {}
4167
4168AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4169 const sp<IMemory>& buffer, int64_t pts)
4170 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4171
Mathias Agopian65ab4712010-07-14 17:59:35 -07004172// ----------------------------------------------------------------------------
4173
4174// RecordTrack constructor must be called with AudioFlinger::mLock held
4175AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004176 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004177 const sp<Client>& client,
4178 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004179 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004180 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004181 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004182 int sessionId)
4183 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004184 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004185 mOverflow(false)
4186{
4187 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004188 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
4189 if (format == AUDIO_FORMAT_PCM_16_BIT) {
4190 mCblk->frameSize = mChannelCount * sizeof(int16_t);
4191 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
4192 mCblk->frameSize = mChannelCount * sizeof(int8_t);
4193 } else {
4194 mCblk->frameSize = sizeof(int8_t);
4195 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004196 }
4197}
4198
4199AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4200{
4201 sp<ThreadBase> thread = mThread.promote();
4202 if (thread != 0) {
4203 AudioSystem::releaseInput(thread->id());
4204 }
4205}
4206
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004207// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004208status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004209{
4210 audio_track_cblk_t* cblk = this->cblk();
4211 uint32_t framesAvail;
4212 uint32_t framesReq = buffer->frameCount;
4213
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004214 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004215 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004216 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004217 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004218 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004219 }
4220
4221 framesAvail = cblk->framesAvailable_l();
4222
Glenn Kastenf6b16782011-12-15 09:51:17 -08004223 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004224 uint32_t s = cblk->server;
4225 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4226
4227 if (framesReq > framesAvail) {
4228 framesReq = framesAvail;
4229 }
4230 if (s + framesReq > bufferEnd) {
4231 framesReq = bufferEnd - s;
4232 }
4233
4234 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004235 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004236
4237 buffer->frameCount = framesReq;
4238 return NO_ERROR;
4239 }
4240
4241getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004242 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004243 buffer->frameCount = 0;
4244 return NOT_ENOUGH_DATA;
4245}
4246
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004247status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004248{
4249 sp<ThreadBase> thread = mThread.promote();
4250 if (thread != 0) {
4251 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004252 return recordThread->start(this, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004253 } else {
4254 return BAD_VALUE;
4255 }
4256}
4257
4258void AudioFlinger::RecordThread::RecordTrack::stop()
4259{
4260 sp<ThreadBase> thread = mThread.promote();
4261 if (thread != 0) {
4262 RecordThread *recordThread = (RecordThread *)thread.get();
4263 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004264 TrackBase::reset();
4265 // Force overerrun condition to avoid false overrun callback until first data is
4266 // read from buffer
4267 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004268 }
4269}
4270
4271void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4272{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004273 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004274 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004275 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004276 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004277 mSessionId,
4278 mFrameCount,
4279 mState,
4280 mCblk->sampleRate,
4281 mCblk->server,
4282 mCblk->user);
4283}
4284
4285
4286// ----------------------------------------------------------------------------
4287
4288AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004289 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004290 DuplicatingThread *sourceThread,
4291 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004292 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004293 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004294 int frameCount)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004295 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004296 mActive(false), mSourceThread(sourceThread)
4297{
4298
Mathias Agopian65ab4712010-07-14 17:59:35 -07004299 if (mCblk != NULL) {
4300 mCblk->flags |= CBLK_DIRECTION_OUT;
4301 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004302 mOutBuffer.frameCount = 0;
4303 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01004304 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004305 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4306 mCblk, mBuffer, mCblk->buffers,
4307 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004308 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004309 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004310 }
4311}
4312
4313AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4314{
4315 clearBufferQueue();
4316}
4317
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004318status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004319{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004320 status_t status = Track::start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004321 if (status != NO_ERROR) {
4322 return status;
4323 }
4324
4325 mActive = true;
4326 mRetryCount = 127;
4327 return status;
4328}
4329
4330void AudioFlinger::PlaybackThread::OutputTrack::stop()
4331{
4332 Track::stop();
4333 clearBufferQueue();
4334 mOutBuffer.frameCount = 0;
4335 mActive = false;
4336}
4337
4338bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4339{
4340 Buffer *pInBuffer;
4341 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004342 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004343 bool outputBufferFull = false;
4344 inBuffer.frameCount = frames;
4345 inBuffer.i16 = data;
4346
4347 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4348
4349 if (!mActive && frames != 0) {
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004350 start(0);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004351 sp<ThreadBase> thread = mThread.promote();
4352 if (thread != 0) {
4353 MixerThread *mixerThread = (MixerThread *)thread.get();
4354 if (mCblk->frameCount > frames){
4355 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4356 uint32_t startFrames = (mCblk->frameCount - frames);
4357 pInBuffer = new Buffer;
4358 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4359 pInBuffer->frameCount = startFrames;
4360 pInBuffer->i16 = pInBuffer->mBuffer;
4361 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4362 mBufferQueue.add(pInBuffer);
4363 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004364 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004365 }
4366 }
4367 }
4368 }
4369
4370 while (waitTimeLeftMs) {
4371 // First write pending buffers, then new data
4372 if (mBufferQueue.size()) {
4373 pInBuffer = mBufferQueue.itemAt(0);
4374 } else {
4375 pInBuffer = &inBuffer;
4376 }
4377
4378 if (pInBuffer->frameCount == 0) {
4379 break;
4380 }
4381
4382 if (mOutBuffer.frameCount == 0) {
4383 mOutBuffer.frameCount = pInBuffer->frameCount;
4384 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08004385 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01004386 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004387 outputBufferFull = true;
4388 break;
4389 }
4390 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4391 if (waitTimeLeftMs >= waitTimeMs) {
4392 waitTimeLeftMs -= waitTimeMs;
4393 } else {
4394 waitTimeLeftMs = 0;
4395 }
4396 }
4397
4398 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4399 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4400 mCblk->stepUser(outFrames);
4401 pInBuffer->frameCount -= outFrames;
4402 pInBuffer->i16 += outFrames * channelCount;
4403 mOutBuffer.frameCount -= outFrames;
4404 mOutBuffer.i16 += outFrames * channelCount;
4405
4406 if (pInBuffer->frameCount == 0) {
4407 if (mBufferQueue.size()) {
4408 mBufferQueue.removeAt(0);
4409 delete [] pInBuffer->mBuffer;
4410 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01004411 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004412 } else {
4413 break;
4414 }
4415 }
4416 }
4417
4418 // If we could not write all frames, allocate a buffer and queue it for next time.
4419 if (inBuffer.frameCount) {
4420 sp<ThreadBase> thread = mThread.promote();
4421 if (thread != 0 && !thread->standby()) {
4422 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4423 pInBuffer = new Buffer;
4424 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4425 pInBuffer->frameCount = inBuffer.frameCount;
4426 pInBuffer->i16 = pInBuffer->mBuffer;
4427 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4428 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01004429 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004430 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004431 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004432 }
4433 }
4434 }
4435
4436 // Calling write() with a 0 length buffer, means that no more data will be written:
4437 // If no more buffers are pending, fill output track buffer to make sure it is started
4438 // by output mixer.
4439 if (frames == 0 && mBufferQueue.size() == 0) {
4440 if (mCblk->user < mCblk->frameCount) {
4441 frames = mCblk->frameCount - mCblk->user;
4442 pInBuffer = new Buffer;
4443 pInBuffer->mBuffer = new int16_t[frames * channelCount];
4444 pInBuffer->frameCount = frames;
4445 pInBuffer->i16 = pInBuffer->mBuffer;
4446 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4447 mBufferQueue.add(pInBuffer);
4448 } else if (mActive) {
4449 stop();
4450 }
4451 }
4452
4453 return outputBufferFull;
4454}
4455
4456status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4457{
4458 int active;
4459 status_t result;
4460 audio_track_cblk_t* cblk = mCblk;
4461 uint32_t framesReq = buffer->frameCount;
4462
Steve Block3856b092011-10-20 11:56:00 +01004463// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004464 buffer->frameCount = 0;
4465
4466 uint32_t framesAvail = cblk->framesAvailable();
4467
4468
4469 if (framesAvail == 0) {
4470 Mutex::Autolock _l(cblk->lock);
4471 goto start_loop_here;
4472 while (framesAvail == 0) {
4473 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004474 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004475 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004476 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004477 }
4478 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4479 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004480 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004481 }
4482 // read the server count again
4483 start_loop_here:
4484 framesAvail = cblk->framesAvailable_l();
4485 }
4486 }
4487
4488// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004489// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004490// }
4491
4492 if (framesReq > framesAvail) {
4493 framesReq = framesAvail;
4494 }
4495
4496 uint32_t u = cblk->user;
4497 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4498
4499 if (u + framesReq > bufferEnd) {
4500 framesReq = bufferEnd - u;
4501 }
4502
4503 buffer->frameCount = framesReq;
4504 buffer->raw = (void *)cblk->buffer(u);
4505 return NO_ERROR;
4506}
4507
4508
4509void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4510{
4511 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004512
4513 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004514 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004515 delete [] pBuffer->mBuffer;
4516 delete pBuffer;
4517 }
4518 mBufferQueue.clear();
4519}
4520
4521// ----------------------------------------------------------------------------
4522
4523AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4524 : RefBase(),
4525 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08004526 // 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 -07004527 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08004528 mPid(pid),
4529 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004530{
4531 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4532}
4533
4534// Client destructor must be called with AudioFlinger::mLock held
4535AudioFlinger::Client::~Client()
4536{
4537 mAudioFlinger->removeClient_l(mPid);
4538}
4539
Glenn Kasten435dbe62012-01-30 10:15:48 -08004540sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004541{
4542 return mMemoryDealer;
4543}
4544
John Grossman4ff14ba2012-02-08 16:37:41 -08004545// Reserve one of the limited slots for a timed audio track associated
4546// with this client
4547bool AudioFlinger::Client::reserveTimedTrack()
4548{
4549 const int kMaxTimedTracksPerClient = 4;
4550
4551 Mutex::Autolock _l(mTimedTrackLock);
4552
4553 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4554 ALOGW("can not create timed track - pid %d has exceeded the limit",
4555 mPid);
4556 return false;
4557 }
4558
4559 mTimedTrackCount++;
4560 return true;
4561}
4562
4563// Release a slot for a timed audio track
4564void AudioFlinger::Client::releaseTimedTrack()
4565{
4566 Mutex::Autolock _l(mTimedTrackLock);
4567 mTimedTrackCount--;
4568}
4569
Mathias Agopian65ab4712010-07-14 17:59:35 -07004570// ----------------------------------------------------------------------------
4571
4572AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4573 const sp<IAudioFlingerClient>& client,
4574 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004575 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004576{
4577}
4578
4579AudioFlinger::NotificationClient::~NotificationClient()
4580{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004581}
4582
4583void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4584{
4585 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08004586 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004587}
4588
4589// ----------------------------------------------------------------------------
4590
4591AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4592 : BnAudioTrack(),
4593 mTrack(track)
4594{
4595}
4596
4597AudioFlinger::TrackHandle::~TrackHandle() {
4598 // just stop the track on deletion, associated resources
4599 // will be freed from the main thread once all pending buffers have
4600 // been played. Unless it's not in the active track list, in which
4601 // case we free everything now...
4602 mTrack->destroy();
4603}
4604
Glenn Kasten90716c52012-01-26 13:40:12 -08004605sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4606 return mTrack->getCblk();
4607}
4608
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004609status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4610 return mTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004611}
4612
4613void AudioFlinger::TrackHandle::stop() {
4614 mTrack->stop();
4615}
4616
4617void AudioFlinger::TrackHandle::flush() {
4618 mTrack->flush();
4619}
4620
4621void AudioFlinger::TrackHandle::mute(bool e) {
4622 mTrack->mute(e);
4623}
4624
4625void AudioFlinger::TrackHandle::pause() {
4626 mTrack->pause();
4627}
4628
Mathias Agopian65ab4712010-07-14 17:59:35 -07004629status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4630{
4631 return mTrack->attachAuxEffect(EffectId);
4632}
4633
John Grossman4ff14ba2012-02-08 16:37:41 -08004634status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4635 sp<IMemory>* buffer) {
4636 if (!mTrack->isTimedTrack())
4637 return INVALID_OPERATION;
4638
4639 PlaybackThread::TimedTrack* tt =
4640 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4641 return tt->allocateTimedBuffer(size, buffer);
4642}
4643
4644status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4645 int64_t pts) {
4646 if (!mTrack->isTimedTrack())
4647 return INVALID_OPERATION;
4648
4649 PlaybackThread::TimedTrack* tt =
4650 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4651 return tt->queueTimedBuffer(buffer, pts);
4652}
4653
4654status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4655 const LinearTransform& xform, int target) {
4656
4657 if (!mTrack->isTimedTrack())
4658 return INVALID_OPERATION;
4659
4660 PlaybackThread::TimedTrack* tt =
4661 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4662 return tt->setMediaTimeTransform(
4663 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4664}
4665
Mathias Agopian65ab4712010-07-14 17:59:35 -07004666status_t AudioFlinger::TrackHandle::onTransact(
4667 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4668{
4669 return BnAudioTrack::onTransact(code, data, reply, flags);
4670}
4671
4672// ----------------------------------------------------------------------------
4673
4674sp<IAudioRecord> AudioFlinger::openRecord(
4675 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004676 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004677 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004678 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004679 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004680 int frameCount,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004681 // FIXME dead, remove from IAudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -07004682 uint32_t flags,
4683 int *sessionId,
4684 status_t *status)
4685{
4686 sp<RecordThread::RecordTrack> recordTrack;
4687 sp<RecordHandle> recordHandle;
4688 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004689 status_t lStatus;
4690 RecordThread *thread;
4691 size_t inFrameCount;
4692 int lSessionId;
4693
4694 // check calling permissions
4695 if (!recordingAllowed()) {
4696 lStatus = PERMISSION_DENIED;
4697 goto Exit;
4698 }
4699
4700 // add client to list
4701 { // scope for mLock
4702 Mutex::Autolock _l(mLock);
4703 thread = checkRecordThread_l(input);
4704 if (thread == NULL) {
4705 lStatus = BAD_VALUE;
4706 goto Exit;
4707 }
4708
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004709 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004710
4711 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004712 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004713 lSessionId = *sessionId;
4714 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004715 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004716 if (sessionId != NULL) {
4717 *sessionId = lSessionId;
4718 }
4719 }
4720 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004721 recordTrack = thread->createRecordTrack_l(client,
4722 sampleRate,
4723 format,
4724 channelMask,
4725 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004726 lSessionId,
4727 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004728 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004729 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004730 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4731 // destructor is called by the TrackBase destructor with mLock held
4732 client.clear();
4733 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004734 goto Exit;
4735 }
4736
4737 // return to handle to client
4738 recordHandle = new RecordHandle(recordTrack);
4739 lStatus = NO_ERROR;
4740
4741Exit:
4742 if (status) {
4743 *status = lStatus;
4744 }
4745 return recordHandle;
4746}
4747
4748// ----------------------------------------------------------------------------
4749
4750AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4751 : BnAudioRecord(),
4752 mRecordTrack(recordTrack)
4753{
4754}
4755
4756AudioFlinger::RecordHandle::~RecordHandle() {
4757 stop();
4758}
4759
Glenn Kasten90716c52012-01-26 13:40:12 -08004760sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4761 return mRecordTrack->getCblk();
4762}
4763
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004764status_t AudioFlinger::RecordHandle::start(pid_t tid) {
Steve Block3856b092011-10-20 11:56:00 +01004765 ALOGV("RecordHandle::start()");
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004766 return mRecordTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004767}
4768
4769void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004770 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004771 mRecordTrack->stop();
4772}
4773
Mathias Agopian65ab4712010-07-14 17:59:35 -07004774status_t AudioFlinger::RecordHandle::onTransact(
4775 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4776{
4777 return BnAudioRecord::onTransact(code, data, reply, flags);
4778}
4779
4780// ----------------------------------------------------------------------------
4781
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004782AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4783 AudioStreamIn *input,
4784 uint32_t sampleRate,
4785 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004786 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004787 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004788 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004789 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4790 // mRsmpInIndex and mInputBytes set by readInputParameters()
4791 mReqChannelCount(popcount(channels)),
4792 mReqSampleRate(sampleRate)
4793 // mBytesRead is only meaningful while active, and so is cleared in start()
4794 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004795{
Glenn Kasten480b4682012-02-28 12:30:08 -08004796 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07004797
Mathias Agopian65ab4712010-07-14 17:59:35 -07004798 readInputParameters();
4799}
4800
4801
4802AudioFlinger::RecordThread::~RecordThread()
4803{
4804 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004805 delete mResampler;
4806 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004807}
4808
4809void AudioFlinger::RecordThread::onFirstRef()
4810{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004811 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004812}
4813
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004814status_t AudioFlinger::RecordThread::readyToRun()
4815{
4816 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004817 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004818 return status;
4819}
4820
Mathias Agopian65ab4712010-07-14 17:59:35 -07004821bool AudioFlinger::RecordThread::threadLoop()
4822{
4823 AudioBufferProvider::Buffer buffer;
4824 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004825 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004826
Eric Laurent44d98482010-09-30 16:12:31 -07004827 nsecs_t lastWarning = 0;
4828
Eric Laurentfeb0db62011-07-22 09:04:31 -07004829 acquireWakeLock();
4830
Mathias Agopian65ab4712010-07-14 17:59:35 -07004831 // start recording
4832 while (!exitPending()) {
4833
4834 processConfigEvents();
4835
4836 { // scope for mLock
4837 Mutex::Autolock _l(mLock);
4838 checkForNewParameters_l();
4839 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4840 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004841 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004842 mStandby = true;
4843 }
4844
4845 if (exitPending()) break;
4846
Eric Laurentfeb0db62011-07-22 09:04:31 -07004847 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004848 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004849 // go to sleep
4850 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004851 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004852 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004853 continue;
4854 }
4855 if (mActiveTrack != 0) {
4856 if (mActiveTrack->mState == TrackBase::PAUSING) {
4857 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004858 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004859 mStandby = true;
4860 }
4861 mActiveTrack.clear();
4862 mStartStopCond.broadcast();
4863 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4864 if (mReqChannelCount != mActiveTrack->channelCount()) {
4865 mActiveTrack.clear();
4866 mStartStopCond.broadcast();
4867 } else if (mBytesRead != 0) {
4868 // record start succeeds only if first read from audio input
4869 // succeeds
4870 if (mBytesRead > 0) {
4871 mActiveTrack->mState = TrackBase::ACTIVE;
4872 } else {
4873 mActiveTrack.clear();
4874 }
4875 mStartStopCond.broadcast();
4876 }
4877 mStandby = false;
4878 }
4879 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004880 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004881 }
4882
4883 if (mActiveTrack != 0) {
4884 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4885 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004886 unlockEffectChains(effectChains);
4887 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004888 continue;
4889 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004890 for (size_t i = 0; i < effectChains.size(); i ++) {
4891 effectChains[i]->process_l();
4892 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004893
Mathias Agopian65ab4712010-07-14 17:59:35 -07004894 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004895 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004896 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004897 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004898 // no resampling
4899 while (framesOut) {
4900 size_t framesIn = mFrameCount - mRsmpInIndex;
4901 if (framesIn) {
4902 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4903 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4904 if (framesIn > framesOut)
4905 framesIn = framesOut;
4906 mRsmpInIndex += framesIn;
4907 framesOut -= framesIn;
4908 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004909 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004910 memcpy(dst, src, framesIn * mFrameSize);
4911 } else {
4912 int16_t *src16 = (int16_t *)src;
4913 int16_t *dst16 = (int16_t *)dst;
4914 if (mChannelCount == 1) {
4915 while (framesIn--) {
4916 *dst16++ = *src16;
4917 *dst16++ = *src16++;
4918 }
4919 } else {
4920 while (framesIn--) {
4921 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4922 src16 += 2;
4923 }
4924 }
4925 }
4926 }
4927 if (framesOut && mFrameCount == mRsmpInIndex) {
4928 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004929 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004930 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004931 framesOut = 0;
4932 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004933 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004934 mRsmpInIndex = 0;
4935 }
4936 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004937 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004938 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4939 // Force input into standby so that it tries to
4940 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004941 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004942 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004943 }
4944 mRsmpInIndex = mFrameCount;
4945 framesOut = 0;
4946 buffer.frameCount = 0;
4947 }
4948 }
4949 }
4950 } else {
4951 // resampling
4952
4953 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4954 // alter output frame count as if we were expecting stereo samples
4955 if (mChannelCount == 1 && mReqChannelCount == 1) {
4956 framesOut >>= 1;
4957 }
4958 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4959 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4960 // are 32 bit aligned which should be always true.
4961 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004962 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004963 // the resampler always outputs stereo samples: do post stereo to mono conversion
4964 int16_t *src = (int16_t *)mRsmpOutBuffer;
4965 int16_t *dst = buffer.i16;
4966 while (framesOut--) {
4967 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4968 src += 2;
4969 }
4970 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004971 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004972 }
4973
4974 }
4975 mActiveTrack->releaseBuffer(&buffer);
4976 mActiveTrack->overflow();
4977 }
4978 // client isn't retrieving buffers fast enough
4979 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004980 if (!mActiveTrack->setOverflow()) {
4981 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004982 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004983 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004984 lastWarning = now;
4985 }
4986 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004987 // Release the processor for a while before asking for a new buffer.
4988 // This will give the application more chance to read from the buffer and
4989 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004990 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004991 }
4992 }
Eric Laurentec437d82011-07-26 20:54:46 -07004993 // enable changes in effect chain
4994 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004995 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004996 }
4997
4998 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004999 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005000 }
5001 mActiveTrack.clear();
5002
5003 mStartStopCond.broadcast();
5004
Eric Laurentfeb0db62011-07-22 09:04:31 -07005005 releaseWakeLock();
5006
Steve Block3856b092011-10-20 11:56:00 +01005007 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005008 return false;
5009}
5010
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005011
5012sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5013 const sp<AudioFlinger::Client>& client,
5014 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005015 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005016 int channelMask,
5017 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005018 int sessionId,
5019 status_t *status)
5020{
5021 sp<RecordTrack> track;
5022 status_t lStatus;
5023
5024 lStatus = initCheck();
5025 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005026 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005027 goto Exit;
5028 }
5029
5030 { // scope for mLock
5031 Mutex::Autolock _l(mLock);
5032
5033 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005034 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005035
Glenn Kasten7378ca52012-01-20 13:44:40 -08005036 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005037 lStatus = NO_MEMORY;
5038 goto Exit;
5039 }
5040
5041 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005042 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5043 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005044 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005045 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5046 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005047 }
5048 lStatus = NO_ERROR;
5049
5050Exit:
5051 if (status) {
5052 *status = lStatus;
5053 }
5054 return track;
5055}
5056
Glenn Kasten6dbc1352012-02-02 10:56:47 -08005057status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005058{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08005059 ALOGV("RecordThread::start tid=%d", tid);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005060 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005061 status_t status = NO_ERROR;
5062 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005063 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005064 if (mActiveTrack != 0) {
5065 if (recordTrack != mActiveTrack.get()) {
5066 status = -EBUSY;
5067 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5068 mActiveTrack->mState = TrackBase::ACTIVE;
5069 }
5070 return status;
5071 }
5072
5073 recordTrack->mState = TrackBase::IDLE;
5074 mActiveTrack = recordTrack;
5075 mLock.unlock();
5076 status_t status = AudioSystem::startInput(mId);
5077 mLock.lock();
5078 if (status != NO_ERROR) {
5079 mActiveTrack.clear();
5080 return status;
5081 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005082 mRsmpInIndex = mFrameCount;
5083 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005084 if (mResampler != NULL) {
5085 mResampler->reset();
5086 }
5087 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005088 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005089 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005090 mWaitWorkCV.signal();
5091 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005092 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005093 mActiveTrack.clear();
5094 status = INVALID_OPERATION;
5095 goto startError;
5096 }
5097 mStartStopCond.wait(mLock);
5098 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005099 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005100 status = BAD_VALUE;
5101 goto startError;
5102 }
Steve Block3856b092011-10-20 11:56:00 +01005103 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005104 return status;
5105 }
5106startError:
5107 AudioSystem::stopInput(mId);
5108 return status;
5109}
5110
5111void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005112 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005113 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005114 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005115 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005116 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5117 mActiveTrack->mState = TrackBase::PAUSING;
5118 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005119 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005120 return;
5121 }
5122 mStartStopCond.wait(mLock);
5123 // if we have been restarted, recordTrack == mActiveTrack.get() here
5124 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5125 mLock.unlock();
5126 AudioSystem::stopInput(mId);
5127 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005128 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005129 }
5130 }
5131 }
5132}
5133
5134status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5135{
5136 const size_t SIZE = 256;
5137 char buffer[SIZE];
5138 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005139
5140 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5141 result.append(buffer);
5142
5143 if (mActiveTrack != 0) {
5144 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005145 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005146 mActiveTrack->dump(buffer, SIZE);
5147 result.append(buffer);
5148
5149 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5150 result.append(buffer);
5151 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5152 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005153 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005154 result.append(buffer);
5155 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5156 result.append(buffer);
5157 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5158 result.append(buffer);
5159
5160
5161 } else {
5162 result.append("No record client\n");
5163 }
5164 write(fd, result.string(), result.size());
5165
5166 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005167 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005168
5169 return NO_ERROR;
5170}
5171
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005172// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005173status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005174{
5175 size_t framesReq = buffer->frameCount;
5176 size_t framesReady = mFrameCount - mRsmpInIndex;
5177 int channelCount;
5178
5179 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005180 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005181 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005182 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005183 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5184 // Force input into standby so that it tries to
5185 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005186 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005187 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005188 }
Glenn Kastene0feee32011-12-13 11:53:26 -08005189 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005190 buffer->frameCount = 0;
5191 return NOT_ENOUGH_DATA;
5192 }
5193 mRsmpInIndex = 0;
5194 framesReady = mFrameCount;
5195 }
5196
5197 if (framesReq > framesReady) {
5198 framesReq = framesReady;
5199 }
5200
5201 if (mChannelCount == 1 && mReqChannelCount == 2) {
5202 channelCount = 1;
5203 } else {
5204 channelCount = 2;
5205 }
5206 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5207 buffer->frameCount = framesReq;
5208 return NO_ERROR;
5209}
5210
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005211// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07005212void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5213{
5214 mRsmpInIndex += buffer->frameCount;
5215 buffer->frameCount = 0;
5216}
5217
5218bool AudioFlinger::RecordThread::checkForNewParameters_l()
5219{
5220 bool reconfig = false;
5221
5222 while (!mNewParameters.isEmpty()) {
5223 status_t status = NO_ERROR;
5224 String8 keyValuePair = mNewParameters[0];
5225 AudioParameter param = AudioParameter(keyValuePair);
5226 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08005227 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005228 int reqSamplingRate = mReqSampleRate;
5229 int reqChannelCount = mReqChannelCount;
5230
5231 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5232 reqSamplingRate = value;
5233 reconfig = true;
5234 }
5235 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08005236 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005237 reconfig = true;
5238 }
5239 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005240 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005241 reconfig = true;
5242 }
5243 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5244 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08005245 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005246 // if frame count is changed after track creation
5247 if (mActiveTrack != 0) {
5248 status = INVALID_OPERATION;
5249 } else {
5250 reconfig = true;
5251 }
5252 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005253 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5254 // forward device change to effects that have requested to be
5255 // aware of attached audio device.
5256 for (size_t i = 0; i < mEffectChains.size(); i++) {
5257 mEffectChains[i]->setDevice_l(value);
5258 }
5259 // store input device and output device but do not forward output device to audio HAL.
5260 // Note that status is ignored by the caller for output device
5261 // (see AudioFlinger::setParameters()
5262 if (value & AUDIO_DEVICE_OUT_ALL) {
5263 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5264 status = BAD_VALUE;
5265 } else {
5266 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07005267 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5268 if (mTrack != NULL) {
5269 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005270 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005271 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5272 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5273 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005274 }
5275 mDevice |= (uint32_t)value;
5276 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005277 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005278 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005279 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005280 mInput->stream->common.standby(&mInput->stream->common);
5281 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5282 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005283 }
5284 if (reconfig) {
5285 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005286 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005287 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005288 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08005289 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
5290 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005291 status = NO_ERROR;
5292 }
5293 if (status == NO_ERROR) {
5294 readInputParameters();
5295 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5296 }
5297 }
5298 }
5299
5300 mNewParameters.removeAt(0);
5301
5302 mParamStatus = status;
5303 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07005304 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5305 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08005306 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005307 }
5308 return reconfig;
5309}
5310
5311String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5312{
Dima Zavinfce7a472011-04-19 22:30:36 -07005313 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005314 String8 out_s8 = String8();
5315
5316 Mutex::Autolock _l(mLock);
5317 if (initCheck() != NO_ERROR) {
5318 return out_s8;
5319 }
Dima Zavinfce7a472011-04-19 22:30:36 -07005320
Dima Zavin799a70e2011-04-18 16:57:27 -07005321 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07005322 out_s8 = String8(s);
5323 free(s);
5324 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005325}
5326
5327void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5328 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08005329 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005330
5331 switch (event) {
5332 case AudioSystem::INPUT_OPENED:
5333 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005334 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005335 desc.samplingRate = mSampleRate;
5336 desc.format = mFormat;
5337 desc.frameCount = mFrameCount;
5338 desc.latency = 0;
5339 param2 = &desc;
5340 break;
5341
5342 case AudioSystem::INPUT_CLOSED:
5343 default:
5344 break;
5345 }
5346 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5347}
5348
5349void AudioFlinger::RecordThread::readInputParameters()
5350{
Glenn Kastene9dd0172012-01-27 18:08:45 -08005351 delete mRsmpInBuffer;
5352 // mRsmpInBuffer is always assigned a new[] below
5353 delete mRsmpOutBuffer;
5354 mRsmpOutBuffer = NULL;
5355 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08005356 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005357
Dima Zavin799a70e2011-04-18 16:57:27 -07005358 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005359 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5360 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07005361 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08005362 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07005363 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005364 mFrameCount = mInputBytes / mFrameSize;
5365 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5366
Glenn Kasten53d76db2012-03-08 12:32:47 -08005367 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005368 {
5369 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005370 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5371 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005372 if (mChannelCount == 1 && mReqChannelCount == 2) {
5373 channelCount = 1;
5374 } else {
5375 channelCount = 2;
5376 }
5377 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5378 mResampler->setSampleRate(mSampleRate);
5379 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5380 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5381
5382 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5383 if (mChannelCount == 1 && mReqChannelCount == 1) {
5384 mFrameCount >>= 1;
5385 }
5386
5387 }
5388 mRsmpInIndex = mFrameCount;
5389}
5390
5391unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5392{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005393 Mutex::Autolock _l(mLock);
5394 if (initCheck() != NO_ERROR) {
5395 return 0;
5396 }
5397
Dima Zavin799a70e2011-04-18 16:57:27 -07005398 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005399}
5400
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005401uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5402{
5403 Mutex::Autolock _l(mLock);
5404 uint32_t result = 0;
5405 if (getEffectChain_l(sessionId) != 0) {
5406 result = EFFECT_SESSION;
5407 }
5408
5409 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5410 result |= TRACK_SESSION;
5411 }
5412
5413 return result;
5414}
5415
Eric Laurent59bd0da2011-08-01 09:52:20 -07005416AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5417{
5418 Mutex::Autolock _l(mLock);
5419 return mTrack;
5420}
5421
Glenn Kastenaed850d2012-01-26 09:46:34 -08005422AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005423{
5424 Mutex::Autolock _l(mLock);
5425 return mInput;
5426}
5427
5428AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5429{
5430 Mutex::Autolock _l(mLock);
5431 AudioStreamIn *input = mInput;
5432 mInput = NULL;
5433 return input;
5434}
5435
5436// this method must always be called either with ThreadBase mLock held or inside the thread loop
5437audio_stream_t* AudioFlinger::RecordThread::stream()
5438{
5439 if (mInput == NULL) {
5440 return NULL;
5441 }
5442 return &mInput->stream->common;
5443}
5444
5445
Mathias Agopian65ab4712010-07-14 17:59:35 -07005446// ----------------------------------------------------------------------------
5447
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005448audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005449 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005450 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005451 uint32_t *pChannels,
5452 uint32_t *pLatencyMs,
Glenn Kasten18868c52012-03-07 09:15:37 -08005453 audio_policy_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005454{
5455 status_t status;
5456 PlaybackThread *thread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005457 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005458 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005459 uint32_t channels = pChannels ? *pChannels : 0;
5460 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07005461 audio_stream_out_t *outStream;
5462 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005463
Steve Block3856b092011-10-20 11:56:00 +01005464 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07005465 pDevices ? *pDevices : 0,
5466 samplingRate,
5467 format,
5468 channels,
5469 flags);
5470
5471 if (pDevices == NULL || *pDevices == 0) {
5472 return 0;
5473 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005474
Mathias Agopian65ab4712010-07-14 17:59:35 -07005475 Mutex::Autolock _l(mLock);
5476
Dima Zavin799a70e2011-04-18 16:57:27 -07005477 outHwDev = findSuitableHwDev_l(*pDevices);
5478 if (outHwDev == NULL)
5479 return 0;
5480
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005481 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Glenn Kasten58f30212012-01-12 12:27:51 -08005482 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005483 &channels, &samplingRate, &outStream);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005484 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01005485 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005486 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005487 samplingRate,
5488 format,
5489 channels,
5490 status);
5491
Dima Zavin799a70e2011-04-18 16:57:27 -07005492 if (outStream != NULL) {
5493 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005494 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07005495
Dima Zavinfce7a472011-04-19 22:30:36 -07005496 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5497 (format != AUDIO_FORMAT_PCM_16_BIT) ||
5498 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005499 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005500 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005501 } else {
5502 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005503 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005504 }
5505 mPlaybackThreads.add(id, thread);
5506
Glenn Kastena0d68332012-01-27 16:47:15 -08005507 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5508 if (pFormat != NULL) *pFormat = format;
5509 if (pChannels != NULL) *pChannels = channels;
5510 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005511
5512 // notify client processes of the new output creation
5513 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5514 return id;
5515 }
5516
5517 return 0;
5518}
5519
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005520audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
5521 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005522{
5523 Mutex::Autolock _l(mLock);
5524 MixerThread *thread1 = checkMixerThread_l(output1);
5525 MixerThread *thread2 = checkMixerThread_l(output2);
5526
5527 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005528 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005529 return 0;
5530 }
5531
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005532 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005533 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5534 thread->addOutputTrack(thread2);
5535 mPlaybackThreads.add(id, thread);
5536 // notify client processes of the new output creation
5537 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5538 return id;
5539}
5540
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005541status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005542{
5543 // keep strong reference on the playback thread so that
5544 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005545 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005546 {
5547 Mutex::Autolock _l(mLock);
5548 thread = checkPlaybackThread_l(output);
5549 if (thread == NULL) {
5550 return BAD_VALUE;
5551 }
5552
Steve Block3856b092011-10-20 11:56:00 +01005553 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005554
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005555 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005556 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005557 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005558 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5559 dupThread->removeOutputTrack((MixerThread *)thread.get());
5560 }
5561 }
5562 }
Glenn Kastena1117922012-01-26 10:53:32 -08005563 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005564 mPlaybackThreads.removeItem(output);
5565 }
5566 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005567 // The thread entity (active unit of execution) is no longer running here,
5568 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005569
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005570 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005571 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005572 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005573 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005574 out->hwDev->close_output_stream(out->hwDev, out->stream);
5575 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005576 }
5577 return NO_ERROR;
5578}
5579
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005580status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005581{
5582 Mutex::Autolock _l(mLock);
5583 PlaybackThread *thread = checkPlaybackThread_l(output);
5584
5585 if (thread == NULL) {
5586 return BAD_VALUE;
5587 }
5588
Steve Block3856b092011-10-20 11:56:00 +01005589 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005590 thread->suspend();
5591
5592 return NO_ERROR;
5593}
5594
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005595status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005596{
5597 Mutex::Autolock _l(mLock);
5598 PlaybackThread *thread = checkPlaybackThread_l(output);
5599
5600 if (thread == NULL) {
5601 return BAD_VALUE;
5602 }
5603
Steve Block3856b092011-10-20 11:56:00 +01005604 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005605
5606 thread->restore();
5607
5608 return NO_ERROR;
5609}
5610
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005611audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005612 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005613 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005614 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005615 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005616{
5617 status_t status;
5618 RecordThread *thread = NULL;
5619 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005620 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005621 uint32_t channels = pChannels ? *pChannels : 0;
5622 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005623 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005624 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005625 audio_stream_in_t *inStream;
5626 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005627
5628 if (pDevices == NULL || *pDevices == 0) {
5629 return 0;
5630 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005631
Mathias Agopian65ab4712010-07-14 17:59:35 -07005632 Mutex::Autolock _l(mLock);
5633
Dima Zavin799a70e2011-04-18 16:57:27 -07005634 inHwDev = findSuitableHwDev_l(*pDevices);
5635 if (inHwDev == NULL)
5636 return 0;
5637
Glenn Kasten58f30212012-01-12 12:27:51 -08005638 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005639 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005640 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005641 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005642 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005643 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005644 samplingRate,
5645 format,
5646 channels,
5647 acoustics,
5648 status);
5649
5650 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5651 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5652 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005653 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005654 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005655 (samplingRate <= 2 * reqSamplingRate) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08005656 (popcount(channels) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01005657 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005658 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005659 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005660 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005661 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005662 }
5663
Dima Zavin799a70e2011-04-18 16:57:27 -07005664 if (inStream != NULL) {
5665 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5666
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005667 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005668 // Start record thread
5669 // RecorThread require both input and output device indication to forward to audio
5670 // pre processing modules
5671 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5672 thread = new RecordThread(this,
5673 input,
5674 reqSamplingRate,
5675 reqChannels,
5676 id,
5677 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005678 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005679 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005680 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5681 if (pFormat != NULL) *pFormat = format;
5682 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005683
Dima Zavin799a70e2011-04-18 16:57:27 -07005684 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005685
5686 // notify client processes of the new input creation
5687 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5688 return id;
5689 }
5690
5691 return 0;
5692}
5693
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005694status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005695{
5696 // keep strong reference on the record thread so that
5697 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005698 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005699 {
5700 Mutex::Autolock _l(mLock);
5701 thread = checkRecordThread_l(input);
5702 if (thread == NULL) {
5703 return BAD_VALUE;
5704 }
5705
Steve Block3856b092011-10-20 11:56:00 +01005706 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08005707 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005708 mRecordThreads.removeItem(input);
5709 }
5710 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005711 // The thread entity (active unit of execution) is no longer running here,
5712 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005713
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005714 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005715 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005716 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005717 in->hwDev->close_input_stream(in->hwDev, in->stream);
5718 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005719
5720 return NO_ERROR;
5721}
5722
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005723status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005724{
5725 Mutex::Autolock _l(mLock);
5726 MixerThread *dstThread = checkMixerThread_l(output);
5727 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005728 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005729 return BAD_VALUE;
5730 }
5731
Steve Block3856b092011-10-20 11:56:00 +01005732 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005733 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5734
Eric Laurent9f6530f2011-08-30 10:18:54 -07005735 dstThread->setStreamValid(stream, true);
5736
Mathias Agopian65ab4712010-07-14 17:59:35 -07005737 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5738 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08005739 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005740 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005741 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005742 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005743 }
Eric Laurentde070132010-07-13 04:45:46 -07005744 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005745
5746 return NO_ERROR;
5747}
5748
5749
5750int AudioFlinger::newAudioSessionId()
5751{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005752 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005753}
5754
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005755void AudioFlinger::acquireAudioSessionId(int audioSession)
5756{
5757 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005758 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005759 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005760 size_t num = mAudioSessionRefs.size();
5761 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005762 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005763 if (ref->mSessionid == audioSession && ref->mPid == caller) {
5764 ref->mCnt++;
5765 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005766 return;
5767 }
5768 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005769 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5770 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005771}
5772
5773void AudioFlinger::releaseAudioSessionId(int audioSession)
5774{
5775 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005776 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005777 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005778 size_t num = mAudioSessionRefs.size();
5779 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005780 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005781 if (ref->mSessionid == audioSession && ref->mPid == caller) {
5782 ref->mCnt--;
5783 ALOGV(" decremented refcount to %d", ref->mCnt);
5784 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005785 mAudioSessionRefs.removeAt(i);
5786 delete ref;
5787 purgeStaleEffects_l();
5788 }
5789 return;
5790 }
5791 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005792 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005793}
5794
5795void AudioFlinger::purgeStaleEffects_l() {
5796
Steve Block3856b092011-10-20 11:56:00 +01005797 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005798
5799 Vector< sp<EffectChain> > chains;
5800
5801 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5802 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5803 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5804 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005805 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5806 chains.push(ec);
5807 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005808 }
5809 }
5810 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5811 sp<RecordThread> t = mRecordThreads.valueAt(i);
5812 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5813 sp<EffectChain> ec = t->mEffectChains[j];
5814 chains.push(ec);
5815 }
5816 }
5817
5818 for (size_t i = 0; i < chains.size(); i++) {
5819 sp<EffectChain> ec = chains[i];
5820 int sessionid = ec->sessionId();
5821 sp<ThreadBase> t = ec->mThread.promote();
5822 if (t == 0) {
5823 continue;
5824 }
5825 size_t numsessionrefs = mAudioSessionRefs.size();
5826 bool found = false;
5827 for (size_t k = 0; k < numsessionrefs; k++) {
5828 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005829 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005830 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005831 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005832 found = true;
5833 break;
5834 }
5835 }
5836 if (!found) {
5837 // remove all effects from the chain
5838 while (ec->mEffects.size()) {
5839 sp<EffectModule> effect = ec->mEffects[0];
5840 effect->unPin();
5841 Mutex::Autolock _l (t->mLock);
5842 t->removeEffect_l(effect);
5843 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5844 sp<EffectHandle> handle = effect->mHandles[j].promote();
5845 if (handle != 0) {
5846 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005847 if (handle->mHasControl && handle->mEnabled) {
5848 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5849 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005850 }
5851 }
5852 AudioSystem::unregisterEffect(effect->id());
5853 }
5854 }
5855 }
5856 return;
5857}
5858
Mathias Agopian65ab4712010-07-14 17:59:35 -07005859// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005860AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005861{
Glenn Kastena1117922012-01-26 10:53:32 -08005862 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005863}
5864
5865// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005866AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005867{
5868 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08005869 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005870}
5871
5872// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005873AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005874{
Glenn Kastena1117922012-01-26 10:53:32 -08005875 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005876}
5877
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005878uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005879{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005880 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005881}
5882
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08005883AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005884{
5885 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5886 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005887 AudioStreamOut *output = thread->getOutput();
5888 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005889 return thread;
5890 }
5891 }
5892 return NULL;
5893}
5894
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08005895uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005896{
5897 PlaybackThread *thread = primaryPlaybackThread_l();
5898
5899 if (thread == NULL) {
5900 return 0;
5901 }
5902
5903 return thread->device();
5904}
5905
5906
Mathias Agopian65ab4712010-07-14 17:59:35 -07005907// ----------------------------------------------------------------------------
5908// Effect management
5909// ----------------------------------------------------------------------------
5910
5911
Glenn Kastenf587ba52012-01-26 16:25:10 -08005912status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005913{
5914 Mutex::Autolock _l(mLock);
5915 return EffectQueryNumberEffects(numEffects);
5916}
5917
Glenn Kastenf587ba52012-01-26 16:25:10 -08005918status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005919{
5920 Mutex::Autolock _l(mLock);
5921 return EffectQueryEffect(index, descriptor);
5922}
5923
Glenn Kasten5e92a782012-01-30 07:40:52 -08005924status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08005925 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005926{
5927 Mutex::Autolock _l(mLock);
5928 return EffectGetDescriptor(pUuid, descriptor);
5929}
5930
5931
Mathias Agopian65ab4712010-07-14 17:59:35 -07005932sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5933 effect_descriptor_t *pDesc,
5934 const sp<IEffectClient>& effectClient,
5935 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005936 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005937 int sessionId,
5938 status_t *status,
5939 int *id,
5940 int *enabled)
5941{
5942 status_t lStatus = NO_ERROR;
5943 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005944 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005945
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005946 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005947 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005948
5949 if (pDesc == NULL) {
5950 lStatus = BAD_VALUE;
5951 goto Exit;
5952 }
5953
Eric Laurent84e9a102010-09-23 16:10:16 -07005954 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005955 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005956 lStatus = PERMISSION_DENIED;
5957 goto Exit;
5958 }
5959
Dima Zavinfce7a472011-04-19 22:30:36 -07005960 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005961 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08005962 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005963 lStatus = PERMISSION_DENIED;
5964 goto Exit;
5965 }
5966
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005967 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005968 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005969 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005970 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005971 lStatus = BAD_VALUE;
5972 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005973 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005974 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005975 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005976 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005977 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005978 }
5979 }
5980
Mathias Agopian65ab4712010-07-14 17:59:35 -07005981 {
5982 Mutex::Autolock _l(mLock);
5983
Mathias Agopian65ab4712010-07-14 17:59:35 -07005984
5985 if (!EffectIsNullUuid(&pDesc->uuid)) {
5986 // if uuid is specified, request effect descriptor
5987 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5988 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005989 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005990 goto Exit;
5991 }
5992 } else {
5993 // if uuid is not specified, look for an available implementation
5994 // of the required type in effect factory
5995 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005996 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005997 lStatus = BAD_VALUE;
5998 goto Exit;
5999 }
6000 uint32_t numEffects = 0;
6001 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006002 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07006003 bool found = false;
6004
6005 lStatus = EffectQueryNumberEffects(&numEffects);
6006 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006007 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006008 goto Exit;
6009 }
6010 for (uint32_t i = 0; i < numEffects; i++) {
6011 lStatus = EffectQueryEffect(i, &desc);
6012 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006013 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006014 continue;
6015 }
6016 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
6017 // If matching type found save effect descriptor. If the session is
6018 // 0 and the effect is not auxiliary, continue enumeration in case
6019 // an auxiliary version of this effect type is available
6020 found = true;
6021 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07006022 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006023 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6024 break;
6025 }
6026 }
6027 }
6028 if (!found) {
6029 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00006030 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006031 goto Exit;
6032 }
6033 // For same effect type, chose auxiliary version over insert version if
6034 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07006035 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006036 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
6037 memcpy(&desc, &d, sizeof(effect_descriptor_t));
6038 }
6039 }
6040
6041 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07006042 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006043 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6044 lStatus = INVALID_OPERATION;
6045 goto Exit;
6046 }
6047
Eric Laurent59255e42011-07-27 19:49:51 -07006048 // check recording permission for visualizer
6049 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
6050 !recordingAllowed()) {
6051 lStatus = PERMISSION_DENIED;
6052 goto Exit;
6053 }
6054
Mathias Agopian65ab4712010-07-14 17:59:35 -07006055 // return effect descriptor
6056 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
6057
6058 // If output is not specified try to find a matching audio session ID in one of the
6059 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07006060 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
6061 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006062 // Note: io is never 0 when creating an effect on an input
6063 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006064 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07006065 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6066 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006067 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07006068 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07006069 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006070 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006071 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006072 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6073 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6074 io = mRecordThreads.keyAt(i);
6075 break;
6076 }
6077 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006078 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006079 // If no output thread contains the requested session ID, default to
6080 // first output. The effect chain will be moved to the correct output
6081 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006082 if (io == 0 && mPlaybackThreads.size()) {
6083 io = mPlaybackThreads.keyAt(0);
6084 }
Steve Block3856b092011-10-20 11:56:00 +01006085 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006086 }
6087 ThreadBase *thread = checkRecordThread_l(io);
6088 if (thread == NULL) {
6089 thread = checkPlaybackThread_l(io);
6090 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00006091 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006092 lStatus = BAD_VALUE;
6093 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07006094 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006095 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006096
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006097 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006098
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006099 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07006100 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6101 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006102 if (handle != 0 && id != NULL) {
6103 *id = handle->id();
6104 }
6105 }
6106
6107Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006108 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006109 *status = lStatus;
6110 }
6111 return handle;
6112}
6113
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006114status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
6115 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07006116{
Steve Block3856b092011-10-20 11:56:00 +01006117 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07006118 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006119 Mutex::Autolock _l(mLock);
6120 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006121 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006122 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006123 }
Eric Laurentde070132010-07-13 04:45:46 -07006124 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6125 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006126 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006127 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006128 }
Eric Laurentde070132010-07-13 04:45:46 -07006129 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6130 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006131 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006132 return BAD_VALUE;
6133 }
6134
6135 Mutex::Autolock _dl(dstThread->mLock);
6136 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07006137 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07006138
Mathias Agopian65ab4712010-07-14 17:59:35 -07006139 return NO_ERROR;
6140}
6141
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006142// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07006143status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07006144 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07006145 AudioFlinger::PlaybackThread *dstThread,
6146 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07006147{
Steve Block3856b092011-10-20 11:56:00 +01006148 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006149 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07006150
Eric Laurent59255e42011-07-27 19:49:51 -07006151 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006152 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006153 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006154 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07006155 return INVALID_OPERATION;
6156 }
6157
Eric Laurent39e94f82010-07-28 01:32:47 -07006158 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07006159 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07006160 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07006161 // removed.
6162 srcThread->removeEffectChain_l(chain);
6163
6164 // transfer all effects one by one so that new effect chain is created on new thread with
6165 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006166 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07006167 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006168 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07006169 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6170 while (effect != 0) {
6171 srcThread->removeEffect_l(effect);
6172 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07006173 // removeEffect_l() has stopped the effect if it was active so it must be restarted
6174 if (effect->state() == EffectModule::ACTIVE ||
6175 effect->state() == EffectModule::STOPPING) {
6176 effect->start();
6177 }
Eric Laurent39e94f82010-07-28 01:32:47 -07006178 // if the move request is not received from audio policy manager, the effect must be
6179 // re-registered with the new strategy and output
6180 if (dstChain == 0) {
6181 dstChain = effect->chain().promote();
6182 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006183 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07006184 srcThread->addEffect_l(effect);
6185 return NO_INIT;
6186 }
6187 strategy = dstChain->strategy();
6188 }
6189 if (reRegister) {
6190 AudioSystem::unregisterEffect(effect->id());
6191 AudioSystem::registerEffect(&effect->desc(),
6192 dstOutput,
6193 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07006194 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07006195 effect->id());
6196 }
Eric Laurentde070132010-07-13 04:45:46 -07006197 effect = chain->getEffectFromId_l(0);
6198 }
6199
6200 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006201}
6202
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006203
Mathias Agopian65ab4712010-07-14 17:59:35 -07006204// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006205sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07006206 const sp<AudioFlinger::Client>& client,
6207 const sp<IEffectClient>& effectClient,
6208 int32_t priority,
6209 int sessionId,
6210 effect_descriptor_t *desc,
6211 int *enabled,
6212 status_t *status
6213 )
6214{
6215 sp<EffectModule> effect;
6216 sp<EffectHandle> handle;
6217 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006218 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07006219 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006220 bool effectCreated = false;
6221 bool effectRegistered = false;
6222
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006223 lStatus = initCheck();
6224 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006225 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006226 goto Exit;
6227 }
6228
6229 // Do not allow effects with session ID 0 on direct output or duplicating threads
6230 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07006231 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006232 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07006233 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006234 lStatus = BAD_VALUE;
6235 goto Exit;
6236 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006237 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08006238 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006239 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006240 desc->name, desc->flags, mType);
6241 lStatus = BAD_VALUE;
6242 goto Exit;
6243 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006244
Steve Block3856b092011-10-20 11:56:00 +01006245 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006246
6247 { // scope for mLock
6248 Mutex::Autolock _l(mLock);
6249
6250 // check for existing effect chain with the requested audio session
6251 chain = getEffectChain_l(sessionId);
6252 if (chain == 0) {
6253 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006254 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006255 chain = new EffectChain(this, sessionId);
6256 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07006257 chain->setStrategy(getStrategyForSession_l(sessionId));
6258 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006259 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07006260 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006261 }
6262
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08006263 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006264
6265 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006266 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006267 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07006268 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006269 if (lStatus != NO_ERROR) {
6270 goto Exit;
6271 }
6272 effectRegistered = true;
6273 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07006274 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006275 lStatus = effect->status();
6276 if (lStatus != NO_ERROR) {
6277 goto Exit;
6278 }
Eric Laurentcab11242010-07-15 12:50:15 -07006279 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006280 if (lStatus != NO_ERROR) {
6281 goto Exit;
6282 }
6283 effectCreated = true;
6284
6285 effect->setDevice(mDevice);
6286 effect->setMode(mAudioFlinger->getMode());
6287 }
6288 // create effect handle and connect it to effect module
6289 handle = new EffectHandle(effect, client, effectClient, priority);
6290 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08006291 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006292 *enabled = (int)effect->isEnabled();
6293 }
6294 }
6295
6296Exit:
6297 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07006298 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006299 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07006300 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006301 }
6302 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07006303 AudioSystem::unregisterEffect(effect->id());
6304 }
6305 if (chainCreated) {
6306 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006307 }
6308 handle.clear();
6309 }
6310
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006311 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006312 *status = lStatus;
6313 }
6314 return handle;
6315}
6316
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006317sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6318{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006319 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08006320 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006321}
6322
Eric Laurentde070132010-07-13 04:45:46 -07006323// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6324// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006325status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07006326{
6327 // check for existing effect chain with the requested audio session
6328 int sessionId = effect->sessionId();
6329 sp<EffectChain> chain = getEffectChain_l(sessionId);
6330 bool chainCreated = false;
6331
6332 if (chain == 0) {
6333 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006334 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006335 chain = new EffectChain(this, sessionId);
6336 addEffectChain_l(chain);
6337 chain->setStrategy(getStrategyForSession_l(sessionId));
6338 chainCreated = true;
6339 }
Steve Block3856b092011-10-20 11:56:00 +01006340 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006341
6342 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006343 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07006344 this, effect->desc().name, chain.get());
6345 return BAD_VALUE;
6346 }
6347
6348 status_t status = chain->addEffect_l(effect);
6349 if (status != NO_ERROR) {
6350 if (chainCreated) {
6351 removeEffectChain_l(chain);
6352 }
6353 return status;
6354 }
6355
6356 effect->setDevice(mDevice);
6357 effect->setMode(mAudioFlinger->getMode());
6358 return NO_ERROR;
6359}
6360
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006361void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07006362
Steve Block3856b092011-10-20 11:56:00 +01006363 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006364 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07006365 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6366 detachAuxEffect_l(effect->id());
6367 }
6368
6369 sp<EffectChain> chain = effect->chain().promote();
6370 if (chain != 0) {
6371 // remove effect chain if removing last effect
6372 if (chain->removeEffect_l(effect) == 0) {
6373 removeEffectChain_l(chain);
6374 }
6375 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00006376 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006377 }
6378}
6379
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006380void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006381 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006382{
6383 effectChains = mEffectChains;
6384 for (size_t i = 0; i < mEffectChains.size(); i++) {
6385 mEffectChains[i]->lock();
6386 }
6387}
6388
6389void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006390 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006391{
6392 for (size_t i = 0; i < effectChains.size(); i++) {
6393 effectChains[i]->unlock();
6394 }
6395}
6396
6397sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6398{
6399 Mutex::Autolock _l(mLock);
6400 return getEffectChain_l(sessionId);
6401}
6402
6403sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6404{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006405 size_t size = mEffectChains.size();
6406 for (size_t i = 0; i < size; i++) {
6407 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08006408 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006409 }
6410 }
Glenn Kasten090f0192012-01-30 13:00:02 -08006411 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006412}
6413
Glenn Kastenf78aee72012-01-04 11:00:47 -08006414void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006415{
6416 Mutex::Autolock _l(mLock);
6417 size_t size = mEffectChains.size();
6418 for (size_t i = 0; i < size; i++) {
6419 mEffectChains[i]->setMode_l(mode);
6420 }
6421}
6422
6423void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006424 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08006425 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07006426
Mathias Agopian65ab4712010-07-14 17:59:35 -07006427 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006428 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006429 // delete the effect module if removing last handle on it
6430 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006431 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006432 removeEffect_l(effect);
6433 AudioSystem::unregisterEffect(effect->id());
6434 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006435 }
6436}
6437
6438status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6439{
6440 int session = chain->sessionId();
6441 int16_t *buffer = mMixBuffer;
6442 bool ownsBuffer = false;
6443
Steve Block3856b092011-10-20 11:56:00 +01006444 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006445 if (session > 0) {
6446 // Only one effect chain can be present in direct output thread and it uses
6447 // the mix buffer as input
6448 if (mType != DIRECT) {
6449 size_t numSamples = mFrameCount * mChannelCount;
6450 buffer = new int16_t[numSamples];
6451 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01006452 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006453 ownsBuffer = true;
6454 }
6455
6456 // Attach all tracks with same session ID to this chain.
6457 for (size_t i = 0; i < mTracks.size(); ++i) {
6458 sp<Track> track = mTracks[i];
6459 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006460 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006461 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006462 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006463 }
6464 }
6465
6466 // indicate all active tracks in the chain
6467 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6468 sp<Track> track = mActiveTracks[i].promote();
6469 if (track == 0) continue;
6470 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006471 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07006472 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006473 }
6474 }
6475 }
6476
6477 chain->setInBuffer(buffer, ownsBuffer);
6478 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006479 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006480 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006481 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6482 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006483 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006484 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6485 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006486 // Effect chain for other sessions are inserted at beginning of effect
6487 // chains list to be processed before output mix effects. Relative order between other
6488 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006489 size_t size = mEffectChains.size();
6490 size_t i = 0;
6491 for (i = 0; i < size; i++) {
6492 if (mEffectChains[i]->sessionId() < session) break;
6493 }
6494 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006495 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006496
6497 return NO_ERROR;
6498}
6499
6500size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6501{
6502 int session = chain->sessionId();
6503
Steve Block3856b092011-10-20 11:56:00 +01006504 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006505
6506 for (size_t i = 0; i < mEffectChains.size(); i++) {
6507 if (chain == mEffectChains[i]) {
6508 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006509 // detach all active tracks from the chain
6510 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6511 sp<Track> track = mActiveTracks[i].promote();
6512 if (track == 0) continue;
6513 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006514 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006515 chain.get(), session);
6516 chain->decActiveTrackCnt();
6517 }
6518 }
6519
Mathias Agopian65ab4712010-07-14 17:59:35 -07006520 // detach all tracks with same session ID from this chain
6521 for (size_t i = 0; i < mTracks.size(); ++i) {
6522 sp<Track> track = mTracks[i];
6523 if (session == track->sessionId()) {
6524 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006525 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006526 }
6527 }
Eric Laurentde070132010-07-13 04:45:46 -07006528 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006529 }
6530 }
6531 return mEffectChains.size();
6532}
6533
Eric Laurentde070132010-07-13 04:45:46 -07006534status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6535 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006536{
6537 Mutex::Autolock _l(mLock);
6538 return attachAuxEffect_l(track, EffectId);
6539}
6540
Eric Laurentde070132010-07-13 04:45:46 -07006541status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6542 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006543{
6544 status_t status = NO_ERROR;
6545
6546 if (EffectId == 0) {
6547 track->setAuxBuffer(0, NULL);
6548 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006549 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6550 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006551 if (effect != 0) {
6552 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6553 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6554 } else {
6555 status = INVALID_OPERATION;
6556 }
6557 } else {
6558 status = BAD_VALUE;
6559 }
6560 }
6561 return status;
6562}
6563
6564void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6565{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006566 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006567 sp<Track> track = mTracks[i];
6568 if (track->auxEffectId() == effectId) {
6569 attachAuxEffect_l(track, 0);
6570 }
6571 }
6572}
6573
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006574status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6575{
6576 // only one chain per input thread
6577 if (mEffectChains.size() != 0) {
6578 return INVALID_OPERATION;
6579 }
Steve Block3856b092011-10-20 11:56:00 +01006580 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006581
6582 chain->setInBuffer(NULL);
6583 chain->setOutBuffer(NULL);
6584
Eric Laurent59255e42011-07-27 19:49:51 -07006585 checkSuspendOnAddEffectChain_l(chain);
6586
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006587 mEffectChains.add(chain);
6588
6589 return NO_ERROR;
6590}
6591
6592size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6593{
Steve Block3856b092011-10-20 11:56:00 +01006594 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006595 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006596 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6597 chain.get(), mEffectChains.size(), this);
6598 if (mEffectChains.size() == 1) {
6599 mEffectChains.removeAt(0);
6600 }
6601 return 0;
6602}
6603
Mathias Agopian65ab4712010-07-14 17:59:35 -07006604// ----------------------------------------------------------------------------
6605// EffectModule implementation
6606// ----------------------------------------------------------------------------
6607
6608#undef LOG_TAG
6609#define LOG_TAG "AudioFlinger::EffectModule"
6610
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006611AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006612 const wp<AudioFlinger::EffectChain>& chain,
6613 effect_descriptor_t *desc,
6614 int id,
6615 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006616 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006617 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006618{
Steve Block3856b092011-10-20 11:56:00 +01006619 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006620 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006621 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006622 return;
6623 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006624
6625 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6626
6627 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006628 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006629
6630 if (mStatus != NO_ERROR) {
6631 return;
6632 }
6633 lStatus = init();
6634 if (lStatus < 0) {
6635 mStatus = lStatus;
6636 goto Error;
6637 }
6638
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006639 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6640 mPinned = true;
6641 }
Steve Block3856b092011-10-20 11:56:00 +01006642 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006643 return;
6644Error:
6645 EffectRelease(mEffectInterface);
6646 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006647 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006648}
6649
6650AudioFlinger::EffectModule::~EffectModule()
6651{
Steve Block3856b092011-10-20 11:56:00 +01006652 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006653 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006654 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6655 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6656 sp<ThreadBase> thread = mThread.promote();
6657 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006658 audio_stream_t *stream = thread->stream();
6659 if (stream != NULL) {
6660 stream->remove_audio_effect(stream, mEffectInterface);
6661 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006662 }
6663 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006664 // release effect engine
6665 EffectRelease(mEffectInterface);
6666 }
6667}
6668
Glenn Kasten435dbe62012-01-30 10:15:48 -08006669status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006670{
6671 status_t status;
6672
6673 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006674 int priority = handle->priority();
6675 size_t size = mHandles.size();
6676 sp<EffectHandle> h;
6677 size_t i;
6678 for (i = 0; i < size; i++) {
6679 h = mHandles[i].promote();
6680 if (h == 0) continue;
6681 if (h->priority() <= priority) break;
6682 }
6683 // if inserted in first place, move effect control from previous owner to this handle
6684 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006685 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006686 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006687 enabled = h->enabled();
6688 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006689 }
Eric Laurent59255e42011-07-27 19:49:51 -07006690 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006691 status = NO_ERROR;
6692 } else {
6693 status = ALREADY_EXISTS;
6694 }
Steve Block3856b092011-10-20 11:56:00 +01006695 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006696 mHandles.insertAt(handle, i);
6697 return status;
6698}
6699
6700size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6701{
6702 Mutex::Autolock _l(mLock);
6703 size_t size = mHandles.size();
6704 size_t i;
6705 for (i = 0; i < size; i++) {
6706 if (mHandles[i] == handle) break;
6707 }
6708 if (i == size) {
6709 return size;
6710 }
Steve Block3856b092011-10-20 11:56:00 +01006711 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006712
6713 bool enabled = false;
6714 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006715 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006716 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006717 enabled = hdl->enabled();
6718 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006719 mHandles.removeAt(i);
6720 size = mHandles.size();
6721 // if removed from first place, move effect control from this handle to next in line
6722 if (i == 0 && size != 0) {
6723 sp<EffectHandle> h = mHandles[0].promote();
6724 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006725 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006726 }
6727 }
6728
Eric Laurentec437d82011-07-26 20:54:46 -07006729 // Prevent calls to process() and other functions on effect interface from now on.
6730 // The effect engine will be released by the destructor when the last strong reference on
6731 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006732 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006733 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006734 }
6735
Mathias Agopian65ab4712010-07-14 17:59:35 -07006736 return size;
6737}
6738
Eric Laurent59255e42011-07-27 19:49:51 -07006739sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6740{
6741 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08006742 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07006743}
6744
Glenn Kasten58123c32012-02-03 10:32:24 -08006745void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006746{
Glenn Kasten90bebef2012-01-27 15:24:38 -08006747 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006748 // keep a strong reference on this EffectModule to avoid calling the
6749 // destructor before we exit
6750 sp<EffectModule> keep(this);
6751 {
6752 sp<ThreadBase> thread = mThread.promote();
6753 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006754 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006755 }
6756 }
6757}
6758
6759void AudioFlinger::EffectModule::updateState() {
6760 Mutex::Autolock _l(mLock);
6761
6762 switch (mState) {
6763 case RESTART:
6764 reset_l();
6765 // FALL THROUGH
6766
6767 case STARTING:
6768 // clear auxiliary effect input buffer for next accumulation
6769 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6770 memset(mConfig.inputCfg.buffer.raw,
6771 0,
6772 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6773 }
6774 start_l();
6775 mState = ACTIVE;
6776 break;
6777 case STOPPING:
6778 stop_l();
6779 mDisableWaitCnt = mMaxDisableWaitCnt;
6780 mState = STOPPED;
6781 break;
6782 case STOPPED:
6783 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6784 // turn off sequence.
6785 if (--mDisableWaitCnt == 0) {
6786 reset_l();
6787 mState = IDLE;
6788 }
6789 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006790 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006791 break;
6792 }
6793}
6794
6795void AudioFlinger::EffectModule::process()
6796{
6797 Mutex::Autolock _l(mLock);
6798
Eric Laurentec437d82011-07-26 20:54:46 -07006799 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006800 mConfig.inputCfg.buffer.raw == NULL ||
6801 mConfig.outputCfg.buffer.raw == NULL) {
6802 return;
6803 }
6804
Eric Laurent8f45bd72010-08-31 13:50:07 -07006805 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006806 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6807 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006808 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006809 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006810 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006811 }
6812
6813 // do the actual processing in the effect engine
6814 int ret = (*mEffectInterface)->process(mEffectInterface,
6815 &mConfig.inputCfg.buffer,
6816 &mConfig.outputCfg.buffer);
6817
6818 // force transition to IDLE state when engine is ready
6819 if (mState == STOPPED && ret == -ENODATA) {
6820 mDisableWaitCnt = 1;
6821 }
6822
6823 // clear auxiliary effect input buffer for next accumulation
6824 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006825 memset(mConfig.inputCfg.buffer.raw, 0,
6826 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006827 }
6828 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006829 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6830 // If an insert effect is idle and input buffer is different from output buffer,
6831 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006832 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006833 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006834 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6835 int16_t *in = mConfig.inputCfg.buffer.s16;
6836 int16_t *out = mConfig.outputCfg.buffer.s16;
6837 for (size_t i = 0; i < frameCnt; i++) {
6838 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006839 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006840 }
6841 }
6842}
6843
6844void AudioFlinger::EffectModule::reset_l()
6845{
6846 if (mEffectInterface == NULL) {
6847 return;
6848 }
6849 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6850}
6851
6852status_t AudioFlinger::EffectModule::configure()
6853{
6854 uint32_t channels;
6855 if (mEffectInterface == NULL) {
6856 return NO_INIT;
6857 }
6858
6859 sp<ThreadBase> thread = mThread.promote();
6860 if (thread == 0) {
6861 return DEAD_OBJECT;
6862 }
6863
6864 // TODO: handle configuration of effects replacing track process
6865 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006866 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006867 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006868 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006869 }
6870
6871 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006872 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006873 } else {
6874 mConfig.inputCfg.channels = channels;
6875 }
6876 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006877 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6878 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006879 mConfig.inputCfg.samplingRate = thread->sampleRate();
6880 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6881 mConfig.inputCfg.bufferProvider.cookie = NULL;
6882 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6883 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6884 mConfig.outputCfg.bufferProvider.cookie = NULL;
6885 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6886 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6887 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6888 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006889 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006890 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006891 // - in other sessions:
6892 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6893 // other effect: overwrites output buffer: input buffer == output buffer
6894 // Auxiliary effect:
6895 // accumulates in output buffer: input buffer != output buffer
6896 // Therefore: accumulate <=> input buffer != output buffer
6897 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6898 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6899 } else {
6900 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6901 }
6902 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6903 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6904 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6905 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6906
Steve Block3856b092011-10-20 11:56:00 +01006907 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006908 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6909
Mathias Agopian65ab4712010-07-14 17:59:35 -07006910 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006911 uint32_t size = sizeof(int);
6912 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006913 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006914 sizeof(effect_config_t),
6915 &mConfig,
6916 &size,
6917 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006918 if (status == 0) {
6919 status = cmdStatus;
6920 }
6921
6922 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6923 (1000 * mConfig.outputCfg.buffer.frameCount);
6924
6925 return status;
6926}
6927
6928status_t AudioFlinger::EffectModule::init()
6929{
6930 Mutex::Autolock _l(mLock);
6931 if (mEffectInterface == NULL) {
6932 return NO_INIT;
6933 }
6934 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006935 uint32_t size = sizeof(status_t);
6936 status_t status = (*mEffectInterface)->command(mEffectInterface,
6937 EFFECT_CMD_INIT,
6938 0,
6939 NULL,
6940 &size,
6941 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006942 if (status == 0) {
6943 status = cmdStatus;
6944 }
6945 return status;
6946}
6947
Eric Laurentec35a142011-10-05 17:42:25 -07006948status_t AudioFlinger::EffectModule::start()
6949{
6950 Mutex::Autolock _l(mLock);
6951 return start_l();
6952}
6953
Mathias Agopian65ab4712010-07-14 17:59:35 -07006954status_t AudioFlinger::EffectModule::start_l()
6955{
6956 if (mEffectInterface == NULL) {
6957 return NO_INIT;
6958 }
6959 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006960 uint32_t size = sizeof(status_t);
6961 status_t status = (*mEffectInterface)->command(mEffectInterface,
6962 EFFECT_CMD_ENABLE,
6963 0,
6964 NULL,
6965 &size,
6966 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006967 if (status == 0) {
6968 status = cmdStatus;
6969 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006970 if (status == 0 &&
6971 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6972 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6973 sp<ThreadBase> thread = mThread.promote();
6974 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006975 audio_stream_t *stream = thread->stream();
6976 if (stream != NULL) {
6977 stream->add_audio_effect(stream, mEffectInterface);
6978 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006979 }
6980 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006981 return status;
6982}
6983
Eric Laurentec437d82011-07-26 20:54:46 -07006984status_t AudioFlinger::EffectModule::stop()
6985{
6986 Mutex::Autolock _l(mLock);
6987 return stop_l();
6988}
6989
Mathias Agopian65ab4712010-07-14 17:59:35 -07006990status_t AudioFlinger::EffectModule::stop_l()
6991{
6992 if (mEffectInterface == NULL) {
6993 return NO_INIT;
6994 }
6995 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006996 uint32_t size = sizeof(status_t);
6997 status_t status = (*mEffectInterface)->command(mEffectInterface,
6998 EFFECT_CMD_DISABLE,
6999 0,
7000 NULL,
7001 &size,
7002 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007003 if (status == 0) {
7004 status = cmdStatus;
7005 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007006 if (status == 0 &&
7007 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7008 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7009 sp<ThreadBase> thread = mThread.promote();
7010 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007011 audio_stream_t *stream = thread->stream();
7012 if (stream != NULL) {
7013 stream->remove_audio_effect(stream, mEffectInterface);
7014 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007015 }
7016 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007017 return status;
7018}
7019
Eric Laurent25f43952010-07-28 05:40:18 -07007020status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
7021 uint32_t cmdSize,
7022 void *pCmdData,
7023 uint32_t *replySize,
7024 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007025{
7026 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007027// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007028
Eric Laurentec437d82011-07-26 20:54:46 -07007029 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007030 return NO_INIT;
7031 }
Eric Laurent25f43952010-07-28 05:40:18 -07007032 status_t status = (*mEffectInterface)->command(mEffectInterface,
7033 cmdCode,
7034 cmdSize,
7035 pCmdData,
7036 replySize,
7037 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007038 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07007039 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007040 for (size_t i = 1; i < mHandles.size(); i++) {
7041 sp<EffectHandle> h = mHandles[i].promote();
7042 if (h != 0) {
7043 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
7044 }
7045 }
7046 }
7047 return status;
7048}
7049
7050status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
7051{
Eric Laurentdb7c0792011-08-10 10:37:50 -07007052
Mathias Agopian65ab4712010-07-14 17:59:35 -07007053 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007054 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007055
7056 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007057 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
7058 if (enabled && status != NO_ERROR) {
7059 return status;
7060 }
7061
Mathias Agopian65ab4712010-07-14 17:59:35 -07007062 switch (mState) {
7063 // going from disabled to enabled
7064 case IDLE:
7065 mState = STARTING;
7066 break;
7067 case STOPPED:
7068 mState = RESTART;
7069 break;
7070 case STOPPING:
7071 mState = ACTIVE;
7072 break;
7073
7074 // going from enabled to disabled
7075 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007076 mState = STOPPED;
7077 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007078 case STARTING:
7079 mState = IDLE;
7080 break;
7081 case ACTIVE:
7082 mState = STOPPING;
7083 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007084 case DESTROYED:
7085 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007086 }
7087 for (size_t i = 1; i < mHandles.size(); i++) {
7088 sp<EffectHandle> h = mHandles[i].promote();
7089 if (h != 0) {
7090 h->setEnabled(enabled);
7091 }
7092 }
7093 }
7094 return NO_ERROR;
7095}
7096
Glenn Kastenc59c0042012-02-02 14:06:11 -08007097bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007098{
7099 switch (mState) {
7100 case RESTART:
7101 case STARTING:
7102 case ACTIVE:
7103 return true;
7104 case IDLE:
7105 case STOPPING:
7106 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07007107 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07007108 default:
7109 return false;
7110 }
7111}
7112
Glenn Kastenc59c0042012-02-02 14:06:11 -08007113bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07007114{
7115 switch (mState) {
7116 case RESTART:
7117 case ACTIVE:
7118 case STOPPING:
7119 case STOPPED:
7120 return true;
7121 case IDLE:
7122 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07007123 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007124 default:
7125 return false;
7126 }
7127}
7128
Mathias Agopian65ab4712010-07-14 17:59:35 -07007129status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7130{
7131 Mutex::Autolock _l(mLock);
7132 status_t status = NO_ERROR;
7133
7134 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7135 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07007136 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07007137 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7138 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007139 status_t cmdStatus;
7140 uint32_t volume[2];
7141 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07007142 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007143 volume[0] = *left;
7144 volume[1] = *right;
7145 if (controller) {
7146 pVolume = volume;
7147 }
Eric Laurent25f43952010-07-28 05:40:18 -07007148 status = (*mEffectInterface)->command(mEffectInterface,
7149 EFFECT_CMD_SET_VOLUME,
7150 size,
7151 volume,
7152 &size,
7153 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007154 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7155 *left = volume[0];
7156 *right = volume[1];
7157 }
7158 }
7159 return status;
7160}
7161
7162status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7163{
7164 Mutex::Autolock _l(mLock);
7165 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007166 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7167 // audio pre processing modules on RecordThread can receive both output and
7168 // input device indication in the same call
7169 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7170 if (dev) {
7171 status_t cmdStatus;
7172 uint32_t size = sizeof(status_t);
7173
7174 status = (*mEffectInterface)->command(mEffectInterface,
7175 EFFECT_CMD_SET_DEVICE,
7176 sizeof(uint32_t),
7177 &dev,
7178 &size,
7179 &cmdStatus);
7180 if (status == NO_ERROR) {
7181 status = cmdStatus;
7182 }
7183 }
7184 dev = device & AUDIO_DEVICE_IN_ALL;
7185 if (dev) {
7186 status_t cmdStatus;
7187 uint32_t size = sizeof(status_t);
7188
7189 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7190 EFFECT_CMD_SET_INPUT_DEVICE,
7191 sizeof(uint32_t),
7192 &dev,
7193 &size,
7194 &cmdStatus);
7195 if (status2 == NO_ERROR) {
7196 status2 = cmdStatus;
7197 }
7198 if (status == NO_ERROR) {
7199 status = status2;
7200 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007201 }
7202 }
7203 return status;
7204}
7205
Glenn Kastenf78aee72012-01-04 11:00:47 -08007206status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007207{
7208 Mutex::Autolock _l(mLock);
7209 status_t status = NO_ERROR;
7210 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007211 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007212 uint32_t size = sizeof(status_t);
7213 status = (*mEffectInterface)->command(mEffectInterface,
7214 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08007215 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07007216 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07007217 &size,
7218 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007219 if (status == NO_ERROR) {
7220 status = cmdStatus;
7221 }
7222 }
7223 return status;
7224}
7225
Eric Laurent59255e42011-07-27 19:49:51 -07007226void AudioFlinger::EffectModule::setSuspended(bool suspended)
7227{
7228 Mutex::Autolock _l(mLock);
7229 mSuspended = suspended;
7230}
Glenn Kastena3a85482012-01-04 11:01:11 -08007231
7232bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07007233{
7234 Mutex::Autolock _l(mLock);
7235 return mSuspended;
7236}
7237
Mathias Agopian65ab4712010-07-14 17:59:35 -07007238status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7239{
7240 const size_t SIZE = 256;
7241 char buffer[SIZE];
7242 String8 result;
7243
7244 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7245 result.append(buffer);
7246
7247 bool locked = tryLock(mLock);
7248 // failed to lock - AudioFlinger is probably deadlocked
7249 if (!locked) {
7250 result.append("\t\tCould not lock Fx mutex:\n");
7251 }
7252
7253 result.append("\t\tSession Status State Engine:\n");
7254 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7255 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7256 result.append(buffer);
7257
7258 result.append("\t\tDescriptor:\n");
7259 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7260 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7261 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7262 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7263 result.append(buffer);
7264 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7265 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7266 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7267 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7268 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07007269 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007270 mDescriptor.apiVersion,
7271 mDescriptor.flags);
7272 result.append(buffer);
7273 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7274 mDescriptor.name);
7275 result.append(buffer);
7276 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7277 mDescriptor.implementor);
7278 result.append(buffer);
7279
7280 result.append("\t\t- Input configuration:\n");
7281 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7282 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7283 (uint32_t)mConfig.inputCfg.buffer.raw,
7284 mConfig.inputCfg.buffer.frameCount,
7285 mConfig.inputCfg.samplingRate,
7286 mConfig.inputCfg.channels,
7287 mConfig.inputCfg.format);
7288 result.append(buffer);
7289
7290 result.append("\t\t- Output configuration:\n");
7291 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7292 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7293 (uint32_t)mConfig.outputCfg.buffer.raw,
7294 mConfig.outputCfg.buffer.frameCount,
7295 mConfig.outputCfg.samplingRate,
7296 mConfig.outputCfg.channels,
7297 mConfig.outputCfg.format);
7298 result.append(buffer);
7299
7300 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7301 result.append(buffer);
7302 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7303 for (size_t i = 0; i < mHandles.size(); ++i) {
7304 sp<EffectHandle> handle = mHandles[i].promote();
7305 if (handle != 0) {
7306 handle->dump(buffer, SIZE);
7307 result.append(buffer);
7308 }
7309 }
7310
7311 result.append("\n");
7312
7313 write(fd, result.string(), result.length());
7314
7315 if (locked) {
7316 mLock.unlock();
7317 }
7318
7319 return NO_ERROR;
7320}
7321
7322// ----------------------------------------------------------------------------
7323// EffectHandle implementation
7324// ----------------------------------------------------------------------------
7325
7326#undef LOG_TAG
7327#define LOG_TAG "AudioFlinger::EffectHandle"
7328
7329AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7330 const sp<AudioFlinger::Client>& client,
7331 const sp<IEffectClient>& effectClient,
7332 int32_t priority)
7333 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007334 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007335 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007336{
Steve Block3856b092011-10-20 11:56:00 +01007337 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007338
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007339 if (client == 0) {
7340 return;
7341 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007342 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7343 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7344 if (mCblkMemory != 0) {
7345 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7346
Glenn Kastena0d68332012-01-27 16:47:15 -08007347 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007348 new(mCblk) effect_param_cblk_t();
7349 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007350 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007351 } else {
Steve Block29357bc2012-01-06 19:20:56 +00007352 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007353 return;
7354 }
7355}
7356
7357AudioFlinger::EffectHandle::~EffectHandle()
7358{
Steve Block3856b092011-10-20 11:56:00 +01007359 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007360 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01007361 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007362}
7363
7364status_t AudioFlinger::EffectHandle::enable()
7365{
Steve Block3856b092011-10-20 11:56:00 +01007366 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007367 if (!mHasControl) return INVALID_OPERATION;
7368 if (mEffect == 0) return DEAD_OBJECT;
7369
Eric Laurentdb7c0792011-08-10 10:37:50 -07007370 if (mEnabled) {
7371 return NO_ERROR;
7372 }
7373
Eric Laurent59255e42011-07-27 19:49:51 -07007374 mEnabled = true;
7375
7376 sp<ThreadBase> thread = mEffect->thread().promote();
7377 if (thread != 0) {
7378 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7379 }
7380
7381 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7382 if (mEffect->suspended()) {
7383 return NO_ERROR;
7384 }
7385
Eric Laurentdb7c0792011-08-10 10:37:50 -07007386 status_t status = mEffect->setEnabled(true);
7387 if (status != NO_ERROR) {
7388 if (thread != 0) {
7389 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7390 }
7391 mEnabled = false;
7392 }
7393 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007394}
7395
7396status_t AudioFlinger::EffectHandle::disable()
7397{
Steve Block3856b092011-10-20 11:56:00 +01007398 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007399 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07007400 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007401
Eric Laurentdb7c0792011-08-10 10:37:50 -07007402 if (!mEnabled) {
7403 return NO_ERROR;
7404 }
Eric Laurent59255e42011-07-27 19:49:51 -07007405 mEnabled = false;
7406
7407 if (mEffect->suspended()) {
7408 return NO_ERROR;
7409 }
7410
7411 status_t status = mEffect->setEnabled(false);
7412
7413 sp<ThreadBase> thread = mEffect->thread().promote();
7414 if (thread != 0) {
7415 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7416 }
7417
7418 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007419}
7420
7421void AudioFlinger::EffectHandle::disconnect()
7422{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007423 disconnect(true);
7424}
7425
Glenn Kasten58123c32012-02-03 10:32:24 -08007426void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007427{
Glenn Kasten58123c32012-02-03 10:32:24 -08007428 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007429 if (mEffect == 0) {
7430 return;
7431 }
Glenn Kasten58123c32012-02-03 10:32:24 -08007432 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07007433
Eric Laurenta85a74a2011-10-19 11:44:54 -07007434 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007435 sp<ThreadBase> thread = mEffect->thread().promote();
7436 if (thread != 0) {
7437 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7438 }
Eric Laurent59255e42011-07-27 19:49:51 -07007439 }
7440
Mathias Agopian65ab4712010-07-14 17:59:35 -07007441 // release sp on module => module destructor can be called now
7442 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007443 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08007444 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08007445 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007446 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7447 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08007448 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007449 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07007450 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7451 mClient.clear();
7452 }
7453}
7454
Eric Laurent25f43952010-07-28 05:40:18 -07007455status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7456 uint32_t cmdSize,
7457 void *pCmdData,
7458 uint32_t *replySize,
7459 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007460{
Steve Block3856b092011-10-20 11:56:00 +01007461// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07007462// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007463
7464 // only get parameter command is permitted for applications not controlling the effect
7465 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7466 return INVALID_OPERATION;
7467 }
7468 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007469 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007470
7471 // handle commands that are not forwarded transparently to effect engine
7472 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7473 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7474 // no risk to block the whole media server process or mixer threads is we are stuck here
7475 Mutex::Autolock _l(mCblk->lock);
7476 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7477 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7478 mCblk->serverIndex = 0;
7479 mCblk->clientIndex = 0;
7480 return BAD_VALUE;
7481 }
7482 status_t status = NO_ERROR;
7483 while (mCblk->serverIndex < mCblk->clientIndex) {
7484 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007485 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007486 int *p = (int *)(mBuffer + mCblk->serverIndex);
7487 int size = *p++;
7488 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007489 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007490 break;
7491 }
7492 effect_param_t *param = (effect_param_t *)p;
7493 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007494 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007495 mCblk->serverIndex += size;
7496 continue;
7497 }
Eric Laurent25f43952010-07-28 05:40:18 -07007498 uint32_t psize = sizeof(effect_param_t) +
7499 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7500 param->vsize;
7501 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7502 psize,
7503 p,
7504 &rsize,
7505 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007506 // stop at first error encountered
7507 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007508 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007509 *(int *)pReplyData = reply;
7510 break;
7511 } else if (reply != NO_ERROR) {
7512 *(int *)pReplyData = reply;
7513 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007514 }
7515 mCblk->serverIndex += size;
7516 }
7517 mCblk->serverIndex = 0;
7518 mCblk->clientIndex = 0;
7519 return status;
7520 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007521 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007522 return enable();
7523 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007524 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007525 return disable();
7526 }
7527
7528 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7529}
7530
Eric Laurent59255e42011-07-27 19:49:51 -07007531void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007532{
Steve Block3856b092011-10-20 11:56:00 +01007533 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007534
7535 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007536 mEnabled = enabled;
7537
Mathias Agopian65ab4712010-07-14 17:59:35 -07007538 if (signal && mEffectClient != 0) {
7539 mEffectClient->controlStatusChanged(hasControl);
7540 }
7541}
7542
Eric Laurent25f43952010-07-28 05:40:18 -07007543void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7544 uint32_t cmdSize,
7545 void *pCmdData,
7546 uint32_t replySize,
7547 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007548{
7549 if (mEffectClient != 0) {
7550 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7551 }
7552}
7553
7554
7555
7556void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7557{
7558 if (mEffectClient != 0) {
7559 mEffectClient->enableStatusChanged(enabled);
7560 }
7561}
7562
7563status_t AudioFlinger::EffectHandle::onTransact(
7564 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7565{
7566 return BnEffect::onTransact(code, data, reply, flags);
7567}
7568
7569
7570void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7571{
Glenn Kastena0d68332012-01-27 16:47:15 -08007572 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007573
7574 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08007575 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007576 mPriority,
7577 mHasControl,
7578 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007579 mCblk ? mCblk->clientIndex : 0,
7580 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007581 );
7582
7583 if (locked) {
7584 mCblk->lock.unlock();
7585 }
7586}
7587
7588#undef LOG_TAG
7589#define LOG_TAG "AudioFlinger::EffectChain"
7590
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007591AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007592 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007593 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007594 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7595 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007596{
Dima Zavinfce7a472011-04-19 22:30:36 -07007597 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007598 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007599 return;
7600 }
7601 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7602 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007603}
7604
7605AudioFlinger::EffectChain::~EffectChain()
7606{
7607 if (mOwnInBuffer) {
7608 delete mInBuffer;
7609 }
7610
7611}
7612
Eric Laurent59255e42011-07-27 19:49:51 -07007613// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007614sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007615{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007616 size_t size = mEffects.size();
7617
7618 for (size_t i = 0; i < size; i++) {
7619 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007620 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007621 }
7622 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007623 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007624}
7625
Eric Laurent59255e42011-07-27 19:49:51 -07007626// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007627sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007628{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007629 size_t size = mEffects.size();
7630
7631 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007632 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7633 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007634 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007635 }
7636 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007637 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007638}
7639
Eric Laurent59255e42011-07-27 19:49:51 -07007640// getEffectFromType_l() must be called with ThreadBase::mLock held
7641sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7642 const effect_uuid_t *type)
7643{
Eric Laurent59255e42011-07-27 19:49:51 -07007644 size_t size = mEffects.size();
7645
7646 for (size_t i = 0; i < size; i++) {
7647 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007648 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007649 }
7650 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007651 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007652}
7653
Mathias Agopian65ab4712010-07-14 17:59:35 -07007654// Must be called with EffectChain::mLock locked
7655void AudioFlinger::EffectChain::process_l()
7656{
Eric Laurentdac69112010-09-28 14:09:57 -07007657 sp<ThreadBase> thread = mThread.promote();
7658 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007659 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007660 return;
7661 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007662 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7663 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007664 // always process effects unless no more tracks are on the session and the effect tail
7665 // has been rendered
7666 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007667 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007668 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007669
Eric Laurent544fe9b2011-11-11 15:42:52 -08007670 if (!tracksOnSession && mTailBufferCount == 0) {
7671 doProcess = false;
7672 }
7673
7674 if (activeTrackCnt() == 0) {
7675 // if no track is active and the effect tail has not been rendered,
7676 // the input buffer must be cleared here as the mixer process will not do it
7677 if (tracksOnSession || mTailBufferCount > 0) {
7678 size_t numSamples = thread->frameCount() * thread->channelCount();
7679 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7680 if (mTailBufferCount > 0) {
7681 mTailBufferCount--;
7682 }
7683 }
7684 }
Eric Laurentdac69112010-09-28 14:09:57 -07007685 }
7686
Mathias Agopian65ab4712010-07-14 17:59:35 -07007687 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007688 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007689 for (size_t i = 0; i < size; i++) {
7690 mEffects[i]->process();
7691 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007692 }
7693 for (size_t i = 0; i < size; i++) {
7694 mEffects[i]->updateState();
7695 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007696}
7697
Eric Laurentcab11242010-07-15 12:50:15 -07007698// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007699status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007700{
7701 effect_descriptor_t desc = effect->desc();
7702 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7703
7704 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007705 effect->setChain(this);
7706 sp<ThreadBase> thread = mThread.promote();
7707 if (thread == 0) {
7708 return NO_INIT;
7709 }
7710 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007711
7712 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7713 // Auxiliary effects are inserted at the beginning of mEffects vector as
7714 // they are processed first and accumulated in chain input buffer
7715 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007716
Mathias Agopian65ab4712010-07-14 17:59:35 -07007717 // the input buffer for auxiliary effect contains mono samples in
7718 // 32 bit format. This is to avoid saturation in AudoMixer
7719 // accumulation stage. Saturation is done in EffectModule::process() before
7720 // calling the process in effect engine
7721 size_t numSamples = thread->frameCount();
7722 int32_t *buffer = new int32_t[numSamples];
7723 memset(buffer, 0, numSamples * sizeof(int32_t));
7724 effect->setInBuffer((int16_t *)buffer);
7725 // auxiliary effects output samples to chain input buffer for further processing
7726 // by insert effects
7727 effect->setOutBuffer(mInBuffer);
7728 } else {
7729 // Insert effects are inserted at the end of mEffects vector as they are processed
7730 // after track and auxiliary effects.
7731 // Insert effect order as a function of indicated preference:
7732 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7733 // another effect is present
7734 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7735 // last effect claiming first position
7736 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7737 // first effect claiming last position
7738 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7739 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7740 // already present
7741
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007742 size_t size = mEffects.size();
7743 size_t idx_insert = size;
7744 ssize_t idx_insert_first = -1;
7745 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007746
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007747 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007748 effect_descriptor_t d = mEffects[i]->desc();
7749 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7750 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7751 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7752 // check invalid effect chaining combinations
7753 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7754 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007755 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007756 return INVALID_OPERATION;
7757 }
7758 // remember position of first insert effect and by default
7759 // select this as insert position for new effect
7760 if (idx_insert == size) {
7761 idx_insert = i;
7762 }
7763 // remember position of last insert effect claiming
7764 // first position
7765 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7766 idx_insert_first = i;
7767 }
7768 // remember position of first insert effect claiming
7769 // last position
7770 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7771 idx_insert_last == -1) {
7772 idx_insert_last = i;
7773 }
7774 }
7775 }
7776
7777 // modify idx_insert from first position if needed
7778 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7779 if (idx_insert_last != -1) {
7780 idx_insert = idx_insert_last;
7781 } else {
7782 idx_insert = size;
7783 }
7784 } else {
7785 if (idx_insert_first != -1) {
7786 idx_insert = idx_insert_first + 1;
7787 }
7788 }
7789
7790 // always read samples from chain input buffer
7791 effect->setInBuffer(mInBuffer);
7792
7793 // if last effect in the chain, output samples to chain
7794 // output buffer, otherwise to chain input buffer
7795 if (idx_insert == size) {
7796 if (idx_insert != 0) {
7797 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7798 mEffects[idx_insert-1]->configure();
7799 }
7800 effect->setOutBuffer(mOutBuffer);
7801 } else {
7802 effect->setOutBuffer(mInBuffer);
7803 }
7804 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007805
Steve Block3856b092011-10-20 11:56:00 +01007806 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007807 }
7808 effect->configure();
7809 return NO_ERROR;
7810}
7811
Eric Laurentcab11242010-07-15 12:50:15 -07007812// removeEffect_l() must be called with PlaybackThread::mLock held
7813size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007814{
7815 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007816 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007817 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7818
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007819 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007820 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007821 // calling stop here will remove pre-processing effect from the audio HAL.
7822 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7823 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007824 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7825 mEffects[i]->state() == EffectModule::STOPPING) {
7826 mEffects[i]->stop();
7827 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007828 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7829 delete[] effect->inBuffer();
7830 } else {
7831 if (i == size - 1 && i != 0) {
7832 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7833 mEffects[i - 1]->configure();
7834 }
7835 }
7836 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007837 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007838 break;
7839 }
7840 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007841
7842 return mEffects.size();
7843}
7844
Eric Laurentcab11242010-07-15 12:50:15 -07007845// setDevice_l() must be called with PlaybackThread::mLock held
7846void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007847{
7848 size_t size = mEffects.size();
7849 for (size_t i = 0; i < size; i++) {
7850 mEffects[i]->setDevice(device);
7851 }
7852}
7853
Eric Laurentcab11242010-07-15 12:50:15 -07007854// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007855void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007856{
7857 size_t size = mEffects.size();
7858 for (size_t i = 0; i < size; i++) {
7859 mEffects[i]->setMode(mode);
7860 }
7861}
7862
Eric Laurentcab11242010-07-15 12:50:15 -07007863// setVolume_l() must be called with PlaybackThread::mLock held
7864bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007865{
7866 uint32_t newLeft = *left;
7867 uint32_t newRight = *right;
7868 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007869 int ctrlIdx = -1;
7870 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007871
Eric Laurentcab11242010-07-15 12:50:15 -07007872 // first update volume controller
7873 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007874 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007875 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7876 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007877 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007878 break;
7879 }
7880 }
7881
7882 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007883 if (hasControl) {
7884 *left = mNewLeftVolume;
7885 *right = mNewRightVolume;
7886 }
7887 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007888 }
7889
7890 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007891 mLeftVolume = newLeft;
7892 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007893
7894 // second get volume update from volume controller
7895 if (ctrlIdx >= 0) {
7896 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007897 mNewLeftVolume = newLeft;
7898 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007899 }
7900 // then indicate volume to all other effects in chain.
7901 // Pass altered volume to effects before volume controller
7902 // and requested volume to effects after controller
7903 uint32_t lVol = newLeft;
7904 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007905
Mathias Agopian65ab4712010-07-14 17:59:35 -07007906 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007907 if ((int)i == ctrlIdx) continue;
7908 // this also works for ctrlIdx == -1 when there is no volume controller
7909 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007910 lVol = *left;
7911 rVol = *right;
7912 }
7913 mEffects[i]->setVolume(&lVol, &rVol, false);
7914 }
7915 *left = newLeft;
7916 *right = newRight;
7917
7918 return hasControl;
7919}
7920
Mathias Agopian65ab4712010-07-14 17:59:35 -07007921status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7922{
7923 const size_t SIZE = 256;
7924 char buffer[SIZE];
7925 String8 result;
7926
7927 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7928 result.append(buffer);
7929
7930 bool locked = tryLock(mLock);
7931 // failed to lock - AudioFlinger is probably deadlocked
7932 if (!locked) {
7933 result.append("\tCould not lock mutex:\n");
7934 }
7935
Eric Laurentcab11242010-07-15 12:50:15 -07007936 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7937 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007938 mEffects.size(),
7939 (uint32_t)mInBuffer,
7940 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007941 mActiveTrackCnt);
7942 result.append(buffer);
7943 write(fd, result.string(), result.size());
7944
7945 for (size_t i = 0; i < mEffects.size(); ++i) {
7946 sp<EffectModule> effect = mEffects[i];
7947 if (effect != 0) {
7948 effect->dump(fd, args);
7949 }
7950 }
7951
7952 if (locked) {
7953 mLock.unlock();
7954 }
7955
7956 return NO_ERROR;
7957}
7958
Eric Laurent59255e42011-07-27 19:49:51 -07007959// must be called with ThreadBase::mLock held
7960void AudioFlinger::EffectChain::setEffectSuspended_l(
7961 const effect_uuid_t *type, bool suspend)
7962{
7963 sp<SuspendedEffectDesc> desc;
7964 // use effect type UUID timelow as key as there is no real risk of identical
7965 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007966 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007967 if (suspend) {
7968 if (index >= 0) {
7969 desc = mSuspendedEffects.valueAt(index);
7970 } else {
7971 desc = new SuspendedEffectDesc();
7972 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7973 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007974 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007975 }
7976 if (desc->mRefCount++ == 0) {
7977 sp<EffectModule> effect = getEffectIfEnabled(type);
7978 if (effect != 0) {
7979 desc->mEffect = effect;
7980 effect->setSuspended(true);
7981 effect->setEnabled(false);
7982 }
7983 }
7984 } else {
7985 if (index < 0) {
7986 return;
7987 }
7988 desc = mSuspendedEffects.valueAt(index);
7989 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007990 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007991 desc->mRefCount = 1;
7992 }
7993 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007994 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007995 if (desc->mEffect != 0) {
7996 sp<EffectModule> effect = desc->mEffect.promote();
7997 if (effect != 0) {
7998 effect->setSuspended(false);
7999 sp<EffectHandle> handle = effect->controlHandle();
8000 if (handle != 0) {
8001 effect->setEnabled(handle->enabled());
8002 }
8003 }
8004 desc->mEffect.clear();
8005 }
8006 mSuspendedEffects.removeItemsAt(index);
8007 }
8008 }
8009}
8010
8011// must be called with ThreadBase::mLock held
8012void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
8013{
8014 sp<SuspendedEffectDesc> desc;
8015
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008016 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07008017 if (suspend) {
8018 if (index >= 0) {
8019 desc = mSuspendedEffects.valueAt(index);
8020 } else {
8021 desc = new SuspendedEffectDesc();
8022 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01008023 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07008024 }
8025 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08008026 Vector< sp<EffectModule> > effects;
8027 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07008028 for (size_t i = 0; i < effects.size(); i++) {
8029 setEffectSuspended_l(&effects[i]->desc().type, true);
8030 }
8031 }
8032 } else {
8033 if (index < 0) {
8034 return;
8035 }
8036 desc = mSuspendedEffects.valueAt(index);
8037 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008038 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008039 desc->mRefCount = 1;
8040 }
8041 if (--desc->mRefCount == 0) {
8042 Vector<const effect_uuid_t *> types;
8043 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
8044 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
8045 continue;
8046 }
8047 types.add(&mSuspendedEffects.valueAt(i)->mType);
8048 }
8049 for (size_t i = 0; i < types.size(); i++) {
8050 setEffectSuspended_l(types[i], false);
8051 }
Steve Block3856b092011-10-20 11:56:00 +01008052 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008053 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
8054 }
8055 }
8056}
8057
Eric Laurent6bffdb82011-09-23 08:40:41 -07008058
8059// The volume effect is used for automated tests only
8060#ifndef OPENSL_ES_H_
8061static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
8062 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
8063const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
8064#endif //OPENSL_ES_H_
8065
Eric Laurentdb7c0792011-08-10 10:37:50 -07008066bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
8067{
8068 // auxiliary effects and visualizer are never suspended on output mix
8069 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8070 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07008071 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8072 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008073 return false;
8074 }
8075 return true;
8076}
8077
Glenn Kastend0539712012-01-30 12:56:03 -08008078void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07008079{
Glenn Kastend0539712012-01-30 12:56:03 -08008080 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07008081 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08008082 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8083 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07008084 }
Eric Laurent59255e42011-07-27 19:49:51 -07008085 }
Eric Laurent59255e42011-07-27 19:49:51 -07008086}
8087
8088sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8089 const effect_uuid_t *type)
8090{
Glenn Kasten090f0192012-01-30 13:00:02 -08008091 sp<EffectModule> effect = getEffectFromType_l(type);
8092 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008093}
8094
8095void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8096 bool enabled)
8097{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008098 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008099 if (enabled) {
8100 if (index < 0) {
8101 // if the effect is not suspend check if all effects are suspended
8102 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8103 if (index < 0) {
8104 return;
8105 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07008106 if (!isEffectEligibleForSuspend(effect->desc())) {
8107 return;
8108 }
Eric Laurent59255e42011-07-27 19:49:51 -07008109 setEffectSuspended_l(&effect->desc().type, enabled);
8110 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07008111 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008112 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07008113 return;
8114 }
Eric Laurent59255e42011-07-27 19:49:51 -07008115 }
Steve Block3856b092011-10-20 11:56:00 +01008116 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008117 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008118 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8119 // if effect is requested to suspended but was not yet enabled, supend it now.
8120 if (desc->mEffect == 0) {
8121 desc->mEffect = effect;
8122 effect->setEnabled(false);
8123 effect->setSuspended(true);
8124 }
8125 } else {
8126 if (index < 0) {
8127 return;
8128 }
Steve Block3856b092011-10-20 11:56:00 +01008129 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008130 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008131 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8132 desc->mEffect.clear();
8133 effect->setSuspended(false);
8134 }
8135}
8136
Mathias Agopian65ab4712010-07-14 17:59:35 -07008137#undef LOG_TAG
8138#define LOG_TAG "AudioFlinger"
8139
8140// ----------------------------------------------------------------------------
8141
8142status_t AudioFlinger::onTransact(
8143 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8144{
8145 return BnAudioFlinger::onTransact(code, data, reply, flags);
8146}
8147
Mathias Agopian65ab4712010-07-14 17:59:35 -07008148}; // namespace android