blob: 993192c32dddb2c6622804d6a93fba645681c238 [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 Kastena075db42012-03-06 11:22:44 -0800445 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700446 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800447 audio_io_handle_t output,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700448 int *sessionId,
449 status_t *status)
450{
451 sp<PlaybackThread::Track> track;
452 sp<TrackHandle> trackHandle;
453 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700454 status_t lStatus;
455 int lSessionId;
456
Glenn Kasten263709e2012-01-06 08:40:01 -0800457 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
458 // but if someone uses binder directly they could bypass that and cause us to crash
459 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000460 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700461 lStatus = BAD_VALUE;
462 goto Exit;
463 }
464
465 {
466 Mutex::Autolock _l(mLock);
467 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700468 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700469 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000470 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700471 lStatus = BAD_VALUE;
472 goto Exit;
473 }
474
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800475 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700476
Steve Block3856b092011-10-20 11:56:00 +0100477 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700478 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700479 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700480 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
481 if (mPlaybackThreads.keyAt(i) != output) {
482 // prevent same audio session on different output threads
483 uint32_t sessions = t->hasAudioSession(*sessionId);
484 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000485 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700486 lStatus = BAD_VALUE;
487 goto Exit;
488 }
489 // check if an effect with same session ID is waiting for a track to be created
490 if (sessions & PlaybackThread::EFFECT_SESSION) {
491 effectThread = t.get();
492 }
Eric Laurentde070132010-07-13 04:45:46 -0700493 }
494 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700495 lSessionId = *sessionId;
496 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700497 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700498 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700499 if (sessionId != NULL) {
500 *sessionId = lSessionId;
501 }
502 }
Steve Block3856b092011-10-20 11:56:00 +0100503 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700504
Glenn Kastena075db42012-03-06 11:22:44 -0800505 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700506 track = thread->createTrack_l(client, streamType, sampleRate, format,
John Grossman4ff14ba2012-02-08 16:37:41 -0800507 channelMask, frameCount, sharedBuffer, lSessionId, isTimed, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700508
509 // move effect chain to this output thread if an effect on same session was waiting
510 // for a track to be created
511 if (lStatus == NO_ERROR && effectThread != NULL) {
512 Mutex::Autolock _dl(thread->mLock);
513 Mutex::Autolock _sl(effectThread->mLock);
514 moveEffectChain_l(lSessionId, effectThread, thread, true);
515 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700516 }
517 if (lStatus == NO_ERROR) {
518 trackHandle = new TrackHandle(track);
519 } else {
520 // remove local strong reference to Client before deleting the Track so that the Client
521 // destructor is called by the TrackBase destructor with mLock held
522 client.clear();
523 track.clear();
524 }
525
526Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700527 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700528 *status = lStatus;
529 }
530 return trackHandle;
531}
532
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800533uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700534{
535 Mutex::Autolock _l(mLock);
536 PlaybackThread *thread = checkPlaybackThread_l(output);
537 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000538 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700539 return 0;
540 }
541 return thread->sampleRate();
542}
543
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800544int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700545{
546 Mutex::Autolock _l(mLock);
547 PlaybackThread *thread = checkPlaybackThread_l(output);
548 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000549 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700550 return 0;
551 }
552 return thread->channelCount();
553}
554
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800555audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700556{
557 Mutex::Autolock _l(mLock);
558 PlaybackThread *thread = checkPlaybackThread_l(output);
559 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000560 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800561 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700562 }
563 return thread->format();
564}
565
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800566size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700567{
568 Mutex::Autolock _l(mLock);
569 PlaybackThread *thread = checkPlaybackThread_l(output);
570 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000571 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700572 return 0;
573 }
574 return thread->frameCount();
575}
576
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800577uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700578{
579 Mutex::Autolock _l(mLock);
580 PlaybackThread *thread = checkPlaybackThread_l(output);
581 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000582 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700583 return 0;
584 }
585 return thread->latency();
586}
587
588status_t AudioFlinger::setMasterVolume(float value)
589{
Eric Laurenta1884f92011-08-23 08:25:03 -0700590 status_t ret = initCheck();
591 if (ret != NO_ERROR) {
592 return ret;
593 }
594
Mathias Agopian65ab4712010-07-14 17:59:35 -0700595 // check calling permissions
596 if (!settingsAllowed()) {
597 return PERMISSION_DENIED;
598 }
599
John Grossman4ff14ba2012-02-08 16:37:41 -0800600 float swmv = value;
601
Mathias Agopian65ab4712010-07-14 17:59:35 -0700602 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800603 if (MVS_NONE != mMasterVolumeSupportLvl) {
604 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
605 AutoMutex lock(mHardwareLock);
606 audio_hw_device_t *dev = mAudioHwDevs[i];
607
608 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
609 if (NULL != dev->set_master_volume) {
610 dev->set_master_volume(dev, value);
611 }
612 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800613 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800614
615 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700616 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700617
Eric Laurent93575202011-01-18 18:39:02 -0800618 Mutex::Autolock _l(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -0800619 mMasterVolume = value;
620 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800621 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700622 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700623
624 return NO_ERROR;
625}
626
Glenn Kastenf78aee72012-01-04 11:00:47 -0800627status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700628{
Eric Laurenta1884f92011-08-23 08:25:03 -0700629 status_t ret = initCheck();
630 if (ret != NO_ERROR) {
631 return ret;
632 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700633
634 // check calling permissions
635 if (!settingsAllowed()) {
636 return PERMISSION_DENIED;
637 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800638 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000639 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700640 return BAD_VALUE;
641 }
642
643 { // scope for the lock
644 AutoMutex lock(mHardwareLock);
645 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700646 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700647 mHardwareStatus = AUDIO_HW_IDLE;
648 }
649
650 if (NO_ERROR == ret) {
651 Mutex::Autolock _l(mLock);
652 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800653 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700654 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700655 }
656
657 return ret;
658}
659
660status_t AudioFlinger::setMicMute(bool state)
661{
Eric Laurenta1884f92011-08-23 08:25:03 -0700662 status_t ret = initCheck();
663 if (ret != NO_ERROR) {
664 return ret;
665 }
666
Mathias Agopian65ab4712010-07-14 17:59:35 -0700667 // check calling permissions
668 if (!settingsAllowed()) {
669 return PERMISSION_DENIED;
670 }
671
672 AutoMutex lock(mHardwareLock);
673 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700674 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700675 mHardwareStatus = AUDIO_HW_IDLE;
676 return ret;
677}
678
679bool AudioFlinger::getMicMute() const
680{
Eric Laurenta1884f92011-08-23 08:25:03 -0700681 status_t ret = initCheck();
682 if (ret != NO_ERROR) {
683 return false;
684 }
685
Dima Zavinfce7a472011-04-19 22:30:36 -0700686 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800687 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700688 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700689 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700690 mHardwareStatus = AUDIO_HW_IDLE;
691 return state;
692}
693
694status_t AudioFlinger::setMasterMute(bool muted)
695{
696 // check calling permissions
697 if (!settingsAllowed()) {
698 return PERMISSION_DENIED;
699 }
700
Eric Laurent93575202011-01-18 18:39:02 -0800701 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800702 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700703 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800704 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700705 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700706
707 return NO_ERROR;
708}
709
710float AudioFlinger::masterVolume() const
711{
Glenn Kasten98067102011-12-13 11:47:54 -0800712 Mutex::Autolock _l(mLock);
713 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700714}
715
John Grossman4ff14ba2012-02-08 16:37:41 -0800716float AudioFlinger::masterVolumeSW() const
717{
718 Mutex::Autolock _l(mLock);
719 return masterVolumeSW_l();
720}
721
Mathias Agopian65ab4712010-07-14 17:59:35 -0700722bool AudioFlinger::masterMute() const
723{
Glenn Kasten98067102011-12-13 11:47:54 -0800724 Mutex::Autolock _l(mLock);
725 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700726}
727
John Grossman4ff14ba2012-02-08 16:37:41 -0800728float AudioFlinger::masterVolume_l() const
729{
730 if (MVS_FULL == mMasterVolumeSupportLvl) {
731 float ret_val;
732 AutoMutex lock(mHardwareLock);
733
734 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800735 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
736 (NULL != mPrimaryHardwareDev->get_master_volume),
737 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800738
739 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
740 mHardwareStatus = AUDIO_HW_IDLE;
741 return ret_val;
742 }
743
744 return mMasterVolume;
745}
746
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800747status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
748 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700749{
750 // check calling permissions
751 if (!settingsAllowed()) {
752 return PERMISSION_DENIED;
753 }
754
Glenn Kasten263709e2012-01-06 08:40:01 -0800755 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000756 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700757 return BAD_VALUE;
758 }
759
760 AutoMutex lock(mLock);
761 PlaybackThread *thread = NULL;
762 if (output) {
763 thread = checkPlaybackThread_l(output);
764 if (thread == NULL) {
765 return BAD_VALUE;
766 }
767 }
768
769 mStreamTypes[stream].volume = value;
770
771 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800772 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700773 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700774 }
775 } else {
776 thread->setStreamVolume(stream, value);
777 }
778
779 return NO_ERROR;
780}
781
Glenn Kastenfff6d712012-01-12 16:38:12 -0800782status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700783{
784 // check calling permissions
785 if (!settingsAllowed()) {
786 return PERMISSION_DENIED;
787 }
788
Glenn Kasten263709e2012-01-06 08:40:01 -0800789 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700790 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000791 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700792 return BAD_VALUE;
793 }
794
Eric Laurent93575202011-01-18 18:39:02 -0800795 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796 mStreamTypes[stream].mute = muted;
797 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700798 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700799
800 return NO_ERROR;
801}
802
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800803float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700804{
Glenn Kasten263709e2012-01-06 08:40:01 -0800805 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700806 return 0.0f;
807 }
808
809 AutoMutex lock(mLock);
810 float volume;
811 if (output) {
812 PlaybackThread *thread = checkPlaybackThread_l(output);
813 if (thread == NULL) {
814 return 0.0f;
815 }
816 volume = thread->streamVolume(stream);
817 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800818 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700819 }
820
821 return volume;
822}
823
Glenn Kastenfff6d712012-01-12 16:38:12 -0800824bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700825{
Glenn Kasten263709e2012-01-06 08:40:01 -0800826 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700827 return true;
828 }
829
Glenn Kasten6637baa2012-01-09 09:40:36 -0800830 AutoMutex lock(mLock);
831 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700832}
833
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800834status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700835{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800836 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700837 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
838 // check calling permissions
839 if (!settingsAllowed()) {
840 return PERMISSION_DENIED;
841 }
842
Mathias Agopian65ab4712010-07-14 17:59:35 -0700843 // ioHandle == 0 means the parameters are global to the audio hardware interface
844 if (ioHandle == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700845 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800846 {
847 AutoMutex lock(mHardwareLock);
848 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700849 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
850 audio_hw_device_t *dev = mAudioHwDevs[i];
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800851 status_t result = dev->set_parameters(dev, keyValuePairs.string());
Dima Zavin799a70e2011-04-18 16:57:27 -0700852 final_result = result ?: final_result;
853 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700854 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800855 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700856 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
857 AudioParameter param = AudioParameter(keyValuePairs);
858 String8 value;
859 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
860 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700861 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
862 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700863 for (size_t i = 0; i < mRecordThreads.size(); i++) {
864 sp<RecordThread> thread = mRecordThreads.valueAt(i);
865 RecordThread::RecordTrack *track = thread->track();
866 if (track != NULL) {
867 audio_devices_t device = (audio_devices_t)(
868 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700869 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700870 thread->setEffectSuspended(FX_IID_AEC,
871 suspend,
872 track->sessionId());
873 thread->setEffectSuspended(FX_IID_NS,
874 suspend,
875 track->sessionId());
876 }
877 }
Eric Laurentbee53372011-08-29 12:42:48 -0700878 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700879 }
880 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700881 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700882 }
883
884 // hold a strong ref on thread in case closeOutput() or closeInput() is called
885 // and the thread is exited once the lock is released
886 sp<ThreadBase> thread;
887 {
888 Mutex::Autolock _l(mLock);
889 thread = checkPlaybackThread_l(ioHandle);
890 if (thread == NULL) {
891 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800892 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700893 // indicate output device change to all input threads for pre processing
894 AudioParameter param = AudioParameter(keyValuePairs);
895 int value;
896 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
897 for (size_t i = 0; i < mRecordThreads.size(); i++) {
898 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
899 }
900 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700901 }
902 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800903 if (thread != 0) {
904 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700905 }
906 return BAD_VALUE;
907}
908
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800909String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700910{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800911// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700912// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
913
914 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700915 String8 out_s8;
916
Dima Zavin799a70e2011-04-18 16:57:27 -0700917 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800918 char *s;
919 {
920 AutoMutex lock(mHardwareLock);
921 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700922 audio_hw_device_t *dev = mAudioHwDevs[i];
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800923 s = dev->get_parameters(dev, keys.string());
924 mHardwareStatus = AUDIO_HW_IDLE;
925 }
John Grossmanef7740b2012-02-09 11:28:36 -0800926 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700927 free(s);
928 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700929 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700930 }
931
932 Mutex::Autolock _l(mLock);
933
934 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
935 if (playbackThread != NULL) {
936 return playbackThread->getParameters(keys);
937 }
938 RecordThread *recordThread = checkRecordThread_l(ioHandle);
939 if (recordThread != NULL) {
940 return recordThread->getParameters(keys);
941 }
942 return String8("");
943}
944
Glenn Kastenf587ba52012-01-26 16:25:10 -0800945size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700946{
Eric Laurenta1884f92011-08-23 08:25:03 -0700947 status_t ret = initCheck();
948 if (ret != NO_ERROR) {
949 return 0;
950 }
951
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800952 AutoMutex lock(mHardwareLock);
953 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
954 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
955 mHardwareStatus = AUDIO_HW_IDLE;
956 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700957}
958
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800959unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700960{
961 if (ioHandle == 0) {
962 return 0;
963 }
964
965 Mutex::Autolock _l(mLock);
966
967 RecordThread *recordThread = checkRecordThread_l(ioHandle);
968 if (recordThread != NULL) {
969 return recordThread->getInputFramesLost();
970 }
971 return 0;
972}
973
974status_t AudioFlinger::setVoiceVolume(float value)
975{
Eric Laurenta1884f92011-08-23 08:25:03 -0700976 status_t ret = initCheck();
977 if (ret != NO_ERROR) {
978 return ret;
979 }
980
Mathias Agopian65ab4712010-07-14 17:59:35 -0700981 // check calling permissions
982 if (!settingsAllowed()) {
983 return PERMISSION_DENIED;
984 }
985
986 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800987 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700988 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700989 mHardwareStatus = AUDIO_HW_IDLE;
990
991 return ret;
992}
993
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800994status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
995 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700996{
997 status_t status;
998
999 Mutex::Autolock _l(mLock);
1000
1001 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1002 if (playbackThread != NULL) {
1003 return playbackThread->getRenderPosition(halFrames, dspFrames);
1004 }
1005
1006 return BAD_VALUE;
1007}
1008
1009void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1010{
1011
1012 Mutex::Autolock _l(mLock);
1013
Glenn Kastenbb001922012-02-03 11:10:26 -08001014 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001015 if (mNotificationClients.indexOfKey(pid) < 0) {
1016 sp<NotificationClient> notificationClient = new NotificationClient(this,
1017 client,
1018 pid);
Steve Block3856b092011-10-20 11:56:00 +01001019 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001020
1021 mNotificationClients.add(pid, notificationClient);
1022
1023 sp<IBinder> binder = client->asBinder();
1024 binder->linkToDeath(notificationClient);
1025
1026 // the config change is always sent from playback or record threads to avoid deadlock
1027 // with AudioSystem::gLock
1028 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1029 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1030 }
1031
1032 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1033 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1034 }
1035 }
1036}
1037
1038void AudioFlinger::removeNotificationClient(pid_t pid)
1039{
1040 Mutex::Autolock _l(mLock);
1041
Glenn Kastena3b09252012-01-20 09:19:01 -08001042 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001043
Steve Block3856b092011-10-20 11:56:00 +01001044 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001045 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001046 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001047 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001048 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001049 ALOGV(" pid %d @ %d", ref->mPid, i);
1050 if (ref->mPid == pid) {
1051 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001052 mAudioSessionRefs.removeAt(i);
1053 delete ref;
1054 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001055 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001056 } else {
1057 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001058 }
1059 }
1060 if (removed) {
1061 purgeStaleEffects_l();
1062 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001063}
1064
1065// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001066void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001067{
1068 size_t size = mNotificationClients.size();
1069 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001070 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1071 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001072 }
1073}
1074
1075// removeClient_l() must be called with AudioFlinger::mLock held
1076void AudioFlinger::removeClient_l(pid_t pid)
1077{
Steve Block3856b092011-10-20 11:56:00 +01001078 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001079 mClients.removeItem(pid);
1080}
1081
1082
1083// ----------------------------------------------------------------------------
1084
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001085AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1086 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001087 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001088 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001089 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
1090 // mChannelMask
1091 mChannelCount(0),
1092 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1093 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001094 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001095 mDevice(device),
1096 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001097{
1098}
1099
1100AudioFlinger::ThreadBase::~ThreadBase()
1101{
1102 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001103 // do not lock the mutex in destructor
1104 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001105 if (mPowerManager != 0) {
1106 sp<IBinder> binder = mPowerManager->asBinder();
1107 binder->unlinkToDeath(mDeathRecipient);
1108 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001109}
1110
1111void AudioFlinger::ThreadBase::exit()
1112{
Steve Block3856b092011-10-20 11:56:00 +01001113 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001114 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001115 // This lock prevents the following race in thread (uniprocessor for illustration):
1116 // if (!exitPending()) {
1117 // // context switch from here to exit()
1118 // // exit() calls requestExit(), what exitPending() observes
1119 // // exit() calls signal(), which is dropped since no waiters
1120 // // context switch back from exit() to here
1121 // mWaitWorkCV.wait(...);
1122 // // now thread is hung
1123 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001124 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001125 requestExit();
1126 mWaitWorkCV.signal();
1127 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001128 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1129 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001130 requestExitAndWait();
1131}
1132
Mathias Agopian65ab4712010-07-14 17:59:35 -07001133status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1134{
1135 status_t status;
1136
Steve Block3856b092011-10-20 11:56:00 +01001137 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001138 Mutex::Autolock _l(mLock);
1139
1140 mNewParameters.add(keyValuePairs);
1141 mWaitWorkCV.signal();
1142 // wait condition with timeout in case the thread loop has exited
1143 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001144 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001145 status = mParamStatus;
1146 mWaitWorkCV.signal();
1147 } else {
1148 status = TIMED_OUT;
1149 }
1150 return status;
1151}
1152
1153void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1154{
1155 Mutex::Autolock _l(mLock);
1156 sendConfigEvent_l(event, param);
1157}
1158
1159// sendConfigEvent_l() must be called with ThreadBase::mLock held
1160void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1161{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001162 ConfigEvent configEvent;
1163 configEvent.mEvent = event;
1164 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001165 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001166 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001167 mWaitWorkCV.signal();
1168}
1169
1170void AudioFlinger::ThreadBase::processConfigEvents()
1171{
1172 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001173 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001174 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001175 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001176 mConfigEvents.removeAt(0);
1177 // release mLock before locking AudioFlinger mLock: lock order is always
1178 // AudioFlinger then ThreadBase to avoid cross deadlock
1179 mLock.unlock();
1180 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001181 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001182 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001183 mLock.lock();
1184 }
1185 mLock.unlock();
1186}
1187
1188status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1189{
1190 const size_t SIZE = 256;
1191 char buffer[SIZE];
1192 String8 result;
1193
1194 bool locked = tryLock(mLock);
1195 if (!locked) {
1196 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1197 write(fd, buffer, strlen(buffer));
1198 }
1199
Eric Laurent612bbb52012-03-14 15:03:26 -07001200 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1201 result.append(buffer);
1202 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1203 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001204 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1205 result.append(buffer);
1206 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1207 result.append(buffer);
1208 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1209 result.append(buffer);
1210 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1211 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001212 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1213 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001214 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1215 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001216 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001217 result.append(buffer);
1218
1219 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1220 result.append(buffer);
1221 result.append(" Index Command");
1222 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1223 snprintf(buffer, SIZE, "\n %02d ", i);
1224 result.append(buffer);
1225 result.append(mNewParameters[i]);
1226 }
1227
1228 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1229 result.append(buffer);
1230 snprintf(buffer, SIZE, " Index event param\n");
1231 result.append(buffer);
1232 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001233 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001234 result.append(buffer);
1235 }
1236 result.append("\n");
1237
1238 write(fd, result.string(), result.size());
1239
1240 if (locked) {
1241 mLock.unlock();
1242 }
1243 return NO_ERROR;
1244}
1245
Eric Laurent1d2bff02011-07-24 17:49:51 -07001246status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1247{
1248 const size_t SIZE = 256;
1249 char buffer[SIZE];
1250 String8 result;
1251
1252 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1253 write(fd, buffer, strlen(buffer));
1254
1255 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1256 sp<EffectChain> chain = mEffectChains[i];
1257 if (chain != 0) {
1258 chain->dump(fd, args);
1259 }
1260 }
1261 return NO_ERROR;
1262}
1263
Eric Laurentfeb0db62011-07-22 09:04:31 -07001264void AudioFlinger::ThreadBase::acquireWakeLock()
1265{
1266 Mutex::Autolock _l(mLock);
1267 acquireWakeLock_l();
1268}
1269
1270void AudioFlinger::ThreadBase::acquireWakeLock_l()
1271{
1272 if (mPowerManager == 0) {
1273 // use checkService() to avoid blocking if power service is not up yet
1274 sp<IBinder> binder =
1275 defaultServiceManager()->checkService(String16("power"));
1276 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001277 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001278 } else {
1279 mPowerManager = interface_cast<IPowerManager>(binder);
1280 binder->linkToDeath(mDeathRecipient);
1281 }
1282 }
1283 if (mPowerManager != 0) {
1284 sp<IBinder> binder = new BBinder();
1285 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1286 binder,
1287 String16(mName));
1288 if (status == NO_ERROR) {
1289 mWakeLockToken = binder;
1290 }
Steve Block3856b092011-10-20 11:56:00 +01001291 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001292 }
1293}
1294
1295void AudioFlinger::ThreadBase::releaseWakeLock()
1296{
1297 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001298 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001299}
1300
1301void AudioFlinger::ThreadBase::releaseWakeLock_l()
1302{
1303 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001304 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001305 if (mPowerManager != 0) {
1306 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1307 }
1308 mWakeLockToken.clear();
1309 }
1310}
1311
1312void AudioFlinger::ThreadBase::clearPowerManager()
1313{
1314 Mutex::Autolock _l(mLock);
1315 releaseWakeLock_l();
1316 mPowerManager.clear();
1317}
1318
1319void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1320{
1321 sp<ThreadBase> thread = mThread.promote();
1322 if (thread != 0) {
1323 thread->clearPowerManager();
1324 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001325 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001326}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001327
Eric Laurent59255e42011-07-27 19:49:51 -07001328void AudioFlinger::ThreadBase::setEffectSuspended(
1329 const effect_uuid_t *type, bool suspend, int sessionId)
1330{
1331 Mutex::Autolock _l(mLock);
1332 setEffectSuspended_l(type, suspend, sessionId);
1333}
1334
1335void AudioFlinger::ThreadBase::setEffectSuspended_l(
1336 const effect_uuid_t *type, bool suspend, int sessionId)
1337{
Glenn Kasten090f0192012-01-30 13:00:02 -08001338 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001339 if (chain != 0) {
1340 if (type != NULL) {
1341 chain->setEffectSuspended_l(type, suspend);
1342 } else {
1343 chain->setEffectSuspendedAll_l(suspend);
1344 }
1345 }
1346
1347 updateSuspendedSessions_l(type, suspend, sessionId);
1348}
1349
1350void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1351{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001352 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001353 if (index < 0) {
1354 return;
1355 }
1356
1357 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1358 mSuspendedSessions.editValueAt(index);
1359
1360 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001361 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001362 for (int j = 0; j < desc->mRefCount; j++) {
1363 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1364 chain->setEffectSuspendedAll_l(true);
1365 } else {
Steve Block3856b092011-10-20 11:56:00 +01001366 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001367 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001368 chain->setEffectSuspended_l(&desc->mType, true);
1369 }
1370 }
1371 }
1372}
1373
Eric Laurent59255e42011-07-27 19:49:51 -07001374void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1375 bool suspend,
1376 int sessionId)
1377{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001378 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001379
1380 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1381
1382 if (suspend) {
1383 if (index >= 0) {
1384 sessionEffects = mSuspendedSessions.editValueAt(index);
1385 } else {
1386 mSuspendedSessions.add(sessionId, sessionEffects);
1387 }
1388 } else {
1389 if (index < 0) {
1390 return;
1391 }
1392 sessionEffects = mSuspendedSessions.editValueAt(index);
1393 }
1394
1395
1396 int key = EffectChain::kKeyForSuspendAll;
1397 if (type != NULL) {
1398 key = type->timeLow;
1399 }
1400 index = sessionEffects.indexOfKey(key);
1401
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001402 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001403 if (suspend) {
1404 if (index >= 0) {
1405 desc = sessionEffects.valueAt(index);
1406 } else {
1407 desc = new SuspendedSessionDesc();
1408 if (type != NULL) {
1409 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1410 }
1411 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001412 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001413 }
1414 desc->mRefCount++;
1415 } else {
1416 if (index < 0) {
1417 return;
1418 }
1419 desc = sessionEffects.valueAt(index);
1420 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001421 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001422 sessionEffects.removeItemsAt(index);
1423 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001424 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001425 sessionId);
1426 mSuspendedSessions.removeItem(sessionId);
1427 }
1428 }
1429 }
1430 if (!sessionEffects.isEmpty()) {
1431 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1432 }
1433}
1434
1435void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1436 bool enabled,
1437 int sessionId)
1438{
1439 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001440 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1441}
Eric Laurent59255e42011-07-27 19:49:51 -07001442
Eric Laurenta85a74a2011-10-19 11:44:54 -07001443void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1444 bool enabled,
1445 int sessionId)
1446{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001447 if (mType != RECORD) {
1448 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1449 // another session. This gives the priority to well behaved effect control panels
1450 // and applications not using global effects.
1451 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1452 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1453 }
1454 }
Eric Laurent59255e42011-07-27 19:49:51 -07001455
1456 sp<EffectChain> chain = getEffectChain_l(sessionId);
1457 if (chain != 0) {
1458 chain->checkSuspendOnEffectEnabled(effect, enabled);
1459 }
1460}
1461
Mathias Agopian65ab4712010-07-14 17:59:35 -07001462// ----------------------------------------------------------------------------
1463
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001464AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1465 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001466 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001467 uint32_t device,
1468 type_t type)
1469 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001470 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1471 // Assumes constructor is called by AudioFlinger with it's mLock held,
1472 // but it would be safer to explicitly pass initial masterMute as parameter
1473 mMasterMute(audioFlinger->masterMute_l()),
1474 // mStreamTypes[] initialized in constructor body
1475 mOutput(output),
1476 // Assumes constructor is called by AudioFlinger with it's mLock held,
1477 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001478 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001479 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001480 mMixerStatus(MIXER_IDLE),
Glenn Kasten66fcab92012-02-24 14:59:21 -08001481 mPrevMixerStatus(MIXER_IDLE),
1482 standbyDelay(AudioFlinger::mStandbyTimeInNsecs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001483{
Glenn Kasten480b4682012-02-28 12:30:08 -08001484 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001485
Mathias Agopian65ab4712010-07-14 17:59:35 -07001486 readOutputParameters();
1487
Glenn Kasten263709e2012-01-06 08:40:01 -08001488 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001489 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1490 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1491 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001492 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1493 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001494 // initialized by stream_type_t default constructor
1495 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001496 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001497 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1498 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001499}
1500
1501AudioFlinger::PlaybackThread::~PlaybackThread()
1502{
1503 delete [] mMixBuffer;
1504}
1505
1506status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1507{
1508 dumpInternals(fd, args);
1509 dumpTracks(fd, args);
1510 dumpEffectChains(fd, args);
1511 return NO_ERROR;
1512}
1513
1514status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1515{
1516 const size_t SIZE = 256;
1517 char buffer[SIZE];
1518 String8 result;
1519
1520 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1521 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001522 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 -07001523 for (size_t i = 0; i < mTracks.size(); ++i) {
1524 sp<Track> track = mTracks[i];
1525 if (track != 0) {
1526 track->dump(buffer, SIZE);
1527 result.append(buffer);
1528 }
1529 }
1530
1531 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1532 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001533 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 -07001534 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001535 sp<Track> track = mActiveTracks[i].promote();
1536 if (track != 0) {
1537 track->dump(buffer, SIZE);
1538 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001539 }
1540 }
1541 write(fd, result.string(), result.size());
1542 return NO_ERROR;
1543}
1544
Mathias Agopian65ab4712010-07-14 17:59:35 -07001545status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1546{
1547 const size_t SIZE = 256;
1548 char buffer[SIZE];
1549 String8 result;
1550
1551 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1552 result.append(buffer);
1553 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1554 result.append(buffer);
1555 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1556 result.append(buffer);
1557 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1558 result.append(buffer);
1559 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1560 result.append(buffer);
1561 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1562 result.append(buffer);
1563 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1564 result.append(buffer);
1565 write(fd, result.string(), result.size());
1566
1567 dumpBase(fd, args);
1568
1569 return NO_ERROR;
1570}
1571
1572// Thread virtuals
1573status_t AudioFlinger::PlaybackThread::readyToRun()
1574{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001575 status_t status = initCheck();
1576 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001577 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001578 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001579 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001580 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001581 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001582}
1583
1584void AudioFlinger::PlaybackThread::onFirstRef()
1585{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001586 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001587}
1588
1589// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1590sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1591 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001592 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001593 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001594 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001595 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001596 int frameCount,
1597 const sp<IMemory>& sharedBuffer,
1598 int sessionId,
John Grossman4ff14ba2012-02-08 16:37:41 -08001599 bool isTimed,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600 status_t *status)
1601{
1602 sp<Track> track;
1603 status_t lStatus;
1604
1605 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001606 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1607 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001608 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001609 "for output %p with format %d",
1610 sampleRate, format, channelMask, mOutput, mFormat);
1611 lStatus = BAD_VALUE;
1612 goto Exit;
1613 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001614 }
1615 } else {
1616 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1617 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001618 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001619 lStatus = BAD_VALUE;
1620 goto Exit;
1621 }
1622 }
1623
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001624 lStatus = initCheck();
1625 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001626 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001627 goto Exit;
1628 }
1629
1630 { // scope for mLock
1631 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001632
1633 // all tracks in same audio session must share the same routing strategy otherwise
1634 // conflicts will happen when tracks are moved from one output to another by audio policy
1635 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001636 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001637 for (size_t i = 0; i < mTracks.size(); ++i) {
1638 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001639 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001640 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001641 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001642 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001643 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001644 lStatus = BAD_VALUE;
1645 goto Exit;
1646 }
1647 }
1648 }
1649
John Grossman4ff14ba2012-02-08 16:37:41 -08001650 if (!isTimed) {
1651 track = new Track(this, client, streamType, sampleRate, format,
1652 channelMask, frameCount, sharedBuffer, sessionId);
1653 } else {
1654 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1655 channelMask, frameCount, sharedBuffer, sessionId);
1656 }
1657 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001658 lStatus = NO_MEMORY;
1659 goto Exit;
1660 }
1661 mTracks.add(track);
1662
1663 sp<EffectChain> chain = getEffectChain_l(sessionId);
1664 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001665 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001666 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001667 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001668 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001669 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001670
1671 // invalidate track immediately if the stream type was moved to another thread since
1672 // createTrack() was called by the client process.
1673 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001674 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001675 this, streamType);
Eric Laurent9f6530f2011-08-30 10:18:54 -07001676 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1677 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001678 }
1679 lStatus = NO_ERROR;
1680
1681Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001682 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001683 *status = lStatus;
1684 }
1685 return track;
1686}
1687
1688uint32_t AudioFlinger::PlaybackThread::latency() const
1689{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001690 Mutex::Autolock _l(mLock);
1691 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001692 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001693 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001694 return 0;
1695 }
1696}
1697
Glenn Kasten6637baa2012-01-09 09:40:36 -08001698void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001699{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001700 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001701 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001702}
1703
Glenn Kasten6637baa2012-01-09 09:40:36 -08001704void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001705{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001706 Mutex::Autolock _l(mLock);
1707 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001708}
1709
Glenn Kasten6637baa2012-01-09 09:40:36 -08001710void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001711{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001712 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001713 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001714}
1715
Glenn Kasten6637baa2012-01-09 09:40:36 -08001716void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001717{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001718 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001719 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001720}
1721
Glenn Kastenfff6d712012-01-12 16:38:12 -08001722float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001723{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001724 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001725 return mStreamTypes[stream].volume;
1726}
1727
Mathias Agopian65ab4712010-07-14 17:59:35 -07001728// addTrack_l() must be called with ThreadBase::mLock held
1729status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1730{
1731 status_t status = ALREADY_EXISTS;
1732
1733 // set retry count for buffer fill
1734 track->mRetryCount = kMaxTrackStartupRetries;
1735 if (mActiveTracks.indexOf(track) < 0) {
1736 // the track is newly added, make sure it fills up all its
1737 // buffers before playing. This is to ensure the client will
1738 // effectively get the latency it requested.
1739 track->mFillingUpStatus = Track::FS_FILLING;
1740 track->mResetDone = false;
1741 mActiveTracks.add(track);
1742 if (track->mainBuffer() != mMixBuffer) {
1743 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1744 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001745 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001746 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001747 }
1748 }
1749
1750 status = NO_ERROR;
1751 }
1752
Steve Block3856b092011-10-20 11:56:00 +01001753 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001754 mWaitWorkCV.broadcast();
1755
1756 return status;
1757}
1758
1759// destroyTrack_l() must be called with ThreadBase::mLock held
1760void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1761{
1762 track->mState = TrackBase::TERMINATED;
1763 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001764 removeTrack_l(track);
1765 }
1766}
1767
1768void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1769{
1770 mTracks.remove(track);
1771 deleteTrackName_l(track->name());
1772 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1773 if (chain != 0) {
1774 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001775 }
1776}
1777
1778String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1779{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001780 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001781 char *s;
1782
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001783 Mutex::Autolock _l(mLock);
1784 if (initCheck() != NO_ERROR) {
1785 return out_s8;
1786 }
1787
Dima Zavin799a70e2011-04-18 16:57:27 -07001788 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001789 out_s8 = String8(s);
1790 free(s);
1791 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001792}
1793
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001794// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001795void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1796 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001797 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001798
Steve Block3856b092011-10-20 11:56:00 +01001799 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001800
1801 switch (event) {
1802 case AudioSystem::OUTPUT_OPENED:
1803 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001804 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001805 desc.samplingRate = mSampleRate;
1806 desc.format = mFormat;
1807 desc.frameCount = mFrameCount;
1808 desc.latency = latency();
1809 param2 = &desc;
1810 break;
1811
1812 case AudioSystem::STREAM_CONFIG_CHANGED:
1813 param2 = &param;
1814 case AudioSystem::OUTPUT_CLOSED:
1815 default:
1816 break;
1817 }
1818 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1819}
1820
1821void AudioFlinger::PlaybackThread::readOutputParameters()
1822{
Dima Zavin799a70e2011-04-18 16:57:27 -07001823 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001824 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1825 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001826 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001827 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001828 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001829
1830 // FIXME - Current mixer implementation only supports stereo output: Always
1831 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001832 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833 mMixBuffer = new int16_t[mFrameCount * 2];
1834 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1835
Eric Laurentde070132010-07-13 04:45:46 -07001836 // force reconfiguration of effect chains and engines to take new buffer size and audio
1837 // parameters into account
1838 // Note that mLock is not held when readOutputParameters() is called from the constructor
1839 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1840 // matter.
1841 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1842 Vector< sp<EffectChain> > effectChains = mEffectChains;
1843 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001844 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001845 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001846}
1847
1848status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1849{
Glenn Kastena0d68332012-01-27 16:47:15 -08001850 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001851 return BAD_VALUE;
1852 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001853 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001854 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001855 return INVALID_OPERATION;
1856 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001857 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001858
Dima Zavin799a70e2011-04-18 16:57:27 -07001859 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001860}
1861
Eric Laurent39e94f82010-07-28 01:32:47 -07001862uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001863{
1864 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001865 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001866 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001867 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001868 }
1869
1870 for (size_t i = 0; i < mTracks.size(); ++i) {
1871 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001872 if (sessionId == track->sessionId() &&
1873 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001874 result |= TRACK_SESSION;
1875 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001876 }
1877 }
1878
Eric Laurent39e94f82010-07-28 01:32:47 -07001879 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001880}
1881
Eric Laurentde070132010-07-13 04:45:46 -07001882uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1883{
Dima Zavinfce7a472011-04-19 22:30:36 -07001884 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001885 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001886 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1887 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001888 }
1889 for (size_t i = 0; i < mTracks.size(); i++) {
1890 sp<Track> track = mTracks[i];
1891 if (sessionId == track->sessionId() &&
1892 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001893 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07001894 }
1895 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001896 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001897}
1898
Mathias Agopian65ab4712010-07-14 17:59:35 -07001899
Glenn Kastenaed850d2012-01-26 09:46:34 -08001900AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001901{
1902 Mutex::Autolock _l(mLock);
1903 return mOutput;
1904}
1905
1906AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1907{
1908 Mutex::Autolock _l(mLock);
1909 AudioStreamOut *output = mOutput;
1910 mOutput = NULL;
1911 return output;
1912}
1913
1914// this method must always be called either with ThreadBase mLock held or inside the thread loop
1915audio_stream_t* AudioFlinger::PlaybackThread::stream()
1916{
1917 if (mOutput == NULL) {
1918 return NULL;
1919 }
1920 return &mOutput->stream->common;
1921}
1922
Eric Laurent162b40b2011-12-05 09:47:19 -08001923uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1924{
1925 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1926 // decoding and transfer time. So sleeping for half of the latency would likely cause
1927 // underruns
1928 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1929 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1930 } else {
1931 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1932 }
1933}
1934
Mathias Agopian65ab4712010-07-14 17:59:35 -07001935// ----------------------------------------------------------------------------
1936
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001937AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001938 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten000f0e32012-03-01 17:10:56 -08001939 : PlaybackThread(audioFlinger, output, id, device, type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001940{
Glenn Kasten000f0e32012-03-01 17:10:56 -08001941 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001942 // FIXME - Current mixer implementation only supports stereo output
1943 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001944 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001945 }
1946}
1947
1948AudioFlinger::MixerThread::~MixerThread()
1949{
1950 delete mAudioMixer;
1951}
1952
Glenn Kasten83efdd02012-02-24 07:21:32 -08001953class CpuStats {
1954public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08001955 CpuStats();
1956 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08001957#ifdef DEBUG_CPU_USAGE
1958private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08001959 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
1960 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
1961
1962 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
1963
1964 int mCpuNum; // thread's current CPU number
1965 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08001966#endif
1967};
1968
Glenn Kasten190a46f2012-03-06 11:27:10 -08001969CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08001970#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08001971 : mCpuNum(-1), mCpukHz(-1)
1972#endif
1973{
1974}
1975
1976void CpuStats::sample(const String8 &title) {
1977#ifdef DEBUG_CPU_USAGE
1978 // get current thread's delta CPU time in wall clock ns
1979 double wcNs;
1980 bool valid = mCpuUsage.sampleAndEnable(wcNs);
1981
1982 // record sample for wall clock statistics
1983 if (valid) {
1984 mWcStats.sample(wcNs);
1985 }
1986
1987 // get the current CPU number
1988 int cpuNum = sched_getcpu();
1989
1990 // get the current CPU frequency in kHz
1991 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
1992
1993 // check if either CPU number or frequency changed
1994 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
1995 mCpuNum = cpuNum;
1996 mCpukHz = cpukHz;
1997 // ignore sample for purposes of cycles
1998 valid = false;
1999 }
2000
2001 // if no change in CPU number or frequency, then record sample for cycle statistics
2002 if (valid && mCpukHz > 0) {
2003 double cycles = wcNs * cpukHz * 0.000001;
2004 mHzStats.sample(cycles);
2005 }
2006
2007 unsigned n = mWcStats.n();
2008 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002009 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002010 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002011 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2012 double perLoop = elapsed / (double) n;
2013 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002014 double perLoop1k = perLoop * 0.001;
2015 double mean = mWcStats.mean();
2016 double stddev = mWcStats.stddev();
2017 double minimum = mWcStats.minimum();
2018 double maximum = mWcStats.maximum();
2019 double meanCycles = mHzStats.mean();
2020 double stddevCycles = mHzStats.stddev();
2021 double minCycles = mHzStats.minimum();
2022 double maxCycles = mHzStats.maximum();
2023 mCpuUsage.resetElapsed();
2024 mWcStats.reset();
2025 mHzStats.reset();
2026 ALOGD("CPU usage for %s over past %.1f secs\n"
2027 " (%u mixer loops at %.1f mean ms per loop):\n"
2028 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2029 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2030 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2031 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002032 elapsed * .000000001, n, perLoop * .000001,
2033 mean * .001,
2034 stddev * .001,
2035 minimum * .001,
2036 maximum * .001,
2037 mean / perLoop100,
2038 stddev / perLoop100,
2039 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002040 maximum / perLoop100,
2041 meanCycles / perLoop1k,
2042 stddevCycles / perLoop1k,
2043 minCycles / perLoop1k,
2044 maxCycles / perLoop1k);
2045
Glenn Kasten83efdd02012-02-24 07:21:32 -08002046 }
2047 }
2048#endif
2049};
2050
Glenn Kasten37d825e2012-02-24 07:21:48 -08002051void AudioFlinger::PlaybackThread::checkSilentMode_l()
2052{
2053 if (!mMasterMute) {
2054 char value[PROPERTY_VALUE_MAX];
2055 if (property_get("ro.audio.silent", value, "0") > 0) {
2056 char *endptr;
2057 unsigned long ul = strtoul(value, &endptr, 0);
2058 if (*endptr == '\0' && ul != 0) {
2059 ALOGD("Silence is golden");
2060 // The setprop command will not allow a property to be changed after
2061 // the first time it is set, so we don't have to worry about un-muting.
2062 setMasterMute_l(true);
2063 }
2064 }
2065 }
2066}
2067
Glenn Kasten000f0e32012-03-01 17:10:56 -08002068bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002069{
2070 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002071
Glenn Kasten000f0e32012-03-01 17:10:56 -08002072 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002073
2074 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002075 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002076if (mType == MIXER) {
2077 longStandbyExit = false;
2078}
Glenn Kasten688a6402012-02-29 07:57:06 -08002079
Glenn Kasten000f0e32012-03-01 17:10:56 -08002080 // DUPLICATING
2081 // FIXME could this be made local to while loop?
2082 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002083
Glenn Kasten66fcab92012-02-24 14:59:21 -08002084 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002085 sleepTime = idleSleepTime;
2086
2087if (mType == MIXER) {
2088 sleepTimeShift = 0;
2089}
2090
Glenn Kasten83efdd02012-02-24 07:21:32 -08002091 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002092 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002093
Eric Laurentfeb0db62011-07-22 09:04:31 -07002094 acquireWakeLock();
2095
Mathias Agopian65ab4712010-07-14 17:59:35 -07002096 while (!exitPending())
2097 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002098 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002099
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002100 Vector< sp<EffectChain> > effectChains;
2101
Mathias Agopian65ab4712010-07-14 17:59:35 -07002102 processConfigEvents();
2103
Mathias Agopian65ab4712010-07-14 17:59:35 -07002104 { // scope for mLock
2105
2106 Mutex::Autolock _l(mLock);
2107
2108 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002109 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002110 }
2111
Glenn Kastenfa26a852012-03-06 11:28:04 -08002112 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002113
Mathias Agopian65ab4712010-07-14 17:59:35 -07002114 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002115 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002116 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002117 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002118
2119 threadLoop_standby();
2120
Mathias Agopian65ab4712010-07-14 17:59:35 -07002121 mStandby = true;
2122 mBytesWritten = 0;
2123 }
2124
Glenn Kasten3e074702012-02-28 18:40:35 -08002125 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002126 // we're about to wait, flush the binder command buffer
2127 IPCThreadState::self()->flushCommands();
2128
Glenn Kastenfa26a852012-03-06 11:28:04 -08002129 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002130
Mathias Agopian65ab4712010-07-14 17:59:35 -07002131 if (exitPending()) break;
2132
Eric Laurentfeb0db62011-07-22 09:04:31 -07002133 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002134 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002135 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002136 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002137 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002138 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002139
Eric Laurent27741442012-01-17 19:20:12 -08002140 mPrevMixerStatus = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002141
Glenn Kasten37d825e2012-02-24 07:21:48 -08002142 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002143
Glenn Kasten000f0e32012-03-01 17:10:56 -08002144 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002145 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002146 if (mType == MIXER) {
2147 sleepTimeShift = 0;
2148 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002149
Mathias Agopian65ab4712010-07-14 17:59:35 -07002150 continue;
2151 }
2152 }
2153
Glenn Kastenfec279f2012-03-08 07:47:15 -08002154 mixer_state newMixerStatus = prepareTracks_l(&tracksToRemove);
2155 // Shift in the new status; this could be a queue if it's
2156 // useful to filter the mixer status over several cycles.
2157 mPrevMixerStatus = mMixerStatus;
2158 mMixerStatus = newMixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002159
2160 // prevent any changes in effect chain list and in each effect chain
2161 // during mixing and effect process as the audio buffers could be deleted
2162 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002163 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002164 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002165
Glenn Kastenfec279f2012-03-08 07:47:15 -08002166 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002167 threadLoop_mix();
2168 } else {
2169 threadLoop_sleepTime();
2170 }
2171
2172 if (mSuspended > 0) {
2173 sleepTime = suspendSleepTimeUs();
2174 }
2175
2176 // only process effects if we're going to write
2177 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002178 for (size_t i = 0; i < effectChains.size(); i ++) {
2179 effectChains[i]->process_l();
2180 }
2181 }
2182
2183 // enable changes in effect chain
2184 unlockEffectChains(effectChains);
2185
2186 // sleepTime == 0 means we must write to audio hardware
2187 if (sleepTime == 0) {
2188
2189 threadLoop_write();
2190
2191if (mType == MIXER) {
2192 // write blocked detection
2193 nsecs_t now = systemTime();
2194 nsecs_t delta = now - mLastWriteTime;
2195 if (!mStandby && delta > maxPeriod) {
2196 mNumDelayedWrites++;
2197 if ((now - lastWarning) > kWarningThrottleNs) {
2198 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2199 ns2ms(delta), mNumDelayedWrites, this);
2200 lastWarning = now;
2201 }
2202 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2203 // a different threshold. Or completely removed for what it is worth anyway...
2204 if (mStandby) {
2205 longStandbyExit = true;
2206 }
2207 }
2208}
2209
2210 mStandby = false;
2211 } else {
2212 usleep(sleepTime);
2213 }
2214
2215 // finally let go of removed track(s), without the lock held
2216 // since we can't guarantee the destructors won't acquire that
2217 // same lock.
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002218 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002219
Glenn Kastenfa26a852012-03-06 11:28:04 -08002220 // FIXME I don't understand the need for this here;
2221 // it was in the original code but maybe the
2222 // assignment in saveOutputTracks() makes this unnecessary?
2223 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002224
2225 // Effect chains will be actually deleted here if they were removed from
2226 // mEffectChains list during mixing or effects processing
2227 effectChains.clear();
2228
2229 // FIXME Note that the above .clear() is no longer necessary since effectChains
2230 // is now local to this block, but will keep it for now (at least until merge done).
2231 }
2232
2233if (mType == MIXER || mType == DIRECT) {
2234 // put output stream into standby mode
2235 if (!mStandby) {
2236 mOutput->stream->common.standby(&mOutput->stream->common);
2237 }
2238}
2239if (mType == DUPLICATING) {
2240 // for DuplicatingThread, standby mode is handled by the outputTracks
2241}
2242
2243 releaseWakeLock();
2244
2245 ALOGV("Thread %p type %d exiting", this, mType);
2246 return false;
2247}
2248
2249// shared by MIXER and DIRECT, overridden by DUPLICATING
2250void AudioFlinger::PlaybackThread::threadLoop_write()
2251{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002252 // FIXME rewrite to reduce number of system calls
2253 mLastWriteTime = systemTime();
2254 mInWrite = true;
2255 mBytesWritten += mixBufferSize;
2256 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2257 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2258 mNumWrites++;
2259 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002260}
2261
2262// shared by MIXER and DIRECT, overridden by DUPLICATING
2263void AudioFlinger::PlaybackThread::threadLoop_standby()
2264{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002265 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2266 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002267}
2268
2269void AudioFlinger::MixerThread::threadLoop_mix()
2270{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002271 // obtain the presentation timestamp of the next output buffer
2272 int64_t pts;
2273 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002274
Glenn Kasten952eeb22012-03-06 11:30:57 -08002275 if (NULL != mOutput->stream->get_next_write_timestamp) {
2276 status = mOutput->stream->get_next_write_timestamp(
2277 mOutput->stream, &pts);
2278 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002279
Glenn Kasten952eeb22012-03-06 11:30:57 -08002280 if (status != NO_ERROR) {
2281 pts = AudioBufferProvider::kInvalidPTS;
2282 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002283
Glenn Kasten952eeb22012-03-06 11:30:57 -08002284 // mix buffers...
2285 mAudioMixer->process(pts);
2286 // increase sleep time progressively when application underrun condition clears.
2287 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2288 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2289 // such that we would underrun the audio HAL.
2290 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2291 sleepTimeShift--;
2292 }
2293 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002294 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002295 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002296}
2297
2298void AudioFlinger::MixerThread::threadLoop_sleepTime()
2299{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002300 // If no tracks are ready, sleep once for the duration of an output
2301 // buffer size, then write 0s to the output
2302 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002303 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002304 sleepTime = activeSleepTime >> sleepTimeShift;
2305 if (sleepTime < kMinThreadSleepTimeUs) {
2306 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002307 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002308 // reduce sleep time in case of consecutive application underruns to avoid
2309 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2310 // duration we would end up writing less data than needed by the audio HAL if
2311 // the condition persists.
2312 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2313 sleepTimeShift++;
2314 }
2315 } else {
2316 sleepTime = idleSleepTime;
2317 }
2318 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002319 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002320 memset (mMixBuffer, 0, mixBufferSize);
2321 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002322 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002323 }
2324 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002325}
2326
2327// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002328AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002329 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002330{
2331
Glenn Kasten29c23c32012-01-26 13:37:52 -08002332 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002333 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002334 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002335 size_t mixedTracks = 0;
2336 size_t tracksWithEffect = 0;
2337
2338 float masterVolume = mMasterVolume;
2339 bool masterMute = mMasterMute;
2340
Eric Laurent571d49c2010-08-11 05:20:11 -07002341 if (masterMute) {
2342 masterVolume = 0;
2343 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002344 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002345 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002346 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002347 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002348 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002349 masterVolume = (float)((v + (1 << 23)) >> 24);
2350 chain.clear();
2351 }
2352
2353 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002354 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002355 if (t == 0) continue;
2356
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002357 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002358 Track* const track = t.get();
2359 audio_track_cblk_t* cblk = track->cblk();
2360
2361 // The first time a track is added we wait
2362 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002363 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002364 // make sure that we have enough frames to mix one full buffer.
2365 // enforce this condition only once to enable draining the buffer in case the client
2366 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002367 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002368 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002369 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002370 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002371 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002372 if (t->sampleRate() == (int)mSampleRate) {
2373 minFrames = mFrameCount;
2374 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002375 // +1 for rounding and +1 for additional sample needed for interpolation
2376 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2377 // add frames already consumed but not yet released by the resampler
2378 // because cblk->framesReady() will include these frames
2379 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2380 // the minimum track buffer size is normally twice the number of frames necessary
2381 // to fill one buffer and the resampler should not leave more than one buffer worth
2382 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002383 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002384 }
2385 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002386 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002387 !track->isPaused() && !track->isTerminated())
2388 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002389 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002390
2391 mixedTracks++;
2392
2393 // track->mainBuffer() != mMixBuffer means there is an effect chain
2394 // connected to the track
2395 chain.clear();
2396 if (track->mainBuffer() != mMixBuffer) {
2397 chain = getEffectChain_l(track->sessionId());
2398 // Delegate volume control to effect in track effect chain if needed
2399 if (chain != 0) {
2400 tracksWithEffect++;
2401 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002402 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002403 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002404 }
2405 }
2406
2407
2408 int param = AudioMixer::VOLUME;
2409 if (track->mFillingUpStatus == Track::FS_FILLED) {
2410 // no ramp for the first volume setting
2411 track->mFillingUpStatus = Track::FS_ACTIVE;
2412 if (track->mState == TrackBase::RESUMING) {
2413 track->mState = TrackBase::ACTIVE;
2414 param = AudioMixer::RAMP_VOLUME;
2415 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002416 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002417 } else if (cblk->server != 0) {
2418 // If the track is stopped before the first frame was mixed,
2419 // do not apply ramp
2420 param = AudioMixer::RAMP_VOLUME;
2421 }
2422
2423 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002424 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002425 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002426 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002427 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002428 if (track->isPausing()) {
2429 track->setPaused();
2430 }
2431 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002432
Mathias Agopian65ab4712010-07-14 17:59:35 -07002433 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002434 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002435 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002436 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002437 vl = vlr & 0xFFFF;
2438 vr = vlr >> 16;
2439 // track volumes come from shared memory, so can't be trusted and must be clamped
2440 if (vl > MAX_GAIN_INT) {
2441 ALOGV("Track left volume out of range: %04X", vl);
2442 vl = MAX_GAIN_INT;
2443 }
2444 if (vr > MAX_GAIN_INT) {
2445 ALOGV("Track right volume out of range: %04X", vr);
2446 vr = MAX_GAIN_INT;
2447 }
2448 // now apply the master volume and stream type volume
2449 vl = (uint32_t)(v * vl) << 12;
2450 vr = (uint32_t)(v * vr) << 12;
2451 // assuming master volume and stream type volume each go up to 1.0,
2452 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002453
Glenn Kasten05632a52012-01-03 14:22:33 -08002454 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2455 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002456 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002457 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002458 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002459 }
2460 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002461 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002462 // Delegate volume control to effect in track effect chain if needed
2463 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2464 // Do not ramp volume if volume is controlled by effect
2465 param = AudioMixer::VOLUME;
2466 track->mHasVolumeController = true;
2467 } else {
2468 // force no volume ramp when volume controller was just disabled or removed
2469 // from effect chain to avoid volume spike
2470 if (track->mHasVolumeController) {
2471 param = AudioMixer::VOLUME;
2472 }
2473 track->mHasVolumeController = false;
2474 }
2475
2476 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002477 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002478 vl = (vl + (1 << 11)) >> 12;
2479 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2480 vr = (vr + (1 << 11)) >> 12;
2481 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002482
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002483 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 -07002484
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002486 mAudioMixer->setBufferProvider(name, track);
2487 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002488
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002489 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2490 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2491 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002492 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002493 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002494 AudioMixer::TRACK,
2495 AudioMixer::FORMAT, (void *)track->format());
2496 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002497 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002498 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002499 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002500 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002501 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002502 AudioMixer::RESAMPLE,
2503 AudioMixer::SAMPLE_RATE,
2504 (void *)(cblk->sampleRate));
2505 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002506 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002507 AudioMixer::TRACK,
2508 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2509 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002510 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002511 AudioMixer::TRACK,
2512 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2513
2514 // reset retry count
2515 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002516 // If one track is ready, set the mixer ready if:
2517 // - the mixer was not ready during previous round OR
2518 // - no other track is not ready
2519 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2520 mixerStatus != MIXER_TRACKS_ENABLED) {
2521 mixerStatus = MIXER_TRACKS_READY;
2522 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002523 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002524 //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 -07002525 if (track->isStopped()) {
2526 track->reset();
2527 }
2528 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2529 // We have consumed all the buffers of this track.
2530 // Remove it from the list of active tracks.
2531 tracksToRemove->add(track);
2532 } else {
2533 // No buffers for this track. Give it a few chances to
2534 // fill a buffer, then remove it from active list.
2535 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002536 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002537 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002538 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002539 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002540 // If one track is not ready, mark the mixer also not ready if:
2541 // - the mixer was ready during previous round OR
2542 // - no other track is ready
2543 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2544 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002545 mixerStatus = MIXER_TRACKS_ENABLED;
2546 }
2547 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002548 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002549 }
2550 }
2551
2552 // remove all the tracks that need to be...
2553 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002554 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002555 for (size_t i=0 ; i<count ; i++) {
2556 const sp<Track>& track = tracksToRemove->itemAt(i);
2557 mActiveTracks.remove(track);
2558 if (track->mainBuffer() != mMixBuffer) {
2559 chain = getEffectChain_l(track->sessionId());
2560 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002561 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002562 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002563 }
2564 }
2565 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002566 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002567 }
2568 }
2569 }
2570
2571 // mix buffer must be cleared if all tracks are connected to an
2572 // effect chain as in this case the mixer will not write to
2573 // mix buffer and track effects will accumulate into it
2574 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2575 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2576 }
2577
2578 return mixerStatus;
2579}
2580
Glenn Kasten66fcab92012-02-24 14:59:21 -08002581/*
2582The derived values that are cached:
2583 - mixBufferSize from frame count * frame size
2584 - activeSleepTime from activeSleepTimeUs()
2585 - idleSleepTime from idleSleepTimeUs()
2586 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2587 - maxPeriod from frame count and sample rate (MIXER only)
2588
2589The parameters that affect these derived values are:
2590 - frame count
2591 - frame size
2592 - sample rate
2593 - device type: A2DP or not
2594 - device latency
2595 - format: PCM or not
2596 - active sleep time
2597 - idle sleep time
2598*/
2599
2600void AudioFlinger::PlaybackThread::cacheParameters_l()
2601{
2602 mixBufferSize = mFrameCount * mFrameSize;
2603 activeSleepTime = activeSleepTimeUs();
2604 idleSleepTime = idleSleepTimeUs();
2605}
2606
Glenn Kastenfff6d712012-01-12 16:38:12 -08002607void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002608{
Steve Block3856b092011-10-20 11:56:00 +01002609 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002610 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002611 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002612
Mathias Agopian65ab4712010-07-14 17:59:35 -07002613 size_t size = mTracks.size();
2614 for (size_t i = 0; i < size; i++) {
2615 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08002616 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002617 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002618 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002619 }
2620 }
2621}
2622
Glenn Kastenfff6d712012-01-12 16:38:12 -08002623void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002624{
Steve Block3856b092011-10-20 11:56:00 +01002625 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002626 this, streamType, valid);
2627 Mutex::Autolock _l(mLock);
2628
2629 mStreamTypes[streamType].valid = valid;
2630}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002631
2632// getTrackName_l() must be called with ThreadBase::mLock held
2633int AudioFlinger::MixerThread::getTrackName_l()
2634{
2635 return mAudioMixer->getTrackName();
2636}
2637
2638// deleteTrackName_l() must be called with ThreadBase::mLock held
2639void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2640{
Steve Block3856b092011-10-20 11:56:00 +01002641 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002642 mAudioMixer->deleteTrackName(name);
2643}
2644
2645// checkForNewParameters_l() must be called with ThreadBase::mLock held
2646bool AudioFlinger::MixerThread::checkForNewParameters_l()
2647{
2648 bool reconfig = false;
2649
2650 while (!mNewParameters.isEmpty()) {
2651 status_t status = NO_ERROR;
2652 String8 keyValuePair = mNewParameters[0];
2653 AudioParameter param = AudioParameter(keyValuePair);
2654 int value;
2655
2656 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2657 reconfig = true;
2658 }
2659 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002660 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002661 status = BAD_VALUE;
2662 } else {
2663 reconfig = true;
2664 }
2665 }
2666 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002667 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002668 status = BAD_VALUE;
2669 } else {
2670 reconfig = true;
2671 }
2672 }
2673 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2674 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002675 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002676 // if frame count is changed after track creation
2677 if (!mTracks.isEmpty()) {
2678 status = INVALID_OPERATION;
2679 } else {
2680 reconfig = true;
2681 }
2682 }
2683 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07002684#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08002685 // when changing the audio output device, call addBatteryData to notify
2686 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002687 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002688 uint32_t params = 0;
2689 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002690 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002691 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2692 }
2693
2694 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002695 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002696 // check if any other device (except speaker) is on
2697 if (value & deviceWithoutSpeaker ) {
2698 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2699 }
2700
2701 if (params != 0) {
2702 addBatteryData(params);
2703 }
2704 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07002705#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08002706
Mathias Agopian65ab4712010-07-14 17:59:35 -07002707 // forward device change to effects that have requested to be
2708 // aware of attached audio device.
2709 mDevice = (uint32_t)value;
2710 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002711 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002712 }
2713 }
2714
2715 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002716 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002717 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002718 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002719 mOutput->stream->common.standby(&mOutput->stream->common);
2720 mStandby = true;
2721 mBytesWritten = 0;
2722 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002723 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002724 }
2725 if (status == NO_ERROR && reconfig) {
2726 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002727 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2728 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002729 readOutputParameters();
2730 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2731 for (size_t i = 0; i < mTracks.size() ; i++) {
2732 int name = getTrackName_l();
2733 if (name < 0) break;
2734 mTracks[i]->mName = name;
2735 // limit track sample rate to 2 x new output sample rate
2736 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2737 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2738 }
2739 }
2740 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2741 }
2742 }
2743
2744 mNewParameters.removeAt(0);
2745
2746 mParamStatus = status;
2747 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002748 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2749 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002750 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002751 }
2752 return reconfig;
2753}
2754
2755status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2756{
2757 const size_t SIZE = 256;
2758 char buffer[SIZE];
2759 String8 result;
2760
2761 PlaybackThread::dumpInternals(fd, args);
2762
2763 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2764 result.append(buffer);
2765 write(fd, result.string(), result.size());
2766 return NO_ERROR;
2767}
2768
Mathias Agopian65ab4712010-07-14 17:59:35 -07002769uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2770{
Eric Laurent60e18242010-07-29 06:50:24 -07002771 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002772}
2773
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002774uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2775{
2776 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2777}
2778
Glenn Kasten66fcab92012-02-24 14:59:21 -08002779void AudioFlinger::MixerThread::cacheParameters_l()
2780{
2781 PlaybackThread::cacheParameters_l();
2782
2783 // FIXME: Relaxed timing because of a certain device that can't meet latency
2784 // Should be reduced to 2x after the vendor fixes the driver issue
2785 // increase threshold again due to low power audio mode. The way this warning
2786 // threshold is calculated and its usefulness should be reconsidered anyway.
2787 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
2788}
2789
Mathias Agopian65ab4712010-07-14 17:59:35 -07002790// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002791AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2792 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002793 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002794 // mLeftVolFloat, mRightVolFloat
2795 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002796{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002797}
2798
2799AudioFlinger::DirectOutputThread::~DirectOutputThread()
2800{
2801}
2802
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002803AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
2804 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08002805)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002806{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002807 sp<Track> trackToRemove;
2808
Glenn Kastenfec279f2012-03-08 07:47:15 -08002809 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002810
Glenn Kasten952eeb22012-03-06 11:30:57 -08002811 // find out which tracks need to be processed
2812 if (mActiveTracks.size() != 0) {
2813 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08002814 // The track died recently
2815 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002816
Glenn Kasten952eeb22012-03-06 11:30:57 -08002817 Track* const track = t.get();
2818 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002819
Glenn Kasten952eeb22012-03-06 11:30:57 -08002820 // The first time a track is added we wait
2821 // for all its buffers to be filled before processing it
2822 if (cblk->framesReady() && track->isReady() &&
2823 !track->isPaused() && !track->isTerminated())
2824 {
2825 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002826
Glenn Kasten952eeb22012-03-06 11:30:57 -08002827 if (track->mFillingUpStatus == Track::FS_FILLED) {
2828 track->mFillingUpStatus = Track::FS_ACTIVE;
2829 mLeftVolFloat = mRightVolFloat = 0;
2830 mLeftVolShort = mRightVolShort = 0;
2831 if (track->mState == TrackBase::RESUMING) {
2832 track->mState = TrackBase::ACTIVE;
2833 rampVolume = true;
2834 }
2835 } else if (cblk->server != 0) {
2836 // If the track is stopped before the first frame was mixed,
2837 // do not apply ramp
2838 rampVolume = true;
2839 }
2840 // compute volume for this track
2841 float left, right;
2842 if (track->isMuted() || mMasterMute || track->isPausing() ||
2843 mStreamTypes[track->streamType()].mute) {
2844 left = right = 0;
2845 if (track->isPausing()) {
2846 track->setPaused();
2847 }
2848 } else {
2849 float typeVolume = mStreamTypes[track->streamType()].volume;
2850 float v = mMasterVolume * typeVolume;
2851 uint32_t vlr = cblk->getVolumeLR();
2852 float v_clamped = v * (vlr & 0xFFFF);
2853 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2854 left = v_clamped/MAX_GAIN;
2855 v_clamped = v * (vlr >> 16);
2856 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2857 right = v_clamped/MAX_GAIN;
2858 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002859
Glenn Kasten952eeb22012-03-06 11:30:57 -08002860 if (left != mLeftVolFloat || right != mRightVolFloat) {
2861 mLeftVolFloat = left;
2862 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002863
Glenn Kasten952eeb22012-03-06 11:30:57 -08002864 // If audio HAL implements volume control,
2865 // force software volume to nominal value
2866 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
2867 left = 1.0f;
2868 right = 1.0f;
2869 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002870
Glenn Kasten952eeb22012-03-06 11:30:57 -08002871 // Convert volumes from float to 8.24
2872 uint32_t vl = (uint32_t)(left * (1 << 24));
2873 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002874
Glenn Kasten952eeb22012-03-06 11:30:57 -08002875 // Delegate volume control to effect in track effect chain if needed
2876 // only one effect chain can be present on DirectOutputThread, so if
2877 // there is one, the track is connected to it
2878 if (!mEffectChains.isEmpty()) {
2879 // Do not ramp volume if volume is controlled by effect
2880 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002881 rampVolume = false;
2882 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002883 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002884
Glenn Kasten952eeb22012-03-06 11:30:57 -08002885 // Convert volumes from 8.24 to 4.12 format
2886 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2887 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2888 leftVol = (uint16_t)v_clamped;
2889 v_clamped = (vr + (1 << 11)) >> 12;
2890 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2891 rightVol = (uint16_t)v_clamped;
2892 } else {
2893 leftVol = mLeftVolShort;
2894 rightVol = mRightVolShort;
2895 rampVolume = false;
2896 }
2897
2898 // reset retry count
2899 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002900 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002901 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002902 } else {
2903 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2904 if (track->isStopped()) {
2905 track->reset();
2906 }
2907 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2908 // We have consumed all the buffers of this track.
2909 // Remove it from the list of active tracks.
2910 trackToRemove = track;
2911 } else {
2912 // No buffers for this track. Give it a few chances to
2913 // fill a buffer, then remove it from active list.
2914 if (--(track->mRetryCount) <= 0) {
2915 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2916 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002917 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002918 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002919 }
2920 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002921 }
2922 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002923
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002924 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08002925 // remove all the tracks that need to be...
2926 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002927 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002928 mActiveTracks.remove(trackToRemove);
2929 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002930 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08002931 trackToRemove->sessionId());
2932 mEffectChains[0]->decActiveTrackCnt();
2933 }
2934 if (trackToRemove->isTerminated()) {
2935 removeTrack_l(trackToRemove);
2936 }
2937 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002938
Glenn Kastenfec279f2012-03-08 07:47:15 -08002939 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002940}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002941
Glenn Kasten000f0e32012-03-01 17:10:56 -08002942void AudioFlinger::DirectOutputThread::threadLoop_mix()
2943{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002944 AudioBufferProvider::Buffer buffer;
2945 size_t frameCount = mFrameCount;
2946 int8_t *curBuf = (int8_t *)mMixBuffer;
2947 // output audio to hardware
2948 while (frameCount) {
2949 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002950 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002951 if (CC_UNLIKELY(buffer.raw == NULL)) {
2952 memset(curBuf, 0, frameCount * mFrameSize);
2953 break;
2954 }
2955 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2956 frameCount -= buffer.frameCount;
2957 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002958 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002959 }
2960 sleepTime = 0;
2961 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002962 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08002963
2964 // apply volume
2965
2966 // Do not apply volume on compressed audio
2967 if (!audio_is_linear_pcm(mFormat)) {
2968 return;
2969 }
2970
2971 // convert to signed 16 bit before volume calculation
2972 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
2973 size_t count = mFrameCount * mChannelCount;
2974 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2975 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002976 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08002977 *dst-- = (int16_t)(*src--^0x80) << 8;
2978 }
2979 }
2980
2981 frameCount = mFrameCount;
2982 int16_t *out = mMixBuffer;
2983 if (rampVolume) {
2984 if (mChannelCount == 1) {
2985 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2986 int32_t vlInc = d / (int32_t)frameCount;
2987 int32_t vl = ((int32_t)mLeftVolShort << 16);
2988 do {
2989 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2990 out++;
2991 vl += vlInc;
2992 } while (--frameCount);
2993
2994 } else {
2995 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2996 int32_t vlInc = d / (int32_t)frameCount;
2997 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2998 int32_t vrInc = d / (int32_t)frameCount;
2999 int32_t vl = ((int32_t)mLeftVolShort << 16);
3000 int32_t vr = ((int32_t)mRightVolShort << 16);
3001 do {
3002 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3003 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3004 out += 2;
3005 vl += vlInc;
3006 vr += vrInc;
3007 } while (--frameCount);
3008 }
3009 } else {
3010 if (mChannelCount == 1) {
3011 do {
3012 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3013 out++;
3014 } while (--frameCount);
3015 } else {
3016 do {
3017 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3018 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3019 out += 2;
3020 } while (--frameCount);
3021 }
3022 }
3023
3024 // convert back to unsigned 8 bit after volume calculation
3025 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3026 size_t count = mFrameCount * mChannelCount;
3027 int16_t *src = mMixBuffer;
3028 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003029 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003030 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3031 }
3032 }
3033
3034 mLeftVolShort = leftVol;
3035 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003036}
3037
3038void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3039{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003040 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003041 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003042 sleepTime = activeSleepTime;
3043 } else {
3044 sleepTime = idleSleepTime;
3045 }
3046 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3047 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
3048 sleepTime = 0;
3049 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003050}
3051
3052// getTrackName_l() must be called with ThreadBase::mLock held
3053int AudioFlinger::DirectOutputThread::getTrackName_l()
3054{
3055 return 0;
3056}
3057
3058// deleteTrackName_l() must be called with ThreadBase::mLock held
3059void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3060{
3061}
3062
3063// checkForNewParameters_l() must be called with ThreadBase::mLock held
3064bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3065{
3066 bool reconfig = false;
3067
3068 while (!mNewParameters.isEmpty()) {
3069 status_t status = NO_ERROR;
3070 String8 keyValuePair = mNewParameters[0];
3071 AudioParameter param = AudioParameter(keyValuePair);
3072 int value;
3073
3074 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3075 // do not accept frame count changes if tracks are open as the track buffer
3076 // size depends on frame count and correct behavior would not be garantied
3077 // if frame count is changed after track creation
3078 if (!mTracks.isEmpty()) {
3079 status = INVALID_OPERATION;
3080 } else {
3081 reconfig = true;
3082 }
3083 }
3084 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003085 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003086 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003087 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003088 mOutput->stream->common.standby(&mOutput->stream->common);
3089 mStandby = true;
3090 mBytesWritten = 0;
3091 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003092 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003093 }
3094 if (status == NO_ERROR && reconfig) {
3095 readOutputParameters();
3096 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3097 }
3098 }
3099
3100 mNewParameters.removeAt(0);
3101
3102 mParamStatus = status;
3103 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003104 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3105 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003106 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003107 }
3108 return reconfig;
3109}
3110
3111uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
3112{
3113 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003114 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003115 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003116 } else {
3117 time = 10000;
3118 }
3119 return time;
3120}
3121
3122uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
3123{
3124 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003125 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003126 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003127 } else {
3128 time = 10000;
3129 }
3130 return time;
3131}
3132
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003133uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
3134{
3135 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003136 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003137 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3138 } else {
3139 time = 10000;
3140 }
3141 return time;
3142}
3143
Glenn Kasten66fcab92012-02-24 14:59:21 -08003144void AudioFlinger::DirectOutputThread::cacheParameters_l()
3145{
3146 PlaybackThread::cacheParameters_l();
3147
3148 // use shorter standby delay as on normal output to release
3149 // hardware resources as soon as possible
3150 standbyDelay = microseconds(activeSleepTime*2);
3151}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003152
Mathias Agopian65ab4712010-07-14 17:59:35 -07003153// ----------------------------------------------------------------------------
3154
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003155AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003156 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003157 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3158 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003159{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003160 addOutputTrack(mainThread);
3161}
3162
3163AudioFlinger::DuplicatingThread::~DuplicatingThread()
3164{
3165 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3166 mOutputTracks[i]->destroy();
3167 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003168}
3169
Glenn Kasten000f0e32012-03-01 17:10:56 -08003170void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003171{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003172 // mix buffers...
3173 if (outputsReady(outputTracks)) {
3174 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3175 } else {
3176 memset(mMixBuffer, 0, mixBufferSize);
3177 }
3178 sleepTime = 0;
3179 writeFrames = mFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003180}
3181
3182void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3183{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003184 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003185 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003186 sleepTime = activeSleepTime;
3187 } else {
3188 sleepTime = idleSleepTime;
3189 }
3190 } else if (mBytesWritten != 0) {
3191 // flush remaining overflow buffers in output tracks
3192 for (size_t i = 0; i < outputTracks.size(); i++) {
3193 if (outputTracks[i]->isActive()) {
3194 sleepTime = 0;
3195 writeFrames = 0;
3196 memset(mMixBuffer, 0, mixBufferSize);
3197 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003198 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003199 }
3200 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003201}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003202
Glenn Kasten000f0e32012-03-01 17:10:56 -08003203void AudioFlinger::DuplicatingThread::threadLoop_write()
3204{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003205 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003206 for (size_t i = 0; i < outputTracks.size(); i++) {
3207 outputTracks[i]->write(mMixBuffer, writeFrames);
3208 }
3209 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003210}
Glenn Kasten688a6402012-02-29 07:57:06 -08003211
Glenn Kasten000f0e32012-03-01 17:10:56 -08003212void AudioFlinger::DuplicatingThread::threadLoop_standby()
3213{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003214 // DuplicatingThread implements standby by stopping all tracks
3215 for (size_t i = 0; i < outputTracks.size(); i++) {
3216 outputTracks[i]->stop();
3217 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003218}
3219
Glenn Kastenfa26a852012-03-06 11:28:04 -08003220void AudioFlinger::DuplicatingThread::saveOutputTracks()
3221{
3222 outputTracks = mOutputTracks;
3223}
3224
3225void AudioFlinger::DuplicatingThread::clearOutputTracks()
3226{
3227 outputTracks.clear();
3228}
3229
Mathias Agopian65ab4712010-07-14 17:59:35 -07003230void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3231{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003232 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003233 // FIXME explain this formula
Mathias Agopian65ab4712010-07-14 17:59:35 -07003234 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003235 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003236 this,
3237 mSampleRate,
3238 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003239 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003240 frameCount);
3241 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003242 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003243 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003244 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003245 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003246 }
3247}
3248
3249void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3250{
3251 Mutex::Autolock _l(mLock);
3252 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003253 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003254 mOutputTracks[i]->destroy();
3255 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003256 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003257 return;
3258 }
3259 }
Steve Block3856b092011-10-20 11:56:00 +01003260 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003261}
3262
Glenn Kasten438b0362012-03-06 11:24:48 -08003263// caller must hold mLock
3264void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003265{
3266 mWaitTimeMs = UINT_MAX;
3267 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3268 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003269 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003270 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3271 if (waitTimeMs < mWaitTimeMs) {
3272 mWaitTimeMs = waitTimeMs;
3273 }
3274 }
3275 }
3276}
3277
3278
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003279bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003280{
3281 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003282 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003283 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003284 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003285 return false;
3286 }
3287 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3288 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003289 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003290 return false;
3291 }
3292 }
3293 return true;
3294}
3295
3296uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3297{
3298 return (mWaitTimeMs * 1000) / 2;
3299}
3300
Glenn Kasten66fcab92012-02-24 14:59:21 -08003301void AudioFlinger::DuplicatingThread::cacheParameters_l()
3302{
3303 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3304 updateWaitTime_l();
3305
3306 MixerThread::cacheParameters_l();
3307}
3308
Mathias Agopian65ab4712010-07-14 17:59:35 -07003309// ----------------------------------------------------------------------------
3310
3311// TrackBase constructor must be called with AudioFlinger::mLock held
3312AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003313 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003314 const sp<Client>& client,
3315 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003316 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003317 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003318 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003319 const sp<IMemory>& sharedBuffer,
3320 int sessionId)
3321 : RefBase(),
3322 mThread(thread),
3323 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003324 mCblk(NULL),
3325 // mBuffer
3326 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003327 mFrameCount(0),
3328 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003329 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003330 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003331 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003332 // mChannelCount
3333 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003334{
Steve Block3856b092011-10-20 11:56:00 +01003335 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003336
Steve Blockb8a80522011-12-20 16:23:08 +00003337 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003338 size_t size = sizeof(audio_track_cblk_t);
3339 uint8_t channelCount = popcount(channelMask);
3340 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3341 if (sharedBuffer == 0) {
3342 size += bufferSize;
3343 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003344
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003345 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003346 mCblkMemory = client->heap()->allocate(size);
3347 if (mCblkMemory != 0) {
3348 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003349 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003350 new(mCblk) audio_track_cblk_t();
3351 // clear all buffers
3352 mCblk->frameCount = frameCount;
3353 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003354 mChannelCount = channelCount;
3355 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003356 if (sharedBuffer == 0) {
3357 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3358 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3359 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003360 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003361 mCblk->flags = CBLK_UNDERRUN_ON;
3362 } else {
3363 mBuffer = sharedBuffer->pointer();
3364 }
3365 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3366 }
3367 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003368 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003369 client->heap()->dump("AudioTrack");
3370 return;
3371 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003372 } else {
3373 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3374 // construct the shared structure in-place.
3375 new(mCblk) audio_track_cblk_t();
3376 // clear all buffers
3377 mCblk->frameCount = frameCount;
3378 mCblk->sampleRate = sampleRate;
3379 mChannelCount = channelCount;
3380 mChannelMask = channelMask;
3381 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3382 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3383 // Force underrun condition to avoid false underrun callback until first data is
3384 // written to buffer (other flags are cleared)
3385 mCblk->flags = CBLK_UNDERRUN_ON;
3386 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3387 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003388}
3389
3390AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3391{
Glenn Kastena0d68332012-01-27 16:47:15 -08003392 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003393 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003394 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003395 } else {
3396 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003397 }
3398 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003399 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003400 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003401 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003402 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003403 // If the client's reference count drops to zero, the associated destructor
3404 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3405 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003406 mClient.clear();
3407 }
3408}
3409
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003410// AudioBufferProvider interface
3411// getNextBuffer() = 0;
3412// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07003413void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3414{
Glenn Kastene0feee32011-12-13 11:53:26 -08003415 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003416 mFrameCount = buffer->frameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003417 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003418 buffer->frameCount = 0;
3419}
3420
3421bool AudioFlinger::ThreadBase::TrackBase::step() {
3422 bool result;
3423 audio_track_cblk_t* cblk = this->cblk();
3424
3425 result = cblk->stepServer(mFrameCount);
3426 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003427 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003428 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003429 }
3430 return result;
3431}
3432
3433void AudioFlinger::ThreadBase::TrackBase::reset() {
3434 audio_track_cblk_t* cblk = this->cblk();
3435
3436 cblk->user = 0;
3437 cblk->server = 0;
3438 cblk->userBase = 0;
3439 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003440 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01003441 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003442}
3443
Mathias Agopian65ab4712010-07-14 17:59:35 -07003444int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3445 return (int)mCblk->sampleRate;
3446}
3447
Mathias Agopian65ab4712010-07-14 17:59:35 -07003448void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3449 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003450 size_t frameSize = cblk->frameSize;
3451 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3452 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003453
3454 // Check validity of returned pointer in case the track control block would have been corrupted.
3455 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003456 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003457 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 -07003458 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003459 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003460 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003461 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003462 }
3463
3464 return bufferStart;
3465}
3466
3467// ----------------------------------------------------------------------------
3468
3469// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3470AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003471 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003472 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003473 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003474 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003475 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003476 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003477 int frameCount,
3478 const sp<IMemory>& sharedBuffer,
3479 int sessionId)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003480 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003481 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3482 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003483{
3484 if (mCblk != NULL) {
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003485 if (thread != NULL) {
3486 mName = thread->getTrackName_l();
3487 mMainBuffer = thread->mixBuffer();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003488 }
Glenn Kasten23d82a92012-02-03 11:10:00 -08003489 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003490 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003491 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003492 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003493 mStreamType = streamType;
3494 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3495 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003496 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003497 }
3498}
3499
3500AudioFlinger::PlaybackThread::Track::~Track()
3501{
Steve Block3856b092011-10-20 11:56:00 +01003502 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003503 sp<ThreadBase> thread = mThread.promote();
3504 if (thread != 0) {
3505 Mutex::Autolock _l(thread->mLock);
3506 mState = TERMINATED;
3507 }
3508}
3509
3510void AudioFlinger::PlaybackThread::Track::destroy()
3511{
3512 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3513 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08003514 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003515 // we must acquire a strong reference on this Track before locking mLock
3516 // here so that the destructor is called only when exiting this function.
3517 // On the other hand, as long as Track::destroy() is only called by
3518 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3519 // this Track with its member mTrack.
3520 sp<Track> keep(this);
3521 { // scope for mLock
3522 sp<ThreadBase> thread = mThread.promote();
3523 if (thread != 0) {
3524 if (!isOutputTrack()) {
3525 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08003526 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003527
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003528#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003529 // to track the speaker usage
3530 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003531#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003532 }
3533 AudioSystem::releaseOutput(thread->id());
3534 }
3535 Mutex::Autolock _l(thread->mLock);
3536 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3537 playbackThread->destroyTrack_l(this);
3538 }
3539 }
3540}
3541
3542void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3543{
Glenn Kasten83d86532012-01-17 14:39:34 -08003544 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003545 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 -07003546 mName - AudioMixer::TRACK0,
Glenn Kasten44deb052012-02-05 18:09:08 -08003547 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003548 mStreamType,
3549 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003550 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003551 mSessionId,
3552 mFrameCount,
3553 mState,
3554 mMute,
3555 mFillingUpStatus,
3556 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003557 vlr & 0xFFFF,
3558 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003559 mCblk->server,
3560 mCblk->user,
3561 (int)mMainBuffer,
3562 (int)mAuxBuffer);
3563}
3564
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003565// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08003566status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003567 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003568{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003569 audio_track_cblk_t* cblk = this->cblk();
3570 uint32_t framesReady;
3571 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003572
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003573 // Check if last stepServer failed, try to step now
3574 if (mStepServerFailed) {
3575 if (!step()) goto getNextBuffer_exit;
3576 ALOGV("stepServer recovered");
3577 mStepServerFailed = false;
3578 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003579
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003580 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003581
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003582 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003583 uint32_t s = cblk->server;
3584 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3585
3586 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3587 if (framesReq > framesReady) {
3588 framesReq = framesReady;
3589 }
3590 if (s + framesReq > bufferEnd) {
3591 framesReq = bufferEnd - s;
3592 }
3593
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003594 buffer->raw = getBuffer(s, framesReq);
3595 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003596
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003597 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003598 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003599 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003600
3601getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003602 buffer->raw = NULL;
3603 buffer->frameCount = 0;
3604 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3605 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003606}
3607
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003608uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08003609 return mCblk->framesReady();
3610}
3611
Mathias Agopian65ab4712010-07-14 17:59:35 -07003612bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003613 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003614
John Grossman4ff14ba2012-02-08 16:37:41 -08003615 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003616 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3617 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003618 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003619 return true;
3620 }
3621 return false;
3622}
3623
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003624status_t AudioFlinger::PlaybackThread::Track::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003625{
3626 status_t status = NO_ERROR;
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003627 ALOGV("start(%d), calling pid %d session %d tid %d",
3628 mName, IPCThreadState::self()->getCallingPid(), mSessionId, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003629 sp<ThreadBase> thread = mThread.promote();
3630 if (thread != 0) {
3631 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003632 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003633 // here the track could be either new, or restarted
3634 // in both cases "unstop" the track
3635 if (mState == PAUSED) {
3636 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003637 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003638 } else {
3639 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003640 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003641 }
3642
3643 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3644 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003645 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003646 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003647
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003648#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003649 // to track the speaker usage
3650 if (status == NO_ERROR) {
3651 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3652 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003653#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003654 }
3655 if (status == NO_ERROR) {
3656 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3657 playbackThread->addTrack_l(this);
3658 } else {
3659 mState = state;
3660 }
3661 } else {
3662 status = BAD_VALUE;
3663 }
3664 return status;
3665}
3666
3667void AudioFlinger::PlaybackThread::Track::stop()
3668{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003669 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003670 sp<ThreadBase> thread = mThread.promote();
3671 if (thread != 0) {
3672 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003673 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003674 if (mState > STOPPED) {
3675 mState = STOPPED;
3676 // If the track is not active (PAUSED and buffers full), flush buffers
3677 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3678 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3679 reset();
3680 }
Steve Block3856b092011-10-20 11:56:00 +01003681 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003682 }
3683 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3684 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003685 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003686 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003687
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003688#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003689 // to track the speaker usage
3690 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003691#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003692 }
3693 }
3694}
3695
3696void AudioFlinger::PlaybackThread::Track::pause()
3697{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003698 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003699 sp<ThreadBase> thread = mThread.promote();
3700 if (thread != 0) {
3701 Mutex::Autolock _l(thread->mLock);
3702 if (mState == ACTIVE || mState == RESUMING) {
3703 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003704 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003705 if (!isOutputTrack()) {
3706 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003707 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003708 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003709
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003710#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003711 // to track the speaker usage
3712 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003713#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003714 }
3715 }
3716 }
3717}
3718
3719void AudioFlinger::PlaybackThread::Track::flush()
3720{
Steve Block3856b092011-10-20 11:56:00 +01003721 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003722 sp<ThreadBase> thread = mThread.promote();
3723 if (thread != 0) {
3724 Mutex::Autolock _l(thread->mLock);
3725 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3726 return;
3727 }
3728 // No point remaining in PAUSED state after a flush => go to
3729 // STOPPED state
3730 mState = STOPPED;
3731
Eric Laurent38ccae22011-03-28 18:37:07 -07003732 // do not reset the track if it is still in the process of being stopped or paused.
3733 // this will be done by prepareTracks_l() when the track is stopped.
3734 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3735 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3736 reset();
3737 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003738 }
3739}
3740
3741void AudioFlinger::PlaybackThread::Track::reset()
3742{
3743 // Do not reset twice to avoid discarding data written just after a flush and before
3744 // the audioflinger thread detects the track is stopped.
3745 if (!mResetDone) {
3746 TrackBase::reset();
3747 // Force underrun condition to avoid false underrun callback until first data is
3748 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003749 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3750 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003751 mFillingUpStatus = FS_FILLING;
3752 mResetDone = true;
3753 }
3754}
3755
3756void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3757{
3758 mMute = muted;
3759}
3760
Mathias Agopian65ab4712010-07-14 17:59:35 -07003761status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3762{
3763 status_t status = DEAD_OBJECT;
3764 sp<ThreadBase> thread = mThread.promote();
3765 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003766 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3767 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003768 }
3769 return status;
3770}
3771
3772void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3773{
3774 mAuxEffectId = EffectId;
3775 mAuxBuffer = buffer;
3776}
3777
John Grossman4ff14ba2012-02-08 16:37:41 -08003778// timed audio tracks
3779
3780sp<AudioFlinger::PlaybackThread::TimedTrack>
3781AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003782 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003783 const sp<Client>& client,
3784 audio_stream_type_t streamType,
3785 uint32_t sampleRate,
3786 audio_format_t format,
3787 uint32_t channelMask,
3788 int frameCount,
3789 const sp<IMemory>& sharedBuffer,
3790 int sessionId) {
3791 if (!client->reserveTimedTrack())
3792 return NULL;
3793
3794 sp<TimedTrack> track = new TimedTrack(
3795 thread, client, streamType, sampleRate, format, channelMask, frameCount,
3796 sharedBuffer, sessionId);
3797
3798 if (track == NULL) {
3799 client->releaseTimedTrack();
3800 return NULL;
3801 }
3802
3803 return track;
3804}
3805
3806AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003807 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003808 const sp<Client>& client,
3809 audio_stream_type_t streamType,
3810 uint32_t sampleRate,
3811 audio_format_t format,
3812 uint32_t channelMask,
3813 int frameCount,
3814 const sp<IMemory>& sharedBuffer,
3815 int sessionId)
3816 : Track(thread, client, streamType, sampleRate, format, channelMask,
3817 frameCount, sharedBuffer, sessionId),
3818 mTimedSilenceBuffer(NULL),
3819 mTimedSilenceBufferSize(0),
3820 mTimedAudioOutputOnTime(false),
3821 mMediaTimeTransformValid(false)
3822{
3823 LocalClock lc;
3824 mLocalTimeFreq = lc.getLocalFreq();
3825
3826 mLocalTimeToSampleTransform.a_zero = 0;
3827 mLocalTimeToSampleTransform.b_zero = 0;
3828 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3829 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3830 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3831 &mLocalTimeToSampleTransform.a_to_b_denom);
3832}
3833
3834AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3835 mClient->releaseTimedTrack();
3836 delete [] mTimedSilenceBuffer;
3837}
3838
3839status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3840 size_t size, sp<IMemory>* buffer) {
3841
3842 Mutex::Autolock _l(mTimedBufferQueueLock);
3843
3844 trimTimedBufferQueue_l();
3845
3846 // lazily initialize the shared memory heap for timed buffers
3847 if (mTimedMemoryDealer == NULL) {
3848 const int kTimedBufferHeapSize = 512 << 10;
3849
3850 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3851 "AudioFlingerTimed");
3852 if (mTimedMemoryDealer == NULL)
3853 return NO_MEMORY;
3854 }
3855
3856 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3857 if (newBuffer == NULL) {
3858 newBuffer = mTimedMemoryDealer->allocate(size);
3859 if (newBuffer == NULL)
3860 return NO_MEMORY;
3861 }
3862
3863 *buffer = newBuffer;
3864 return NO_ERROR;
3865}
3866
3867// caller must hold mTimedBufferQueueLock
3868void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
3869 int64_t mediaTimeNow;
3870 {
3871 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3872 if (!mMediaTimeTransformValid)
3873 return;
3874
3875 int64_t targetTimeNow;
3876 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
3877 ? mCCHelper.getCommonTime(&targetTimeNow)
3878 : mCCHelper.getLocalTime(&targetTimeNow);
3879
3880 if (OK != res)
3881 return;
3882
3883 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
3884 &mediaTimeNow)) {
3885 return;
3886 }
3887 }
3888
3889 size_t trimIndex;
3890 for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
3891 if (mTimedBufferQueue[trimIndex].pts() > mediaTimeNow)
3892 break;
3893 }
3894
3895 if (trimIndex) {
3896 mTimedBufferQueue.removeItemsAt(0, trimIndex);
3897 }
3898}
3899
3900status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
3901 const sp<IMemory>& buffer, int64_t pts) {
3902
3903 {
3904 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3905 if (!mMediaTimeTransformValid)
3906 return INVALID_OPERATION;
3907 }
3908
3909 Mutex::Autolock _l(mTimedBufferQueueLock);
3910
3911 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
3912
3913 return NO_ERROR;
3914}
3915
3916status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
3917 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
3918
3919 ALOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
3920 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
3921 target);
3922
3923 if (!(target == TimedAudioTrack::LOCAL_TIME ||
3924 target == TimedAudioTrack::COMMON_TIME)) {
3925 return BAD_VALUE;
3926 }
3927
3928 Mutex::Autolock lock(mMediaTimeTransformLock);
3929 mMediaTimeTransform = xform;
3930 mMediaTimeTransformTarget = target;
3931 mMediaTimeTransformValid = true;
3932
3933 return NO_ERROR;
3934}
3935
3936#define min(a, b) ((a) < (b) ? (a) : (b))
3937
3938// implementation of getNextBuffer for tracks whose buffers have timestamps
3939status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
3940 AudioBufferProvider::Buffer* buffer, int64_t pts)
3941{
3942 if (pts == AudioBufferProvider::kInvalidPTS) {
3943 buffer->raw = 0;
3944 buffer->frameCount = 0;
3945 return INVALID_OPERATION;
3946 }
3947
John Grossman4ff14ba2012-02-08 16:37:41 -08003948 Mutex::Autolock _l(mTimedBufferQueueLock);
3949
3950 while (true) {
3951
3952 // if we have no timed buffers, then fail
3953 if (mTimedBufferQueue.isEmpty()) {
3954 buffer->raw = 0;
3955 buffer->frameCount = 0;
3956 return NOT_ENOUGH_DATA;
3957 }
3958
3959 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
3960
3961 // calculate the PTS of the head of the timed buffer queue expressed in
3962 // local time
3963 int64_t headLocalPTS;
3964 {
3965 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3966
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003967 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08003968
3969 if (mMediaTimeTransform.a_to_b_denom == 0) {
3970 // the transform represents a pause, so yield silence
3971 timedYieldSilence(buffer->frameCount, buffer);
3972 return NO_ERROR;
3973 }
3974
3975 int64_t transformedPTS;
3976 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
3977 &transformedPTS)) {
3978 // the transform failed. this shouldn't happen, but if it does
3979 // then just drop this buffer
3980 ALOGW("timedGetNextBuffer transform failed");
3981 buffer->raw = 0;
3982 buffer->frameCount = 0;
3983 mTimedBufferQueue.removeAt(0);
3984 return NO_ERROR;
3985 }
3986
3987 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
3988 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
3989 &headLocalPTS)) {
3990 buffer->raw = 0;
3991 buffer->frameCount = 0;
3992 return INVALID_OPERATION;
3993 }
3994 } else {
3995 headLocalPTS = transformedPTS;
3996 }
3997 }
3998
3999 // adjust the head buffer's PTS to reflect the portion of the head buffer
4000 // that has already been consumed
4001 int64_t effectivePTS = headLocalPTS +
4002 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4003
4004 // Calculate the delta in samples between the head of the input buffer
4005 // queue and the start of the next output buffer that will be written.
4006 // If the transformation fails because of over or underflow, it means
4007 // that the sample's position in the output stream is so far out of
4008 // whack that it should just be dropped.
4009 int64_t sampleDelta;
4010 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4011 ALOGV("*** head buffer is too far from PTS: dropped buffer");
4012 mTimedBufferQueue.removeAt(0);
4013 continue;
4014 }
4015 if (!mLocalTimeToSampleTransform.doForwardTransform(
4016 (effectivePTS - pts) << 32, &sampleDelta)) {
4017 ALOGV("*** too late during sample rate transform: dropped buffer");
4018 mTimedBufferQueue.removeAt(0);
4019 continue;
4020 }
4021
4022 ALOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
4023 __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
4024 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
4025 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
4026
4027 // if the delta between the ideal placement for the next input sample and
4028 // the current output position is within this threshold, then we will
4029 // concatenate the next input samples to the previous output
4030 const int64_t kSampleContinuityThreshold =
4031 (static_cast<int64_t>(sampleRate()) << 32) / 10;
4032
4033 // if this is the first buffer of audio that we're emitting from this track
4034 // then it should be almost exactly on time.
4035 const int64_t kSampleStartupThreshold = 1LL << 32;
4036
4037 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
4038 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
4039 // the next input is close enough to being on time, so concatenate it
4040 // with the last output
4041 timedYieldSamples(buffer);
4042
4043 ALOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4044 return NO_ERROR;
4045 } else if (sampleDelta > 0) {
4046 // the gap between the current output position and the proper start of
4047 // the next input sample is too big, so fill it with silence
4048 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4049
4050 timedYieldSilence(framesUntilNextInput, buffer);
4051 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4052 return NO_ERROR;
4053 } else {
4054 // the next input sample is late
4055 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4056 size_t onTimeSamplePosition =
4057 head.position() + lateFrames * mCblk->frameSize;
4058
4059 if (onTimeSamplePosition > head.buffer()->size()) {
4060 // all the remaining samples in the head are too late, so
4061 // drop it and move on
4062 ALOGV("*** too late: dropped buffer");
4063 mTimedBufferQueue.removeAt(0);
4064 continue;
4065 } else {
4066 // skip over the late samples
4067 head.setPosition(onTimeSamplePosition);
4068
4069 // yield the available samples
4070 timedYieldSamples(buffer);
4071
4072 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4073 return NO_ERROR;
4074 }
4075 }
4076 }
4077}
4078
4079// Yield samples from the timed buffer queue head up to the given output
4080// buffer's capacity.
4081//
4082// Caller must hold mTimedBufferQueueLock
4083void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples(
4084 AudioBufferProvider::Buffer* buffer) {
4085
4086 const TimedBuffer& head = mTimedBufferQueue[0];
4087
4088 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4089 head.position());
4090
4091 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4092 mCblk->frameSize);
4093 size_t framesRequested = buffer->frameCount;
4094 buffer->frameCount = min(framesLeftInHead, framesRequested);
4095
4096 mTimedAudioOutputOnTime = true;
4097}
4098
4099// Yield samples of silence up to the given output buffer's capacity
4100//
4101// Caller must hold mTimedBufferQueueLock
4102void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence(
4103 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4104
4105 // lazily allocate a buffer filled with silence
4106 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4107 delete [] mTimedSilenceBuffer;
4108 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4109 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4110 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4111 }
4112
4113 buffer->raw = mTimedSilenceBuffer;
4114 size_t framesRequested = buffer->frameCount;
4115 buffer->frameCount = min(numFrames, framesRequested);
4116
4117 mTimedAudioOutputOnTime = false;
4118}
4119
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004120// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004121void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4122 AudioBufferProvider::Buffer* buffer) {
4123
4124 Mutex::Autolock _l(mTimedBufferQueueLock);
4125
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004126 // If the buffer which was just released is part of the buffer at the head
4127 // of the queue, be sure to update the amt of the buffer which has been
4128 // consumed. If the buffer being returned is not part of the head of the
4129 // queue, its either because the buffer is part of the silence buffer, or
4130 // because the head of the timed queue was trimmed after the mixer called
4131 // getNextBuffer but before the mixer called releaseBuffer.
4132 if ((buffer->raw != mTimedSilenceBuffer) && mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004133 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004134
4135 void* start = head.buffer()->pointer();
Glenn Kastenf063b492012-02-17 16:24:10 -08004136 void* end = (char *) head.buffer()->pointer() + head.buffer()->size();
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004137
4138 if ((buffer->raw >= start) && (buffer->raw <= end)) {
4139 head.setPosition(head.position() +
4140 (buffer->frameCount * mCblk->frameSize));
4141 if (static_cast<size_t>(head.position()) >= head.buffer()->size()) {
4142 mTimedBufferQueue.removeAt(0);
4143 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004144 }
4145 }
4146
4147 buffer->raw = 0;
4148 buffer->frameCount = 0;
4149}
4150
4151uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4152 Mutex::Autolock _l(mTimedBufferQueueLock);
4153
4154 uint32_t frames = 0;
4155 for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4156 const TimedBuffer& tb = mTimedBufferQueue[i];
4157 frames += (tb.buffer()->size() - tb.position()) / mCblk->frameSize;
4158 }
4159
4160 return frames;
4161}
4162
4163AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4164 : mPTS(0), mPosition(0) {}
4165
4166AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4167 const sp<IMemory>& buffer, int64_t pts)
4168 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4169
Mathias Agopian65ab4712010-07-14 17:59:35 -07004170// ----------------------------------------------------------------------------
4171
4172// RecordTrack constructor must be called with AudioFlinger::mLock held
4173AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004174 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004175 const sp<Client>& client,
4176 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004177 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004178 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004179 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004180 int sessionId)
4181 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004182 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004183 mOverflow(false)
4184{
4185 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004186 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
4187 if (format == AUDIO_FORMAT_PCM_16_BIT) {
4188 mCblk->frameSize = mChannelCount * sizeof(int16_t);
4189 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
4190 mCblk->frameSize = mChannelCount * sizeof(int8_t);
4191 } else {
4192 mCblk->frameSize = sizeof(int8_t);
4193 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004194 }
4195}
4196
4197AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4198{
4199 sp<ThreadBase> thread = mThread.promote();
4200 if (thread != 0) {
4201 AudioSystem::releaseInput(thread->id());
4202 }
4203}
4204
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004205// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004206status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004207{
4208 audio_track_cblk_t* cblk = this->cblk();
4209 uint32_t framesAvail;
4210 uint32_t framesReq = buffer->frameCount;
4211
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004212 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004213 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004214 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004215 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004216 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004217 }
4218
4219 framesAvail = cblk->framesAvailable_l();
4220
Glenn Kastenf6b16782011-12-15 09:51:17 -08004221 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004222 uint32_t s = cblk->server;
4223 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4224
4225 if (framesReq > framesAvail) {
4226 framesReq = framesAvail;
4227 }
4228 if (s + framesReq > bufferEnd) {
4229 framesReq = bufferEnd - s;
4230 }
4231
4232 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004233 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004234
4235 buffer->frameCount = framesReq;
4236 return NO_ERROR;
4237 }
4238
4239getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004240 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004241 buffer->frameCount = 0;
4242 return NOT_ENOUGH_DATA;
4243}
4244
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004245status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004246{
4247 sp<ThreadBase> thread = mThread.promote();
4248 if (thread != 0) {
4249 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004250 return recordThread->start(this, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004251 } else {
4252 return BAD_VALUE;
4253 }
4254}
4255
4256void AudioFlinger::RecordThread::RecordTrack::stop()
4257{
4258 sp<ThreadBase> thread = mThread.promote();
4259 if (thread != 0) {
4260 RecordThread *recordThread = (RecordThread *)thread.get();
4261 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004262 TrackBase::reset();
4263 // Force overerrun condition to avoid false overrun callback until first data is
4264 // read from buffer
4265 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004266 }
4267}
4268
4269void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4270{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004271 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004272 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004273 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004274 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004275 mSessionId,
4276 mFrameCount,
4277 mState,
4278 mCblk->sampleRate,
4279 mCblk->server,
4280 mCblk->user);
4281}
4282
4283
4284// ----------------------------------------------------------------------------
4285
4286AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004287 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004288 DuplicatingThread *sourceThread,
4289 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004290 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004291 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004292 int frameCount)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004293 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004294 mActive(false), mSourceThread(sourceThread)
4295{
4296
Mathias Agopian65ab4712010-07-14 17:59:35 -07004297 if (mCblk != NULL) {
4298 mCblk->flags |= CBLK_DIRECTION_OUT;
4299 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004300 mOutBuffer.frameCount = 0;
4301 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01004302 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004303 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4304 mCblk, mBuffer, mCblk->buffers,
4305 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004306 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004307 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004308 }
4309}
4310
4311AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4312{
4313 clearBufferQueue();
4314}
4315
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004316status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004317{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004318 status_t status = Track::start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004319 if (status != NO_ERROR) {
4320 return status;
4321 }
4322
4323 mActive = true;
4324 mRetryCount = 127;
4325 return status;
4326}
4327
4328void AudioFlinger::PlaybackThread::OutputTrack::stop()
4329{
4330 Track::stop();
4331 clearBufferQueue();
4332 mOutBuffer.frameCount = 0;
4333 mActive = false;
4334}
4335
4336bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4337{
4338 Buffer *pInBuffer;
4339 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004340 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004341 bool outputBufferFull = false;
4342 inBuffer.frameCount = frames;
4343 inBuffer.i16 = data;
4344
4345 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4346
4347 if (!mActive && frames != 0) {
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004348 start(0);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004349 sp<ThreadBase> thread = mThread.promote();
4350 if (thread != 0) {
4351 MixerThread *mixerThread = (MixerThread *)thread.get();
4352 if (mCblk->frameCount > frames){
4353 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4354 uint32_t startFrames = (mCblk->frameCount - frames);
4355 pInBuffer = new Buffer;
4356 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4357 pInBuffer->frameCount = startFrames;
4358 pInBuffer->i16 = pInBuffer->mBuffer;
4359 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4360 mBufferQueue.add(pInBuffer);
4361 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004362 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004363 }
4364 }
4365 }
4366 }
4367
4368 while (waitTimeLeftMs) {
4369 // First write pending buffers, then new data
4370 if (mBufferQueue.size()) {
4371 pInBuffer = mBufferQueue.itemAt(0);
4372 } else {
4373 pInBuffer = &inBuffer;
4374 }
4375
4376 if (pInBuffer->frameCount == 0) {
4377 break;
4378 }
4379
4380 if (mOutBuffer.frameCount == 0) {
4381 mOutBuffer.frameCount = pInBuffer->frameCount;
4382 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08004383 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01004384 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004385 outputBufferFull = true;
4386 break;
4387 }
4388 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4389 if (waitTimeLeftMs >= waitTimeMs) {
4390 waitTimeLeftMs -= waitTimeMs;
4391 } else {
4392 waitTimeLeftMs = 0;
4393 }
4394 }
4395
4396 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4397 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4398 mCblk->stepUser(outFrames);
4399 pInBuffer->frameCount -= outFrames;
4400 pInBuffer->i16 += outFrames * channelCount;
4401 mOutBuffer.frameCount -= outFrames;
4402 mOutBuffer.i16 += outFrames * channelCount;
4403
4404 if (pInBuffer->frameCount == 0) {
4405 if (mBufferQueue.size()) {
4406 mBufferQueue.removeAt(0);
4407 delete [] pInBuffer->mBuffer;
4408 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01004409 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004410 } else {
4411 break;
4412 }
4413 }
4414 }
4415
4416 // If we could not write all frames, allocate a buffer and queue it for next time.
4417 if (inBuffer.frameCount) {
4418 sp<ThreadBase> thread = mThread.promote();
4419 if (thread != 0 && !thread->standby()) {
4420 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4421 pInBuffer = new Buffer;
4422 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4423 pInBuffer->frameCount = inBuffer.frameCount;
4424 pInBuffer->i16 = pInBuffer->mBuffer;
4425 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4426 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01004427 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004428 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004429 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004430 }
4431 }
4432 }
4433
4434 // Calling write() with a 0 length buffer, means that no more data will be written:
4435 // If no more buffers are pending, fill output track buffer to make sure it is started
4436 // by output mixer.
4437 if (frames == 0 && mBufferQueue.size() == 0) {
4438 if (mCblk->user < mCblk->frameCount) {
4439 frames = mCblk->frameCount - mCblk->user;
4440 pInBuffer = new Buffer;
4441 pInBuffer->mBuffer = new int16_t[frames * channelCount];
4442 pInBuffer->frameCount = frames;
4443 pInBuffer->i16 = pInBuffer->mBuffer;
4444 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4445 mBufferQueue.add(pInBuffer);
4446 } else if (mActive) {
4447 stop();
4448 }
4449 }
4450
4451 return outputBufferFull;
4452}
4453
4454status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4455{
4456 int active;
4457 status_t result;
4458 audio_track_cblk_t* cblk = mCblk;
4459 uint32_t framesReq = buffer->frameCount;
4460
Steve Block3856b092011-10-20 11:56:00 +01004461// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004462 buffer->frameCount = 0;
4463
4464 uint32_t framesAvail = cblk->framesAvailable();
4465
4466
4467 if (framesAvail == 0) {
4468 Mutex::Autolock _l(cblk->lock);
4469 goto start_loop_here;
4470 while (framesAvail == 0) {
4471 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004472 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004473 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004474 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004475 }
4476 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4477 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004478 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004479 }
4480 // read the server count again
4481 start_loop_here:
4482 framesAvail = cblk->framesAvailable_l();
4483 }
4484 }
4485
4486// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004487// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004488// }
4489
4490 if (framesReq > framesAvail) {
4491 framesReq = framesAvail;
4492 }
4493
4494 uint32_t u = cblk->user;
4495 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4496
4497 if (u + framesReq > bufferEnd) {
4498 framesReq = bufferEnd - u;
4499 }
4500
4501 buffer->frameCount = framesReq;
4502 buffer->raw = (void *)cblk->buffer(u);
4503 return NO_ERROR;
4504}
4505
4506
4507void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4508{
4509 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004510
4511 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004512 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004513 delete [] pBuffer->mBuffer;
4514 delete pBuffer;
4515 }
4516 mBufferQueue.clear();
4517}
4518
4519// ----------------------------------------------------------------------------
4520
4521AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4522 : RefBase(),
4523 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08004524 // 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 -07004525 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08004526 mPid(pid),
4527 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004528{
4529 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4530}
4531
4532// Client destructor must be called with AudioFlinger::mLock held
4533AudioFlinger::Client::~Client()
4534{
4535 mAudioFlinger->removeClient_l(mPid);
4536}
4537
Glenn Kasten435dbe62012-01-30 10:15:48 -08004538sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004539{
4540 return mMemoryDealer;
4541}
4542
John Grossman4ff14ba2012-02-08 16:37:41 -08004543// Reserve one of the limited slots for a timed audio track associated
4544// with this client
4545bool AudioFlinger::Client::reserveTimedTrack()
4546{
4547 const int kMaxTimedTracksPerClient = 4;
4548
4549 Mutex::Autolock _l(mTimedTrackLock);
4550
4551 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4552 ALOGW("can not create timed track - pid %d has exceeded the limit",
4553 mPid);
4554 return false;
4555 }
4556
4557 mTimedTrackCount++;
4558 return true;
4559}
4560
4561// Release a slot for a timed audio track
4562void AudioFlinger::Client::releaseTimedTrack()
4563{
4564 Mutex::Autolock _l(mTimedTrackLock);
4565 mTimedTrackCount--;
4566}
4567
Mathias Agopian65ab4712010-07-14 17:59:35 -07004568// ----------------------------------------------------------------------------
4569
4570AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4571 const sp<IAudioFlingerClient>& client,
4572 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004573 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004574{
4575}
4576
4577AudioFlinger::NotificationClient::~NotificationClient()
4578{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004579}
4580
4581void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4582{
4583 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08004584 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004585}
4586
4587// ----------------------------------------------------------------------------
4588
4589AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4590 : BnAudioTrack(),
4591 mTrack(track)
4592{
4593}
4594
4595AudioFlinger::TrackHandle::~TrackHandle() {
4596 // just stop the track on deletion, associated resources
4597 // will be freed from the main thread once all pending buffers have
4598 // been played. Unless it's not in the active track list, in which
4599 // case we free everything now...
4600 mTrack->destroy();
4601}
4602
Glenn Kasten90716c52012-01-26 13:40:12 -08004603sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4604 return mTrack->getCblk();
4605}
4606
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004607status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4608 return mTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004609}
4610
4611void AudioFlinger::TrackHandle::stop() {
4612 mTrack->stop();
4613}
4614
4615void AudioFlinger::TrackHandle::flush() {
4616 mTrack->flush();
4617}
4618
4619void AudioFlinger::TrackHandle::mute(bool e) {
4620 mTrack->mute(e);
4621}
4622
4623void AudioFlinger::TrackHandle::pause() {
4624 mTrack->pause();
4625}
4626
Mathias Agopian65ab4712010-07-14 17:59:35 -07004627status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4628{
4629 return mTrack->attachAuxEffect(EffectId);
4630}
4631
John Grossman4ff14ba2012-02-08 16:37:41 -08004632status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4633 sp<IMemory>* buffer) {
4634 if (!mTrack->isTimedTrack())
4635 return INVALID_OPERATION;
4636
4637 PlaybackThread::TimedTrack* tt =
4638 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4639 return tt->allocateTimedBuffer(size, buffer);
4640}
4641
4642status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4643 int64_t pts) {
4644 if (!mTrack->isTimedTrack())
4645 return INVALID_OPERATION;
4646
4647 PlaybackThread::TimedTrack* tt =
4648 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4649 return tt->queueTimedBuffer(buffer, pts);
4650}
4651
4652status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4653 const LinearTransform& xform, int target) {
4654
4655 if (!mTrack->isTimedTrack())
4656 return INVALID_OPERATION;
4657
4658 PlaybackThread::TimedTrack* tt =
4659 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4660 return tt->setMediaTimeTransform(
4661 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4662}
4663
Mathias Agopian65ab4712010-07-14 17:59:35 -07004664status_t AudioFlinger::TrackHandle::onTransact(
4665 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4666{
4667 return BnAudioTrack::onTransact(code, data, reply, flags);
4668}
4669
4670// ----------------------------------------------------------------------------
4671
4672sp<IAudioRecord> AudioFlinger::openRecord(
4673 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004674 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004675 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004676 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004677 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004678 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08004679 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004680 int *sessionId,
4681 status_t *status)
4682{
4683 sp<RecordThread::RecordTrack> recordTrack;
4684 sp<RecordHandle> recordHandle;
4685 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004686 status_t lStatus;
4687 RecordThread *thread;
4688 size_t inFrameCount;
4689 int lSessionId;
4690
4691 // check calling permissions
4692 if (!recordingAllowed()) {
4693 lStatus = PERMISSION_DENIED;
4694 goto Exit;
4695 }
4696
4697 // add client to list
4698 { // scope for mLock
4699 Mutex::Autolock _l(mLock);
4700 thread = checkRecordThread_l(input);
4701 if (thread == NULL) {
4702 lStatus = BAD_VALUE;
4703 goto Exit;
4704 }
4705
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004706 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004707
4708 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004709 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004710 lSessionId = *sessionId;
4711 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004712 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004713 if (sessionId != NULL) {
4714 *sessionId = lSessionId;
4715 }
4716 }
4717 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004718 recordTrack = thread->createRecordTrack_l(client,
4719 sampleRate,
4720 format,
4721 channelMask,
4722 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004723 lSessionId,
4724 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004725 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004726 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004727 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4728 // destructor is called by the TrackBase destructor with mLock held
4729 client.clear();
4730 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004731 goto Exit;
4732 }
4733
4734 // return to handle to client
4735 recordHandle = new RecordHandle(recordTrack);
4736 lStatus = NO_ERROR;
4737
4738Exit:
4739 if (status) {
4740 *status = lStatus;
4741 }
4742 return recordHandle;
4743}
4744
4745// ----------------------------------------------------------------------------
4746
4747AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4748 : BnAudioRecord(),
4749 mRecordTrack(recordTrack)
4750{
4751}
4752
4753AudioFlinger::RecordHandle::~RecordHandle() {
4754 stop();
4755}
4756
Glenn Kasten90716c52012-01-26 13:40:12 -08004757sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4758 return mRecordTrack->getCblk();
4759}
4760
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004761status_t AudioFlinger::RecordHandle::start(pid_t tid) {
Steve Block3856b092011-10-20 11:56:00 +01004762 ALOGV("RecordHandle::start()");
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004763 return mRecordTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004764}
4765
4766void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004767 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004768 mRecordTrack->stop();
4769}
4770
Mathias Agopian65ab4712010-07-14 17:59:35 -07004771status_t AudioFlinger::RecordHandle::onTransact(
4772 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4773{
4774 return BnAudioRecord::onTransact(code, data, reply, flags);
4775}
4776
4777// ----------------------------------------------------------------------------
4778
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004779AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4780 AudioStreamIn *input,
4781 uint32_t sampleRate,
4782 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004783 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004784 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004785 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004786 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4787 // mRsmpInIndex and mInputBytes set by readInputParameters()
4788 mReqChannelCount(popcount(channels)),
4789 mReqSampleRate(sampleRate)
4790 // mBytesRead is only meaningful while active, and so is cleared in start()
4791 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004792{
Glenn Kasten480b4682012-02-28 12:30:08 -08004793 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07004794
Mathias Agopian65ab4712010-07-14 17:59:35 -07004795 readInputParameters();
4796}
4797
4798
4799AudioFlinger::RecordThread::~RecordThread()
4800{
4801 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004802 delete mResampler;
4803 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004804}
4805
4806void AudioFlinger::RecordThread::onFirstRef()
4807{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004808 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004809}
4810
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004811status_t AudioFlinger::RecordThread::readyToRun()
4812{
4813 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004814 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004815 return status;
4816}
4817
Mathias Agopian65ab4712010-07-14 17:59:35 -07004818bool AudioFlinger::RecordThread::threadLoop()
4819{
4820 AudioBufferProvider::Buffer buffer;
4821 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004822 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004823
Eric Laurent44d98482010-09-30 16:12:31 -07004824 nsecs_t lastWarning = 0;
4825
Eric Laurentfeb0db62011-07-22 09:04:31 -07004826 acquireWakeLock();
4827
Mathias Agopian65ab4712010-07-14 17:59:35 -07004828 // start recording
4829 while (!exitPending()) {
4830
4831 processConfigEvents();
4832
4833 { // scope for mLock
4834 Mutex::Autolock _l(mLock);
4835 checkForNewParameters_l();
4836 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4837 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004838 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004839 mStandby = true;
4840 }
4841
4842 if (exitPending()) break;
4843
Eric Laurentfeb0db62011-07-22 09:04:31 -07004844 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004845 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004846 // go to sleep
4847 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004848 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004849 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004850 continue;
4851 }
4852 if (mActiveTrack != 0) {
4853 if (mActiveTrack->mState == TrackBase::PAUSING) {
4854 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004855 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004856 mStandby = true;
4857 }
4858 mActiveTrack.clear();
4859 mStartStopCond.broadcast();
4860 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4861 if (mReqChannelCount != mActiveTrack->channelCount()) {
4862 mActiveTrack.clear();
4863 mStartStopCond.broadcast();
4864 } else if (mBytesRead != 0) {
4865 // record start succeeds only if first read from audio input
4866 // succeeds
4867 if (mBytesRead > 0) {
4868 mActiveTrack->mState = TrackBase::ACTIVE;
4869 } else {
4870 mActiveTrack.clear();
4871 }
4872 mStartStopCond.broadcast();
4873 }
4874 mStandby = false;
4875 }
4876 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004877 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004878 }
4879
4880 if (mActiveTrack != 0) {
4881 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4882 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004883 unlockEffectChains(effectChains);
4884 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004885 continue;
4886 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004887 for (size_t i = 0; i < effectChains.size(); i ++) {
4888 effectChains[i]->process_l();
4889 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004890
Mathias Agopian65ab4712010-07-14 17:59:35 -07004891 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004892 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004893 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004894 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004895 // no resampling
4896 while (framesOut) {
4897 size_t framesIn = mFrameCount - mRsmpInIndex;
4898 if (framesIn) {
4899 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4900 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4901 if (framesIn > framesOut)
4902 framesIn = framesOut;
4903 mRsmpInIndex += framesIn;
4904 framesOut -= framesIn;
4905 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004906 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004907 memcpy(dst, src, framesIn * mFrameSize);
4908 } else {
4909 int16_t *src16 = (int16_t *)src;
4910 int16_t *dst16 = (int16_t *)dst;
4911 if (mChannelCount == 1) {
4912 while (framesIn--) {
4913 *dst16++ = *src16;
4914 *dst16++ = *src16++;
4915 }
4916 } else {
4917 while (framesIn--) {
4918 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4919 src16 += 2;
4920 }
4921 }
4922 }
4923 }
4924 if (framesOut && mFrameCount == mRsmpInIndex) {
4925 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004926 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004927 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004928 framesOut = 0;
4929 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004930 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004931 mRsmpInIndex = 0;
4932 }
4933 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004934 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004935 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4936 // Force input into standby so that it tries to
4937 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004938 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004939 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004940 }
4941 mRsmpInIndex = mFrameCount;
4942 framesOut = 0;
4943 buffer.frameCount = 0;
4944 }
4945 }
4946 }
4947 } else {
4948 // resampling
4949
4950 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4951 // alter output frame count as if we were expecting stereo samples
4952 if (mChannelCount == 1 && mReqChannelCount == 1) {
4953 framesOut >>= 1;
4954 }
4955 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4956 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4957 // are 32 bit aligned which should be always true.
4958 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004959 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004960 // the resampler always outputs stereo samples: do post stereo to mono conversion
4961 int16_t *src = (int16_t *)mRsmpOutBuffer;
4962 int16_t *dst = buffer.i16;
4963 while (framesOut--) {
4964 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4965 src += 2;
4966 }
4967 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004968 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004969 }
4970
4971 }
4972 mActiveTrack->releaseBuffer(&buffer);
4973 mActiveTrack->overflow();
4974 }
4975 // client isn't retrieving buffers fast enough
4976 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004977 if (!mActiveTrack->setOverflow()) {
4978 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004979 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004980 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004981 lastWarning = now;
4982 }
4983 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004984 // Release the processor for a while before asking for a new buffer.
4985 // This will give the application more chance to read from the buffer and
4986 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004987 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004988 }
4989 }
Eric Laurentec437d82011-07-26 20:54:46 -07004990 // enable changes in effect chain
4991 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004992 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004993 }
4994
4995 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004996 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004997 }
4998 mActiveTrack.clear();
4999
5000 mStartStopCond.broadcast();
5001
Eric Laurentfeb0db62011-07-22 09:04:31 -07005002 releaseWakeLock();
5003
Steve Block3856b092011-10-20 11:56:00 +01005004 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005005 return false;
5006}
5007
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005008
5009sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5010 const sp<AudioFlinger::Client>& client,
5011 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005012 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005013 int channelMask,
5014 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005015 int sessionId,
5016 status_t *status)
5017{
5018 sp<RecordTrack> track;
5019 status_t lStatus;
5020
5021 lStatus = initCheck();
5022 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005023 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005024 goto Exit;
5025 }
5026
5027 { // scope for mLock
5028 Mutex::Autolock _l(mLock);
5029
5030 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005031 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005032
Glenn Kasten7378ca52012-01-20 13:44:40 -08005033 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005034 lStatus = NO_MEMORY;
5035 goto Exit;
5036 }
5037
5038 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005039 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5040 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005041 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005042 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5043 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005044 }
5045 lStatus = NO_ERROR;
5046
5047Exit:
5048 if (status) {
5049 *status = lStatus;
5050 }
5051 return track;
5052}
5053
Glenn Kasten6dbc1352012-02-02 10:56:47 -08005054status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005055{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08005056 ALOGV("RecordThread::start tid=%d", tid);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005057 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005058 status_t status = NO_ERROR;
5059 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005060 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005061 if (mActiveTrack != 0) {
5062 if (recordTrack != mActiveTrack.get()) {
5063 status = -EBUSY;
5064 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5065 mActiveTrack->mState = TrackBase::ACTIVE;
5066 }
5067 return status;
5068 }
5069
5070 recordTrack->mState = TrackBase::IDLE;
5071 mActiveTrack = recordTrack;
5072 mLock.unlock();
5073 status_t status = AudioSystem::startInput(mId);
5074 mLock.lock();
5075 if (status != NO_ERROR) {
5076 mActiveTrack.clear();
5077 return status;
5078 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005079 mRsmpInIndex = mFrameCount;
5080 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005081 if (mResampler != NULL) {
5082 mResampler->reset();
5083 }
5084 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005085 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005086 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005087 mWaitWorkCV.signal();
5088 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005089 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005090 mActiveTrack.clear();
5091 status = INVALID_OPERATION;
5092 goto startError;
5093 }
5094 mStartStopCond.wait(mLock);
5095 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005096 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005097 status = BAD_VALUE;
5098 goto startError;
5099 }
Steve Block3856b092011-10-20 11:56:00 +01005100 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005101 return status;
5102 }
5103startError:
5104 AudioSystem::stopInput(mId);
5105 return status;
5106}
5107
5108void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005109 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005110 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005111 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005112 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005113 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5114 mActiveTrack->mState = TrackBase::PAUSING;
5115 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005116 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005117 return;
5118 }
5119 mStartStopCond.wait(mLock);
5120 // if we have been restarted, recordTrack == mActiveTrack.get() here
5121 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5122 mLock.unlock();
5123 AudioSystem::stopInput(mId);
5124 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005125 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005126 }
5127 }
5128 }
5129}
5130
5131status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5132{
5133 const size_t SIZE = 256;
5134 char buffer[SIZE];
5135 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005136
5137 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5138 result.append(buffer);
5139
5140 if (mActiveTrack != 0) {
5141 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005142 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005143 mActiveTrack->dump(buffer, SIZE);
5144 result.append(buffer);
5145
5146 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5147 result.append(buffer);
5148 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5149 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005150 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005151 result.append(buffer);
5152 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5153 result.append(buffer);
5154 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5155 result.append(buffer);
5156
5157
5158 } else {
5159 result.append("No record client\n");
5160 }
5161 write(fd, result.string(), result.size());
5162
5163 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005164 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005165
5166 return NO_ERROR;
5167}
5168
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005169// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005170status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005171{
5172 size_t framesReq = buffer->frameCount;
5173 size_t framesReady = mFrameCount - mRsmpInIndex;
5174 int channelCount;
5175
5176 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005177 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005178 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005179 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005180 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5181 // Force input into standby so that it tries to
5182 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005183 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005184 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005185 }
Glenn Kastene0feee32011-12-13 11:53:26 -08005186 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005187 buffer->frameCount = 0;
5188 return NOT_ENOUGH_DATA;
5189 }
5190 mRsmpInIndex = 0;
5191 framesReady = mFrameCount;
5192 }
5193
5194 if (framesReq > framesReady) {
5195 framesReq = framesReady;
5196 }
5197
5198 if (mChannelCount == 1 && mReqChannelCount == 2) {
5199 channelCount = 1;
5200 } else {
5201 channelCount = 2;
5202 }
5203 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5204 buffer->frameCount = framesReq;
5205 return NO_ERROR;
5206}
5207
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005208// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07005209void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5210{
5211 mRsmpInIndex += buffer->frameCount;
5212 buffer->frameCount = 0;
5213}
5214
5215bool AudioFlinger::RecordThread::checkForNewParameters_l()
5216{
5217 bool reconfig = false;
5218
5219 while (!mNewParameters.isEmpty()) {
5220 status_t status = NO_ERROR;
5221 String8 keyValuePair = mNewParameters[0];
5222 AudioParameter param = AudioParameter(keyValuePair);
5223 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08005224 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005225 int reqSamplingRate = mReqSampleRate;
5226 int reqChannelCount = mReqChannelCount;
5227
5228 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5229 reqSamplingRate = value;
5230 reconfig = true;
5231 }
5232 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08005233 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005234 reconfig = true;
5235 }
5236 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005237 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005238 reconfig = true;
5239 }
5240 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5241 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08005242 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005243 // if frame count is changed after track creation
5244 if (mActiveTrack != 0) {
5245 status = INVALID_OPERATION;
5246 } else {
5247 reconfig = true;
5248 }
5249 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005250 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5251 // forward device change to effects that have requested to be
5252 // aware of attached audio device.
5253 for (size_t i = 0; i < mEffectChains.size(); i++) {
5254 mEffectChains[i]->setDevice_l(value);
5255 }
5256 // store input device and output device but do not forward output device to audio HAL.
5257 // Note that status is ignored by the caller for output device
5258 // (see AudioFlinger::setParameters()
5259 if (value & AUDIO_DEVICE_OUT_ALL) {
5260 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5261 status = BAD_VALUE;
5262 } else {
5263 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07005264 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5265 if (mTrack != NULL) {
5266 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005267 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005268 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5269 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5270 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005271 }
5272 mDevice |= (uint32_t)value;
5273 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005274 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005275 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005276 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005277 mInput->stream->common.standby(&mInput->stream->common);
5278 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5279 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005280 }
5281 if (reconfig) {
5282 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005283 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005284 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005285 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08005286 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
5287 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005288 status = NO_ERROR;
5289 }
5290 if (status == NO_ERROR) {
5291 readInputParameters();
5292 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5293 }
5294 }
5295 }
5296
5297 mNewParameters.removeAt(0);
5298
5299 mParamStatus = status;
5300 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07005301 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5302 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08005303 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005304 }
5305 return reconfig;
5306}
5307
5308String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5309{
Dima Zavinfce7a472011-04-19 22:30:36 -07005310 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005311 String8 out_s8 = String8();
5312
5313 Mutex::Autolock _l(mLock);
5314 if (initCheck() != NO_ERROR) {
5315 return out_s8;
5316 }
Dima Zavinfce7a472011-04-19 22:30:36 -07005317
Dima Zavin799a70e2011-04-18 16:57:27 -07005318 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07005319 out_s8 = String8(s);
5320 free(s);
5321 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005322}
5323
5324void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5325 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08005326 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005327
5328 switch (event) {
5329 case AudioSystem::INPUT_OPENED:
5330 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005331 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005332 desc.samplingRate = mSampleRate;
5333 desc.format = mFormat;
5334 desc.frameCount = mFrameCount;
5335 desc.latency = 0;
5336 param2 = &desc;
5337 break;
5338
5339 case AudioSystem::INPUT_CLOSED:
5340 default:
5341 break;
5342 }
5343 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5344}
5345
5346void AudioFlinger::RecordThread::readInputParameters()
5347{
Glenn Kastene9dd0172012-01-27 18:08:45 -08005348 delete mRsmpInBuffer;
5349 // mRsmpInBuffer is always assigned a new[] below
5350 delete mRsmpOutBuffer;
5351 mRsmpOutBuffer = NULL;
5352 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08005353 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005354
Dima Zavin799a70e2011-04-18 16:57:27 -07005355 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005356 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5357 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07005358 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08005359 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07005360 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005361 mFrameCount = mInputBytes / mFrameSize;
5362 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5363
Glenn Kasten53d76db2012-03-08 12:32:47 -08005364 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005365 {
5366 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005367 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5368 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005369 if (mChannelCount == 1 && mReqChannelCount == 2) {
5370 channelCount = 1;
5371 } else {
5372 channelCount = 2;
5373 }
5374 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5375 mResampler->setSampleRate(mSampleRate);
5376 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5377 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5378
5379 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5380 if (mChannelCount == 1 && mReqChannelCount == 1) {
5381 mFrameCount >>= 1;
5382 }
5383
5384 }
5385 mRsmpInIndex = mFrameCount;
5386}
5387
5388unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5389{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005390 Mutex::Autolock _l(mLock);
5391 if (initCheck() != NO_ERROR) {
5392 return 0;
5393 }
5394
Dima Zavin799a70e2011-04-18 16:57:27 -07005395 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005396}
5397
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005398uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5399{
5400 Mutex::Autolock _l(mLock);
5401 uint32_t result = 0;
5402 if (getEffectChain_l(sessionId) != 0) {
5403 result = EFFECT_SESSION;
5404 }
5405
5406 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5407 result |= TRACK_SESSION;
5408 }
5409
5410 return result;
5411}
5412
Eric Laurent59bd0da2011-08-01 09:52:20 -07005413AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5414{
5415 Mutex::Autolock _l(mLock);
5416 return mTrack;
5417}
5418
Glenn Kastenaed850d2012-01-26 09:46:34 -08005419AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005420{
5421 Mutex::Autolock _l(mLock);
5422 return mInput;
5423}
5424
5425AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5426{
5427 Mutex::Autolock _l(mLock);
5428 AudioStreamIn *input = mInput;
5429 mInput = NULL;
5430 return input;
5431}
5432
5433// this method must always be called either with ThreadBase mLock held or inside the thread loop
5434audio_stream_t* AudioFlinger::RecordThread::stream()
5435{
5436 if (mInput == NULL) {
5437 return NULL;
5438 }
5439 return &mInput->stream->common;
5440}
5441
5442
Mathias Agopian65ab4712010-07-14 17:59:35 -07005443// ----------------------------------------------------------------------------
5444
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005445audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005446 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005447 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005448 uint32_t *pChannels,
5449 uint32_t *pLatencyMs,
Glenn Kasten18868c52012-03-07 09:15:37 -08005450 audio_policy_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005451{
5452 status_t status;
5453 PlaybackThread *thread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005454 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005455 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005456 uint32_t channels = pChannels ? *pChannels : 0;
5457 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07005458 audio_stream_out_t *outStream;
5459 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005460
Steve Block3856b092011-10-20 11:56:00 +01005461 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07005462 pDevices ? *pDevices : 0,
5463 samplingRate,
5464 format,
5465 channels,
5466 flags);
5467
5468 if (pDevices == NULL || *pDevices == 0) {
5469 return 0;
5470 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005471
Mathias Agopian65ab4712010-07-14 17:59:35 -07005472 Mutex::Autolock _l(mLock);
5473
Dima Zavin799a70e2011-04-18 16:57:27 -07005474 outHwDev = findSuitableHwDev_l(*pDevices);
5475 if (outHwDev == NULL)
5476 return 0;
5477
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005478 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Glenn Kasten58f30212012-01-12 12:27:51 -08005479 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005480 &channels, &samplingRate, &outStream);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005481 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01005482 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005483 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005484 samplingRate,
5485 format,
5486 channels,
5487 status);
5488
Dima Zavin799a70e2011-04-18 16:57:27 -07005489 if (outStream != NULL) {
5490 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005491 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07005492
Dima Zavinfce7a472011-04-19 22:30:36 -07005493 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5494 (format != AUDIO_FORMAT_PCM_16_BIT) ||
5495 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005496 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005497 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005498 } else {
5499 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005500 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005501 }
5502 mPlaybackThreads.add(id, thread);
5503
Glenn Kastena0d68332012-01-27 16:47:15 -08005504 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5505 if (pFormat != NULL) *pFormat = format;
5506 if (pChannels != NULL) *pChannels = channels;
5507 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005508
5509 // notify client processes of the new output creation
5510 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5511 return id;
5512 }
5513
5514 return 0;
5515}
5516
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005517audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
5518 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005519{
5520 Mutex::Autolock _l(mLock);
5521 MixerThread *thread1 = checkMixerThread_l(output1);
5522 MixerThread *thread2 = checkMixerThread_l(output2);
5523
5524 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005525 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005526 return 0;
5527 }
5528
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005529 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005530 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5531 thread->addOutputTrack(thread2);
5532 mPlaybackThreads.add(id, thread);
5533 // notify client processes of the new output creation
5534 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5535 return id;
5536}
5537
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005538status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005539{
5540 // keep strong reference on the playback thread so that
5541 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005542 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005543 {
5544 Mutex::Autolock _l(mLock);
5545 thread = checkPlaybackThread_l(output);
5546 if (thread == NULL) {
5547 return BAD_VALUE;
5548 }
5549
Steve Block3856b092011-10-20 11:56:00 +01005550 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005551
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005552 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005553 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005554 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005555 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5556 dupThread->removeOutputTrack((MixerThread *)thread.get());
5557 }
5558 }
5559 }
Glenn Kastena1117922012-01-26 10:53:32 -08005560 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005561 mPlaybackThreads.removeItem(output);
5562 }
5563 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005564 // The thread entity (active unit of execution) is no longer running here,
5565 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005566
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005567 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005568 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005569 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005570 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005571 out->hwDev->close_output_stream(out->hwDev, out->stream);
5572 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005573 }
5574 return NO_ERROR;
5575}
5576
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005577status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005578{
5579 Mutex::Autolock _l(mLock);
5580 PlaybackThread *thread = checkPlaybackThread_l(output);
5581
5582 if (thread == NULL) {
5583 return BAD_VALUE;
5584 }
5585
Steve Block3856b092011-10-20 11:56:00 +01005586 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005587 thread->suspend();
5588
5589 return NO_ERROR;
5590}
5591
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005592status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005593{
5594 Mutex::Autolock _l(mLock);
5595 PlaybackThread *thread = checkPlaybackThread_l(output);
5596
5597 if (thread == NULL) {
5598 return BAD_VALUE;
5599 }
5600
Steve Block3856b092011-10-20 11:56:00 +01005601 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005602
5603 thread->restore();
5604
5605 return NO_ERROR;
5606}
5607
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005608audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005609 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005610 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005611 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005612 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005613{
5614 status_t status;
5615 RecordThread *thread = NULL;
5616 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005617 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005618 uint32_t channels = pChannels ? *pChannels : 0;
5619 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005620 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005621 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005622 audio_stream_in_t *inStream;
5623 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005624
5625 if (pDevices == NULL || *pDevices == 0) {
5626 return 0;
5627 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005628
Mathias Agopian65ab4712010-07-14 17:59:35 -07005629 Mutex::Autolock _l(mLock);
5630
Dima Zavin799a70e2011-04-18 16:57:27 -07005631 inHwDev = findSuitableHwDev_l(*pDevices);
5632 if (inHwDev == NULL)
5633 return 0;
5634
Glenn Kasten58f30212012-01-12 12:27:51 -08005635 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005636 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005637 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005638 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005639 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005640 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005641 samplingRate,
5642 format,
5643 channels,
5644 acoustics,
5645 status);
5646
5647 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5648 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5649 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005650 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005651 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005652 (samplingRate <= 2 * reqSamplingRate) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08005653 (popcount(channels) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01005654 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005655 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005656 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005657 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005658 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005659 }
5660
Dima Zavin799a70e2011-04-18 16:57:27 -07005661 if (inStream != NULL) {
5662 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5663
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005664 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005665 // Start record thread
5666 // RecorThread require both input and output device indication to forward to audio
5667 // pre processing modules
5668 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5669 thread = new RecordThread(this,
5670 input,
5671 reqSamplingRate,
5672 reqChannels,
5673 id,
5674 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005675 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005676 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005677 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5678 if (pFormat != NULL) *pFormat = format;
5679 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005680
Dima Zavin799a70e2011-04-18 16:57:27 -07005681 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005682
5683 // notify client processes of the new input creation
5684 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5685 return id;
5686 }
5687
5688 return 0;
5689}
5690
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005691status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005692{
5693 // keep strong reference on the record thread so that
5694 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005695 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005696 {
5697 Mutex::Autolock _l(mLock);
5698 thread = checkRecordThread_l(input);
5699 if (thread == NULL) {
5700 return BAD_VALUE;
5701 }
5702
Steve Block3856b092011-10-20 11:56:00 +01005703 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08005704 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005705 mRecordThreads.removeItem(input);
5706 }
5707 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005708 // The thread entity (active unit of execution) is no longer running here,
5709 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005710
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005711 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005712 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005713 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005714 in->hwDev->close_input_stream(in->hwDev, in->stream);
5715 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005716
5717 return NO_ERROR;
5718}
5719
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005720status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005721{
5722 Mutex::Autolock _l(mLock);
5723 MixerThread *dstThread = checkMixerThread_l(output);
5724 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005725 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005726 return BAD_VALUE;
5727 }
5728
Steve Block3856b092011-10-20 11:56:00 +01005729 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005730 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5731
Eric Laurent9f6530f2011-08-30 10:18:54 -07005732 dstThread->setStreamValid(stream, true);
5733
Mathias Agopian65ab4712010-07-14 17:59:35 -07005734 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5735 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08005736 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005737 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005738 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005739 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005740 }
Eric Laurentde070132010-07-13 04:45:46 -07005741 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005742
5743 return NO_ERROR;
5744}
5745
5746
5747int AudioFlinger::newAudioSessionId()
5748{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005749 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005750}
5751
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005752void AudioFlinger::acquireAudioSessionId(int audioSession)
5753{
5754 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005755 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005756 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005757 size_t num = mAudioSessionRefs.size();
5758 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005759 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005760 if (ref->mSessionid == audioSession && ref->mPid == caller) {
5761 ref->mCnt++;
5762 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005763 return;
5764 }
5765 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005766 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5767 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005768}
5769
5770void AudioFlinger::releaseAudioSessionId(int audioSession)
5771{
5772 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005773 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005774 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005775 size_t num = mAudioSessionRefs.size();
5776 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005777 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005778 if (ref->mSessionid == audioSession && ref->mPid == caller) {
5779 ref->mCnt--;
5780 ALOGV(" decremented refcount to %d", ref->mCnt);
5781 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005782 mAudioSessionRefs.removeAt(i);
5783 delete ref;
5784 purgeStaleEffects_l();
5785 }
5786 return;
5787 }
5788 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005789 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005790}
5791
5792void AudioFlinger::purgeStaleEffects_l() {
5793
Steve Block3856b092011-10-20 11:56:00 +01005794 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005795
5796 Vector< sp<EffectChain> > chains;
5797
5798 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5799 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5800 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5801 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005802 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5803 chains.push(ec);
5804 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005805 }
5806 }
5807 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5808 sp<RecordThread> t = mRecordThreads.valueAt(i);
5809 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5810 sp<EffectChain> ec = t->mEffectChains[j];
5811 chains.push(ec);
5812 }
5813 }
5814
5815 for (size_t i = 0; i < chains.size(); i++) {
5816 sp<EffectChain> ec = chains[i];
5817 int sessionid = ec->sessionId();
5818 sp<ThreadBase> t = ec->mThread.promote();
5819 if (t == 0) {
5820 continue;
5821 }
5822 size_t numsessionrefs = mAudioSessionRefs.size();
5823 bool found = false;
5824 for (size_t k = 0; k < numsessionrefs; k++) {
5825 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005826 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005827 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005828 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005829 found = true;
5830 break;
5831 }
5832 }
5833 if (!found) {
5834 // remove all effects from the chain
5835 while (ec->mEffects.size()) {
5836 sp<EffectModule> effect = ec->mEffects[0];
5837 effect->unPin();
5838 Mutex::Autolock _l (t->mLock);
5839 t->removeEffect_l(effect);
5840 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5841 sp<EffectHandle> handle = effect->mHandles[j].promote();
5842 if (handle != 0) {
5843 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005844 if (handle->mHasControl && handle->mEnabled) {
5845 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5846 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005847 }
5848 }
5849 AudioSystem::unregisterEffect(effect->id());
5850 }
5851 }
5852 }
5853 return;
5854}
5855
Mathias Agopian65ab4712010-07-14 17:59:35 -07005856// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005857AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005858{
Glenn Kastena1117922012-01-26 10:53:32 -08005859 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005860}
5861
5862// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005863AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005864{
5865 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08005866 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005867}
5868
5869// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005870AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005871{
Glenn Kastena1117922012-01-26 10:53:32 -08005872 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005873}
5874
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005875uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005876{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005877 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005878}
5879
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08005880AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005881{
5882 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5883 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005884 AudioStreamOut *output = thread->getOutput();
5885 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005886 return thread;
5887 }
5888 }
5889 return NULL;
5890}
5891
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08005892uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005893{
5894 PlaybackThread *thread = primaryPlaybackThread_l();
5895
5896 if (thread == NULL) {
5897 return 0;
5898 }
5899
5900 return thread->device();
5901}
5902
5903
Mathias Agopian65ab4712010-07-14 17:59:35 -07005904// ----------------------------------------------------------------------------
5905// Effect management
5906// ----------------------------------------------------------------------------
5907
5908
Glenn Kastenf587ba52012-01-26 16:25:10 -08005909status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005910{
5911 Mutex::Autolock _l(mLock);
5912 return EffectQueryNumberEffects(numEffects);
5913}
5914
Glenn Kastenf587ba52012-01-26 16:25:10 -08005915status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005916{
5917 Mutex::Autolock _l(mLock);
5918 return EffectQueryEffect(index, descriptor);
5919}
5920
Glenn Kasten5e92a782012-01-30 07:40:52 -08005921status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08005922 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005923{
5924 Mutex::Autolock _l(mLock);
5925 return EffectGetDescriptor(pUuid, descriptor);
5926}
5927
5928
Mathias Agopian65ab4712010-07-14 17:59:35 -07005929sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5930 effect_descriptor_t *pDesc,
5931 const sp<IEffectClient>& effectClient,
5932 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005933 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005934 int sessionId,
5935 status_t *status,
5936 int *id,
5937 int *enabled)
5938{
5939 status_t lStatus = NO_ERROR;
5940 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005941 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005942
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005943 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005944 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005945
5946 if (pDesc == NULL) {
5947 lStatus = BAD_VALUE;
5948 goto Exit;
5949 }
5950
Eric Laurent84e9a102010-09-23 16:10:16 -07005951 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005952 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005953 lStatus = PERMISSION_DENIED;
5954 goto Exit;
5955 }
5956
Dima Zavinfce7a472011-04-19 22:30:36 -07005957 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005958 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08005959 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005960 lStatus = PERMISSION_DENIED;
5961 goto Exit;
5962 }
5963
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005964 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005965 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005966 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005967 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005968 lStatus = BAD_VALUE;
5969 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005970 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005971 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005972 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005973 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005974 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005975 }
5976 }
5977
Mathias Agopian65ab4712010-07-14 17:59:35 -07005978 {
5979 Mutex::Autolock _l(mLock);
5980
Mathias Agopian65ab4712010-07-14 17:59:35 -07005981
5982 if (!EffectIsNullUuid(&pDesc->uuid)) {
5983 // if uuid is specified, request effect descriptor
5984 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5985 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005986 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005987 goto Exit;
5988 }
5989 } else {
5990 // if uuid is not specified, look for an available implementation
5991 // of the required type in effect factory
5992 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005993 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005994 lStatus = BAD_VALUE;
5995 goto Exit;
5996 }
5997 uint32_t numEffects = 0;
5998 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005999 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07006000 bool found = false;
6001
6002 lStatus = EffectQueryNumberEffects(&numEffects);
6003 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006004 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006005 goto Exit;
6006 }
6007 for (uint32_t i = 0; i < numEffects; i++) {
6008 lStatus = EffectQueryEffect(i, &desc);
6009 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006010 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006011 continue;
6012 }
6013 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
6014 // If matching type found save effect descriptor. If the session is
6015 // 0 and the effect is not auxiliary, continue enumeration in case
6016 // an auxiliary version of this effect type is available
6017 found = true;
6018 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07006019 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006020 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6021 break;
6022 }
6023 }
6024 }
6025 if (!found) {
6026 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00006027 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006028 goto Exit;
6029 }
6030 // For same effect type, chose auxiliary version over insert version if
6031 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07006032 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006033 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
6034 memcpy(&desc, &d, sizeof(effect_descriptor_t));
6035 }
6036 }
6037
6038 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07006039 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006040 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6041 lStatus = INVALID_OPERATION;
6042 goto Exit;
6043 }
6044
Eric Laurent59255e42011-07-27 19:49:51 -07006045 // check recording permission for visualizer
6046 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
6047 !recordingAllowed()) {
6048 lStatus = PERMISSION_DENIED;
6049 goto Exit;
6050 }
6051
Mathias Agopian65ab4712010-07-14 17:59:35 -07006052 // return effect descriptor
6053 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
6054
6055 // If output is not specified try to find a matching audio session ID in one of the
6056 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07006057 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
6058 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006059 // Note: io is never 0 when creating an effect on an input
6060 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006061 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07006062 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6063 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006064 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07006065 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07006066 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006067 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006068 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006069 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6070 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6071 io = mRecordThreads.keyAt(i);
6072 break;
6073 }
6074 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006075 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006076 // If no output thread contains the requested session ID, default to
6077 // first output. The effect chain will be moved to the correct output
6078 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006079 if (io == 0 && mPlaybackThreads.size()) {
6080 io = mPlaybackThreads.keyAt(0);
6081 }
Steve Block3856b092011-10-20 11:56:00 +01006082 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006083 }
6084 ThreadBase *thread = checkRecordThread_l(io);
6085 if (thread == NULL) {
6086 thread = checkPlaybackThread_l(io);
6087 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00006088 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006089 lStatus = BAD_VALUE;
6090 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07006091 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006092 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006093
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006094 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006095
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006096 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07006097 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6098 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006099 if (handle != 0 && id != NULL) {
6100 *id = handle->id();
6101 }
6102 }
6103
6104Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006105 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006106 *status = lStatus;
6107 }
6108 return handle;
6109}
6110
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006111status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
6112 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07006113{
Steve Block3856b092011-10-20 11:56:00 +01006114 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07006115 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006116 Mutex::Autolock _l(mLock);
6117 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006118 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006119 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006120 }
Eric Laurentde070132010-07-13 04:45:46 -07006121 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6122 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006123 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006124 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006125 }
Eric Laurentde070132010-07-13 04:45:46 -07006126 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6127 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006128 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006129 return BAD_VALUE;
6130 }
6131
6132 Mutex::Autolock _dl(dstThread->mLock);
6133 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07006134 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07006135
Mathias Agopian65ab4712010-07-14 17:59:35 -07006136 return NO_ERROR;
6137}
6138
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006139// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07006140status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07006141 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07006142 AudioFlinger::PlaybackThread *dstThread,
6143 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07006144{
Steve Block3856b092011-10-20 11:56:00 +01006145 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006146 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07006147
Eric Laurent59255e42011-07-27 19:49:51 -07006148 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006149 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006150 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006151 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07006152 return INVALID_OPERATION;
6153 }
6154
Eric Laurent39e94f82010-07-28 01:32:47 -07006155 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07006156 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07006157 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07006158 // removed.
6159 srcThread->removeEffectChain_l(chain);
6160
6161 // transfer all effects one by one so that new effect chain is created on new thread with
6162 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006163 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07006164 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006165 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07006166 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6167 while (effect != 0) {
6168 srcThread->removeEffect_l(effect);
6169 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07006170 // removeEffect_l() has stopped the effect if it was active so it must be restarted
6171 if (effect->state() == EffectModule::ACTIVE ||
6172 effect->state() == EffectModule::STOPPING) {
6173 effect->start();
6174 }
Eric Laurent39e94f82010-07-28 01:32:47 -07006175 // if the move request is not received from audio policy manager, the effect must be
6176 // re-registered with the new strategy and output
6177 if (dstChain == 0) {
6178 dstChain = effect->chain().promote();
6179 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006180 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07006181 srcThread->addEffect_l(effect);
6182 return NO_INIT;
6183 }
6184 strategy = dstChain->strategy();
6185 }
6186 if (reRegister) {
6187 AudioSystem::unregisterEffect(effect->id());
6188 AudioSystem::registerEffect(&effect->desc(),
6189 dstOutput,
6190 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07006191 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07006192 effect->id());
6193 }
Eric Laurentde070132010-07-13 04:45:46 -07006194 effect = chain->getEffectFromId_l(0);
6195 }
6196
6197 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006198}
6199
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006200
Mathias Agopian65ab4712010-07-14 17:59:35 -07006201// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006202sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07006203 const sp<AudioFlinger::Client>& client,
6204 const sp<IEffectClient>& effectClient,
6205 int32_t priority,
6206 int sessionId,
6207 effect_descriptor_t *desc,
6208 int *enabled,
6209 status_t *status
6210 )
6211{
6212 sp<EffectModule> effect;
6213 sp<EffectHandle> handle;
6214 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006215 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07006216 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006217 bool effectCreated = false;
6218 bool effectRegistered = false;
6219
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006220 lStatus = initCheck();
6221 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006222 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006223 goto Exit;
6224 }
6225
6226 // Do not allow effects with session ID 0 on direct output or duplicating threads
6227 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07006228 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006229 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07006230 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006231 lStatus = BAD_VALUE;
6232 goto Exit;
6233 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006234 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08006235 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006236 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006237 desc->name, desc->flags, mType);
6238 lStatus = BAD_VALUE;
6239 goto Exit;
6240 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006241
Steve Block3856b092011-10-20 11:56:00 +01006242 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006243
6244 { // scope for mLock
6245 Mutex::Autolock _l(mLock);
6246
6247 // check for existing effect chain with the requested audio session
6248 chain = getEffectChain_l(sessionId);
6249 if (chain == 0) {
6250 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006251 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006252 chain = new EffectChain(this, sessionId);
6253 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07006254 chain->setStrategy(getStrategyForSession_l(sessionId));
6255 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006256 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07006257 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006258 }
6259
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08006260 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006261
6262 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006263 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006264 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07006265 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006266 if (lStatus != NO_ERROR) {
6267 goto Exit;
6268 }
6269 effectRegistered = true;
6270 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07006271 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006272 lStatus = effect->status();
6273 if (lStatus != NO_ERROR) {
6274 goto Exit;
6275 }
Eric Laurentcab11242010-07-15 12:50:15 -07006276 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006277 if (lStatus != NO_ERROR) {
6278 goto Exit;
6279 }
6280 effectCreated = true;
6281
6282 effect->setDevice(mDevice);
6283 effect->setMode(mAudioFlinger->getMode());
6284 }
6285 // create effect handle and connect it to effect module
6286 handle = new EffectHandle(effect, client, effectClient, priority);
6287 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08006288 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006289 *enabled = (int)effect->isEnabled();
6290 }
6291 }
6292
6293Exit:
6294 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07006295 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006296 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07006297 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006298 }
6299 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07006300 AudioSystem::unregisterEffect(effect->id());
6301 }
6302 if (chainCreated) {
6303 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006304 }
6305 handle.clear();
6306 }
6307
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006308 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006309 *status = lStatus;
6310 }
6311 return handle;
6312}
6313
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006314sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6315{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006316 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08006317 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006318}
6319
Eric Laurentde070132010-07-13 04:45:46 -07006320// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6321// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006322status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07006323{
6324 // check for existing effect chain with the requested audio session
6325 int sessionId = effect->sessionId();
6326 sp<EffectChain> chain = getEffectChain_l(sessionId);
6327 bool chainCreated = false;
6328
6329 if (chain == 0) {
6330 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006331 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006332 chain = new EffectChain(this, sessionId);
6333 addEffectChain_l(chain);
6334 chain->setStrategy(getStrategyForSession_l(sessionId));
6335 chainCreated = true;
6336 }
Steve Block3856b092011-10-20 11:56:00 +01006337 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006338
6339 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006340 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07006341 this, effect->desc().name, chain.get());
6342 return BAD_VALUE;
6343 }
6344
6345 status_t status = chain->addEffect_l(effect);
6346 if (status != NO_ERROR) {
6347 if (chainCreated) {
6348 removeEffectChain_l(chain);
6349 }
6350 return status;
6351 }
6352
6353 effect->setDevice(mDevice);
6354 effect->setMode(mAudioFlinger->getMode());
6355 return NO_ERROR;
6356}
6357
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006358void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07006359
Steve Block3856b092011-10-20 11:56:00 +01006360 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006361 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07006362 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6363 detachAuxEffect_l(effect->id());
6364 }
6365
6366 sp<EffectChain> chain = effect->chain().promote();
6367 if (chain != 0) {
6368 // remove effect chain if removing last effect
6369 if (chain->removeEffect_l(effect) == 0) {
6370 removeEffectChain_l(chain);
6371 }
6372 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00006373 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006374 }
6375}
6376
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006377void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006378 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006379{
6380 effectChains = mEffectChains;
6381 for (size_t i = 0; i < mEffectChains.size(); i++) {
6382 mEffectChains[i]->lock();
6383 }
6384}
6385
6386void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006387 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006388{
6389 for (size_t i = 0; i < effectChains.size(); i++) {
6390 effectChains[i]->unlock();
6391 }
6392}
6393
6394sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6395{
6396 Mutex::Autolock _l(mLock);
6397 return getEffectChain_l(sessionId);
6398}
6399
6400sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6401{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006402 size_t size = mEffectChains.size();
6403 for (size_t i = 0; i < size; i++) {
6404 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08006405 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006406 }
6407 }
Glenn Kasten090f0192012-01-30 13:00:02 -08006408 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006409}
6410
Glenn Kastenf78aee72012-01-04 11:00:47 -08006411void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006412{
6413 Mutex::Autolock _l(mLock);
6414 size_t size = mEffectChains.size();
6415 for (size_t i = 0; i < size; i++) {
6416 mEffectChains[i]->setMode_l(mode);
6417 }
6418}
6419
6420void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006421 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08006422 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07006423
Mathias Agopian65ab4712010-07-14 17:59:35 -07006424 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006425 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006426 // delete the effect module if removing last handle on it
6427 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006428 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006429 removeEffect_l(effect);
6430 AudioSystem::unregisterEffect(effect->id());
6431 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006432 }
6433}
6434
6435status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6436{
6437 int session = chain->sessionId();
6438 int16_t *buffer = mMixBuffer;
6439 bool ownsBuffer = false;
6440
Steve Block3856b092011-10-20 11:56:00 +01006441 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006442 if (session > 0) {
6443 // Only one effect chain can be present in direct output thread and it uses
6444 // the mix buffer as input
6445 if (mType != DIRECT) {
6446 size_t numSamples = mFrameCount * mChannelCount;
6447 buffer = new int16_t[numSamples];
6448 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01006449 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006450 ownsBuffer = true;
6451 }
6452
6453 // Attach all tracks with same session ID to this chain.
6454 for (size_t i = 0; i < mTracks.size(); ++i) {
6455 sp<Track> track = mTracks[i];
6456 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006457 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006458 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006459 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006460 }
6461 }
6462
6463 // indicate all active tracks in the chain
6464 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6465 sp<Track> track = mActiveTracks[i].promote();
6466 if (track == 0) continue;
6467 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006468 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07006469 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006470 }
6471 }
6472 }
6473
6474 chain->setInBuffer(buffer, ownsBuffer);
6475 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006476 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006477 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006478 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6479 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006480 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006481 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6482 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006483 // Effect chain for other sessions are inserted at beginning of effect
6484 // chains list to be processed before output mix effects. Relative order between other
6485 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006486 size_t size = mEffectChains.size();
6487 size_t i = 0;
6488 for (i = 0; i < size; i++) {
6489 if (mEffectChains[i]->sessionId() < session) break;
6490 }
6491 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006492 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006493
6494 return NO_ERROR;
6495}
6496
6497size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6498{
6499 int session = chain->sessionId();
6500
Steve Block3856b092011-10-20 11:56:00 +01006501 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006502
6503 for (size_t i = 0; i < mEffectChains.size(); i++) {
6504 if (chain == mEffectChains[i]) {
6505 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006506 // detach all active tracks from the chain
6507 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6508 sp<Track> track = mActiveTracks[i].promote();
6509 if (track == 0) continue;
6510 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006511 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006512 chain.get(), session);
6513 chain->decActiveTrackCnt();
6514 }
6515 }
6516
Mathias Agopian65ab4712010-07-14 17:59:35 -07006517 // detach all tracks with same session ID from this chain
6518 for (size_t i = 0; i < mTracks.size(); ++i) {
6519 sp<Track> track = mTracks[i];
6520 if (session == track->sessionId()) {
6521 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006522 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006523 }
6524 }
Eric Laurentde070132010-07-13 04:45:46 -07006525 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006526 }
6527 }
6528 return mEffectChains.size();
6529}
6530
Eric Laurentde070132010-07-13 04:45:46 -07006531status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6532 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006533{
6534 Mutex::Autolock _l(mLock);
6535 return attachAuxEffect_l(track, EffectId);
6536}
6537
Eric Laurentde070132010-07-13 04:45:46 -07006538status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6539 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006540{
6541 status_t status = NO_ERROR;
6542
6543 if (EffectId == 0) {
6544 track->setAuxBuffer(0, NULL);
6545 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006546 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6547 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006548 if (effect != 0) {
6549 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6550 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6551 } else {
6552 status = INVALID_OPERATION;
6553 }
6554 } else {
6555 status = BAD_VALUE;
6556 }
6557 }
6558 return status;
6559}
6560
6561void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6562{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006563 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006564 sp<Track> track = mTracks[i];
6565 if (track->auxEffectId() == effectId) {
6566 attachAuxEffect_l(track, 0);
6567 }
6568 }
6569}
6570
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006571status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6572{
6573 // only one chain per input thread
6574 if (mEffectChains.size() != 0) {
6575 return INVALID_OPERATION;
6576 }
Steve Block3856b092011-10-20 11:56:00 +01006577 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006578
6579 chain->setInBuffer(NULL);
6580 chain->setOutBuffer(NULL);
6581
Eric Laurent59255e42011-07-27 19:49:51 -07006582 checkSuspendOnAddEffectChain_l(chain);
6583
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006584 mEffectChains.add(chain);
6585
6586 return NO_ERROR;
6587}
6588
6589size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6590{
Steve Block3856b092011-10-20 11:56:00 +01006591 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006592 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006593 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6594 chain.get(), mEffectChains.size(), this);
6595 if (mEffectChains.size() == 1) {
6596 mEffectChains.removeAt(0);
6597 }
6598 return 0;
6599}
6600
Mathias Agopian65ab4712010-07-14 17:59:35 -07006601// ----------------------------------------------------------------------------
6602// EffectModule implementation
6603// ----------------------------------------------------------------------------
6604
6605#undef LOG_TAG
6606#define LOG_TAG "AudioFlinger::EffectModule"
6607
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006608AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006609 const wp<AudioFlinger::EffectChain>& chain,
6610 effect_descriptor_t *desc,
6611 int id,
6612 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006613 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006614 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006615{
Steve Block3856b092011-10-20 11:56:00 +01006616 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006617 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006618 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006619 return;
6620 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006621
6622 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6623
6624 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006625 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006626
6627 if (mStatus != NO_ERROR) {
6628 return;
6629 }
6630 lStatus = init();
6631 if (lStatus < 0) {
6632 mStatus = lStatus;
6633 goto Error;
6634 }
6635
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006636 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6637 mPinned = true;
6638 }
Steve Block3856b092011-10-20 11:56:00 +01006639 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006640 return;
6641Error:
6642 EffectRelease(mEffectInterface);
6643 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006644 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006645}
6646
6647AudioFlinger::EffectModule::~EffectModule()
6648{
Steve Block3856b092011-10-20 11:56:00 +01006649 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006650 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006651 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6652 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6653 sp<ThreadBase> thread = mThread.promote();
6654 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006655 audio_stream_t *stream = thread->stream();
6656 if (stream != NULL) {
6657 stream->remove_audio_effect(stream, mEffectInterface);
6658 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006659 }
6660 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006661 // release effect engine
6662 EffectRelease(mEffectInterface);
6663 }
6664}
6665
Glenn Kasten435dbe62012-01-30 10:15:48 -08006666status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006667{
6668 status_t status;
6669
6670 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006671 int priority = handle->priority();
6672 size_t size = mHandles.size();
6673 sp<EffectHandle> h;
6674 size_t i;
6675 for (i = 0; i < size; i++) {
6676 h = mHandles[i].promote();
6677 if (h == 0) continue;
6678 if (h->priority() <= priority) break;
6679 }
6680 // if inserted in first place, move effect control from previous owner to this handle
6681 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006682 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006683 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006684 enabled = h->enabled();
6685 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006686 }
Eric Laurent59255e42011-07-27 19:49:51 -07006687 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006688 status = NO_ERROR;
6689 } else {
6690 status = ALREADY_EXISTS;
6691 }
Steve Block3856b092011-10-20 11:56:00 +01006692 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006693 mHandles.insertAt(handle, i);
6694 return status;
6695}
6696
6697size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6698{
6699 Mutex::Autolock _l(mLock);
6700 size_t size = mHandles.size();
6701 size_t i;
6702 for (i = 0; i < size; i++) {
6703 if (mHandles[i] == handle) break;
6704 }
6705 if (i == size) {
6706 return size;
6707 }
Steve Block3856b092011-10-20 11:56:00 +01006708 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006709
6710 bool enabled = false;
6711 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006712 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006713 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006714 enabled = hdl->enabled();
6715 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006716 mHandles.removeAt(i);
6717 size = mHandles.size();
6718 // if removed from first place, move effect control from this handle to next in line
6719 if (i == 0 && size != 0) {
6720 sp<EffectHandle> h = mHandles[0].promote();
6721 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006722 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006723 }
6724 }
6725
Eric Laurentec437d82011-07-26 20:54:46 -07006726 // Prevent calls to process() and other functions on effect interface from now on.
6727 // The effect engine will be released by the destructor when the last strong reference on
6728 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006729 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006730 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006731 }
6732
Mathias Agopian65ab4712010-07-14 17:59:35 -07006733 return size;
6734}
6735
Eric Laurent59255e42011-07-27 19:49:51 -07006736sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6737{
6738 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08006739 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07006740}
6741
Glenn Kasten58123c32012-02-03 10:32:24 -08006742void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006743{
Glenn Kasten90bebef2012-01-27 15:24:38 -08006744 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006745 // keep a strong reference on this EffectModule to avoid calling the
6746 // destructor before we exit
6747 sp<EffectModule> keep(this);
6748 {
6749 sp<ThreadBase> thread = mThread.promote();
6750 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006751 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006752 }
6753 }
6754}
6755
6756void AudioFlinger::EffectModule::updateState() {
6757 Mutex::Autolock _l(mLock);
6758
6759 switch (mState) {
6760 case RESTART:
6761 reset_l();
6762 // FALL THROUGH
6763
6764 case STARTING:
6765 // clear auxiliary effect input buffer for next accumulation
6766 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6767 memset(mConfig.inputCfg.buffer.raw,
6768 0,
6769 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6770 }
6771 start_l();
6772 mState = ACTIVE;
6773 break;
6774 case STOPPING:
6775 stop_l();
6776 mDisableWaitCnt = mMaxDisableWaitCnt;
6777 mState = STOPPED;
6778 break;
6779 case STOPPED:
6780 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6781 // turn off sequence.
6782 if (--mDisableWaitCnt == 0) {
6783 reset_l();
6784 mState = IDLE;
6785 }
6786 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006787 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006788 break;
6789 }
6790}
6791
6792void AudioFlinger::EffectModule::process()
6793{
6794 Mutex::Autolock _l(mLock);
6795
Eric Laurentec437d82011-07-26 20:54:46 -07006796 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006797 mConfig.inputCfg.buffer.raw == NULL ||
6798 mConfig.outputCfg.buffer.raw == NULL) {
6799 return;
6800 }
6801
Eric Laurent8f45bd72010-08-31 13:50:07 -07006802 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006803 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6804 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006805 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006806 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006807 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006808 }
6809
6810 // do the actual processing in the effect engine
6811 int ret = (*mEffectInterface)->process(mEffectInterface,
6812 &mConfig.inputCfg.buffer,
6813 &mConfig.outputCfg.buffer);
6814
6815 // force transition to IDLE state when engine is ready
6816 if (mState == STOPPED && ret == -ENODATA) {
6817 mDisableWaitCnt = 1;
6818 }
6819
6820 // clear auxiliary effect input buffer for next accumulation
6821 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006822 memset(mConfig.inputCfg.buffer.raw, 0,
6823 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006824 }
6825 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006826 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6827 // If an insert effect is idle and input buffer is different from output buffer,
6828 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006829 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006830 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006831 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6832 int16_t *in = mConfig.inputCfg.buffer.s16;
6833 int16_t *out = mConfig.outputCfg.buffer.s16;
6834 for (size_t i = 0; i < frameCnt; i++) {
6835 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006836 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006837 }
6838 }
6839}
6840
6841void AudioFlinger::EffectModule::reset_l()
6842{
6843 if (mEffectInterface == NULL) {
6844 return;
6845 }
6846 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6847}
6848
6849status_t AudioFlinger::EffectModule::configure()
6850{
6851 uint32_t channels;
6852 if (mEffectInterface == NULL) {
6853 return NO_INIT;
6854 }
6855
6856 sp<ThreadBase> thread = mThread.promote();
6857 if (thread == 0) {
6858 return DEAD_OBJECT;
6859 }
6860
6861 // TODO: handle configuration of effects replacing track process
6862 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006863 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006864 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006865 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006866 }
6867
6868 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006869 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006870 } else {
6871 mConfig.inputCfg.channels = channels;
6872 }
6873 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006874 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6875 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006876 mConfig.inputCfg.samplingRate = thread->sampleRate();
6877 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6878 mConfig.inputCfg.bufferProvider.cookie = NULL;
6879 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6880 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6881 mConfig.outputCfg.bufferProvider.cookie = NULL;
6882 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6883 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6884 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6885 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006886 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006887 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006888 // - in other sessions:
6889 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6890 // other effect: overwrites output buffer: input buffer == output buffer
6891 // Auxiliary effect:
6892 // accumulates in output buffer: input buffer != output buffer
6893 // Therefore: accumulate <=> input buffer != output buffer
6894 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6895 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6896 } else {
6897 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6898 }
6899 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6900 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6901 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6902 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6903
Steve Block3856b092011-10-20 11:56:00 +01006904 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006905 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6906
Mathias Agopian65ab4712010-07-14 17:59:35 -07006907 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006908 uint32_t size = sizeof(int);
6909 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006910 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006911 sizeof(effect_config_t),
6912 &mConfig,
6913 &size,
6914 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006915 if (status == 0) {
6916 status = cmdStatus;
6917 }
6918
6919 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6920 (1000 * mConfig.outputCfg.buffer.frameCount);
6921
6922 return status;
6923}
6924
6925status_t AudioFlinger::EffectModule::init()
6926{
6927 Mutex::Autolock _l(mLock);
6928 if (mEffectInterface == NULL) {
6929 return NO_INIT;
6930 }
6931 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006932 uint32_t size = sizeof(status_t);
6933 status_t status = (*mEffectInterface)->command(mEffectInterface,
6934 EFFECT_CMD_INIT,
6935 0,
6936 NULL,
6937 &size,
6938 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006939 if (status == 0) {
6940 status = cmdStatus;
6941 }
6942 return status;
6943}
6944
Eric Laurentec35a142011-10-05 17:42:25 -07006945status_t AudioFlinger::EffectModule::start()
6946{
6947 Mutex::Autolock _l(mLock);
6948 return start_l();
6949}
6950
Mathias Agopian65ab4712010-07-14 17:59:35 -07006951status_t AudioFlinger::EffectModule::start_l()
6952{
6953 if (mEffectInterface == NULL) {
6954 return NO_INIT;
6955 }
6956 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006957 uint32_t size = sizeof(status_t);
6958 status_t status = (*mEffectInterface)->command(mEffectInterface,
6959 EFFECT_CMD_ENABLE,
6960 0,
6961 NULL,
6962 &size,
6963 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006964 if (status == 0) {
6965 status = cmdStatus;
6966 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006967 if (status == 0 &&
6968 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6969 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6970 sp<ThreadBase> thread = mThread.promote();
6971 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006972 audio_stream_t *stream = thread->stream();
6973 if (stream != NULL) {
6974 stream->add_audio_effect(stream, mEffectInterface);
6975 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006976 }
6977 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006978 return status;
6979}
6980
Eric Laurentec437d82011-07-26 20:54:46 -07006981status_t AudioFlinger::EffectModule::stop()
6982{
6983 Mutex::Autolock _l(mLock);
6984 return stop_l();
6985}
6986
Mathias Agopian65ab4712010-07-14 17:59:35 -07006987status_t AudioFlinger::EffectModule::stop_l()
6988{
6989 if (mEffectInterface == NULL) {
6990 return NO_INIT;
6991 }
6992 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006993 uint32_t size = sizeof(status_t);
6994 status_t status = (*mEffectInterface)->command(mEffectInterface,
6995 EFFECT_CMD_DISABLE,
6996 0,
6997 NULL,
6998 &size,
6999 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007000 if (status == 0) {
7001 status = cmdStatus;
7002 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007003 if (status == 0 &&
7004 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7005 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7006 sp<ThreadBase> thread = mThread.promote();
7007 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007008 audio_stream_t *stream = thread->stream();
7009 if (stream != NULL) {
7010 stream->remove_audio_effect(stream, mEffectInterface);
7011 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007012 }
7013 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007014 return status;
7015}
7016
Eric Laurent25f43952010-07-28 05:40:18 -07007017status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
7018 uint32_t cmdSize,
7019 void *pCmdData,
7020 uint32_t *replySize,
7021 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007022{
7023 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007024// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007025
Eric Laurentec437d82011-07-26 20:54:46 -07007026 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007027 return NO_INIT;
7028 }
Eric Laurent25f43952010-07-28 05:40:18 -07007029 status_t status = (*mEffectInterface)->command(mEffectInterface,
7030 cmdCode,
7031 cmdSize,
7032 pCmdData,
7033 replySize,
7034 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007035 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07007036 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007037 for (size_t i = 1; i < mHandles.size(); i++) {
7038 sp<EffectHandle> h = mHandles[i].promote();
7039 if (h != 0) {
7040 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
7041 }
7042 }
7043 }
7044 return status;
7045}
7046
7047status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
7048{
Eric Laurentdb7c0792011-08-10 10:37:50 -07007049
Mathias Agopian65ab4712010-07-14 17:59:35 -07007050 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007051 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007052
7053 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007054 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
7055 if (enabled && status != NO_ERROR) {
7056 return status;
7057 }
7058
Mathias Agopian65ab4712010-07-14 17:59:35 -07007059 switch (mState) {
7060 // going from disabled to enabled
7061 case IDLE:
7062 mState = STARTING;
7063 break;
7064 case STOPPED:
7065 mState = RESTART;
7066 break;
7067 case STOPPING:
7068 mState = ACTIVE;
7069 break;
7070
7071 // going from enabled to disabled
7072 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007073 mState = STOPPED;
7074 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007075 case STARTING:
7076 mState = IDLE;
7077 break;
7078 case ACTIVE:
7079 mState = STOPPING;
7080 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007081 case DESTROYED:
7082 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007083 }
7084 for (size_t i = 1; i < mHandles.size(); i++) {
7085 sp<EffectHandle> h = mHandles[i].promote();
7086 if (h != 0) {
7087 h->setEnabled(enabled);
7088 }
7089 }
7090 }
7091 return NO_ERROR;
7092}
7093
Glenn Kastenc59c0042012-02-02 14:06:11 -08007094bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007095{
7096 switch (mState) {
7097 case RESTART:
7098 case STARTING:
7099 case ACTIVE:
7100 return true;
7101 case IDLE:
7102 case STOPPING:
7103 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07007104 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07007105 default:
7106 return false;
7107 }
7108}
7109
Glenn Kastenc59c0042012-02-02 14:06:11 -08007110bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07007111{
7112 switch (mState) {
7113 case RESTART:
7114 case ACTIVE:
7115 case STOPPING:
7116 case STOPPED:
7117 return true;
7118 case IDLE:
7119 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07007120 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007121 default:
7122 return false;
7123 }
7124}
7125
Mathias Agopian65ab4712010-07-14 17:59:35 -07007126status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7127{
7128 Mutex::Autolock _l(mLock);
7129 status_t status = NO_ERROR;
7130
7131 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7132 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07007133 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07007134 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7135 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007136 status_t cmdStatus;
7137 uint32_t volume[2];
7138 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07007139 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007140 volume[0] = *left;
7141 volume[1] = *right;
7142 if (controller) {
7143 pVolume = volume;
7144 }
Eric Laurent25f43952010-07-28 05:40:18 -07007145 status = (*mEffectInterface)->command(mEffectInterface,
7146 EFFECT_CMD_SET_VOLUME,
7147 size,
7148 volume,
7149 &size,
7150 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007151 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7152 *left = volume[0];
7153 *right = volume[1];
7154 }
7155 }
7156 return status;
7157}
7158
7159status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7160{
7161 Mutex::Autolock _l(mLock);
7162 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007163 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7164 // audio pre processing modules on RecordThread can receive both output and
7165 // input device indication in the same call
7166 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7167 if (dev) {
7168 status_t cmdStatus;
7169 uint32_t size = sizeof(status_t);
7170
7171 status = (*mEffectInterface)->command(mEffectInterface,
7172 EFFECT_CMD_SET_DEVICE,
7173 sizeof(uint32_t),
7174 &dev,
7175 &size,
7176 &cmdStatus);
7177 if (status == NO_ERROR) {
7178 status = cmdStatus;
7179 }
7180 }
7181 dev = device & AUDIO_DEVICE_IN_ALL;
7182 if (dev) {
7183 status_t cmdStatus;
7184 uint32_t size = sizeof(status_t);
7185
7186 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7187 EFFECT_CMD_SET_INPUT_DEVICE,
7188 sizeof(uint32_t),
7189 &dev,
7190 &size,
7191 &cmdStatus);
7192 if (status2 == NO_ERROR) {
7193 status2 = cmdStatus;
7194 }
7195 if (status == NO_ERROR) {
7196 status = status2;
7197 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007198 }
7199 }
7200 return status;
7201}
7202
Glenn Kastenf78aee72012-01-04 11:00:47 -08007203status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007204{
7205 Mutex::Autolock _l(mLock);
7206 status_t status = NO_ERROR;
7207 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007208 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007209 uint32_t size = sizeof(status_t);
7210 status = (*mEffectInterface)->command(mEffectInterface,
7211 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08007212 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07007213 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07007214 &size,
7215 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007216 if (status == NO_ERROR) {
7217 status = cmdStatus;
7218 }
7219 }
7220 return status;
7221}
7222
Eric Laurent59255e42011-07-27 19:49:51 -07007223void AudioFlinger::EffectModule::setSuspended(bool suspended)
7224{
7225 Mutex::Autolock _l(mLock);
7226 mSuspended = suspended;
7227}
Glenn Kastena3a85482012-01-04 11:01:11 -08007228
7229bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07007230{
7231 Mutex::Autolock _l(mLock);
7232 return mSuspended;
7233}
7234
Mathias Agopian65ab4712010-07-14 17:59:35 -07007235status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7236{
7237 const size_t SIZE = 256;
7238 char buffer[SIZE];
7239 String8 result;
7240
7241 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7242 result.append(buffer);
7243
7244 bool locked = tryLock(mLock);
7245 // failed to lock - AudioFlinger is probably deadlocked
7246 if (!locked) {
7247 result.append("\t\tCould not lock Fx mutex:\n");
7248 }
7249
7250 result.append("\t\tSession Status State Engine:\n");
7251 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7252 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7253 result.append(buffer);
7254
7255 result.append("\t\tDescriptor:\n");
7256 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7257 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7258 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7259 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7260 result.append(buffer);
7261 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7262 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7263 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7264 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7265 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07007266 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007267 mDescriptor.apiVersion,
7268 mDescriptor.flags);
7269 result.append(buffer);
7270 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7271 mDescriptor.name);
7272 result.append(buffer);
7273 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7274 mDescriptor.implementor);
7275 result.append(buffer);
7276
7277 result.append("\t\t- Input configuration:\n");
7278 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7279 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7280 (uint32_t)mConfig.inputCfg.buffer.raw,
7281 mConfig.inputCfg.buffer.frameCount,
7282 mConfig.inputCfg.samplingRate,
7283 mConfig.inputCfg.channels,
7284 mConfig.inputCfg.format);
7285 result.append(buffer);
7286
7287 result.append("\t\t- Output configuration:\n");
7288 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7289 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7290 (uint32_t)mConfig.outputCfg.buffer.raw,
7291 mConfig.outputCfg.buffer.frameCount,
7292 mConfig.outputCfg.samplingRate,
7293 mConfig.outputCfg.channels,
7294 mConfig.outputCfg.format);
7295 result.append(buffer);
7296
7297 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7298 result.append(buffer);
7299 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7300 for (size_t i = 0; i < mHandles.size(); ++i) {
7301 sp<EffectHandle> handle = mHandles[i].promote();
7302 if (handle != 0) {
7303 handle->dump(buffer, SIZE);
7304 result.append(buffer);
7305 }
7306 }
7307
7308 result.append("\n");
7309
7310 write(fd, result.string(), result.length());
7311
7312 if (locked) {
7313 mLock.unlock();
7314 }
7315
7316 return NO_ERROR;
7317}
7318
7319// ----------------------------------------------------------------------------
7320// EffectHandle implementation
7321// ----------------------------------------------------------------------------
7322
7323#undef LOG_TAG
7324#define LOG_TAG "AudioFlinger::EffectHandle"
7325
7326AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7327 const sp<AudioFlinger::Client>& client,
7328 const sp<IEffectClient>& effectClient,
7329 int32_t priority)
7330 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007331 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007332 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007333{
Steve Block3856b092011-10-20 11:56:00 +01007334 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007335
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007336 if (client == 0) {
7337 return;
7338 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007339 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7340 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7341 if (mCblkMemory != 0) {
7342 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7343
Glenn Kastena0d68332012-01-27 16:47:15 -08007344 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007345 new(mCblk) effect_param_cblk_t();
7346 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007347 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007348 } else {
Steve Block29357bc2012-01-06 19:20:56 +00007349 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007350 return;
7351 }
7352}
7353
7354AudioFlinger::EffectHandle::~EffectHandle()
7355{
Steve Block3856b092011-10-20 11:56:00 +01007356 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007357 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01007358 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007359}
7360
7361status_t AudioFlinger::EffectHandle::enable()
7362{
Steve Block3856b092011-10-20 11:56:00 +01007363 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007364 if (!mHasControl) return INVALID_OPERATION;
7365 if (mEffect == 0) return DEAD_OBJECT;
7366
Eric Laurentdb7c0792011-08-10 10:37:50 -07007367 if (mEnabled) {
7368 return NO_ERROR;
7369 }
7370
Eric Laurent59255e42011-07-27 19:49:51 -07007371 mEnabled = true;
7372
7373 sp<ThreadBase> thread = mEffect->thread().promote();
7374 if (thread != 0) {
7375 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7376 }
7377
7378 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7379 if (mEffect->suspended()) {
7380 return NO_ERROR;
7381 }
7382
Eric Laurentdb7c0792011-08-10 10:37:50 -07007383 status_t status = mEffect->setEnabled(true);
7384 if (status != NO_ERROR) {
7385 if (thread != 0) {
7386 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7387 }
7388 mEnabled = false;
7389 }
7390 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007391}
7392
7393status_t AudioFlinger::EffectHandle::disable()
7394{
Steve Block3856b092011-10-20 11:56:00 +01007395 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007396 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07007397 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007398
Eric Laurentdb7c0792011-08-10 10:37:50 -07007399 if (!mEnabled) {
7400 return NO_ERROR;
7401 }
Eric Laurent59255e42011-07-27 19:49:51 -07007402 mEnabled = false;
7403
7404 if (mEffect->suspended()) {
7405 return NO_ERROR;
7406 }
7407
7408 status_t status = mEffect->setEnabled(false);
7409
7410 sp<ThreadBase> thread = mEffect->thread().promote();
7411 if (thread != 0) {
7412 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7413 }
7414
7415 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007416}
7417
7418void AudioFlinger::EffectHandle::disconnect()
7419{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007420 disconnect(true);
7421}
7422
Glenn Kasten58123c32012-02-03 10:32:24 -08007423void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007424{
Glenn Kasten58123c32012-02-03 10:32:24 -08007425 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007426 if (mEffect == 0) {
7427 return;
7428 }
Glenn Kasten58123c32012-02-03 10:32:24 -08007429 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07007430
Eric Laurenta85a74a2011-10-19 11:44:54 -07007431 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007432 sp<ThreadBase> thread = mEffect->thread().promote();
7433 if (thread != 0) {
7434 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7435 }
Eric Laurent59255e42011-07-27 19:49:51 -07007436 }
7437
Mathias Agopian65ab4712010-07-14 17:59:35 -07007438 // release sp on module => module destructor can be called now
7439 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007440 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08007441 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08007442 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007443 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7444 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08007445 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007446 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07007447 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7448 mClient.clear();
7449 }
7450}
7451
Eric Laurent25f43952010-07-28 05:40:18 -07007452status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7453 uint32_t cmdSize,
7454 void *pCmdData,
7455 uint32_t *replySize,
7456 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007457{
Steve Block3856b092011-10-20 11:56:00 +01007458// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07007459// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007460
7461 // only get parameter command is permitted for applications not controlling the effect
7462 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7463 return INVALID_OPERATION;
7464 }
7465 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007466 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007467
7468 // handle commands that are not forwarded transparently to effect engine
7469 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7470 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7471 // no risk to block the whole media server process or mixer threads is we are stuck here
7472 Mutex::Autolock _l(mCblk->lock);
7473 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7474 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7475 mCblk->serverIndex = 0;
7476 mCblk->clientIndex = 0;
7477 return BAD_VALUE;
7478 }
7479 status_t status = NO_ERROR;
7480 while (mCblk->serverIndex < mCblk->clientIndex) {
7481 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007482 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007483 int *p = (int *)(mBuffer + mCblk->serverIndex);
7484 int size = *p++;
7485 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007486 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007487 break;
7488 }
7489 effect_param_t *param = (effect_param_t *)p;
7490 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007491 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007492 mCblk->serverIndex += size;
7493 continue;
7494 }
Eric Laurent25f43952010-07-28 05:40:18 -07007495 uint32_t psize = sizeof(effect_param_t) +
7496 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7497 param->vsize;
7498 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7499 psize,
7500 p,
7501 &rsize,
7502 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007503 // stop at first error encountered
7504 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007505 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007506 *(int *)pReplyData = reply;
7507 break;
7508 } else if (reply != NO_ERROR) {
7509 *(int *)pReplyData = reply;
7510 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007511 }
7512 mCblk->serverIndex += size;
7513 }
7514 mCblk->serverIndex = 0;
7515 mCblk->clientIndex = 0;
7516 return status;
7517 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007518 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007519 return enable();
7520 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007521 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007522 return disable();
7523 }
7524
7525 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7526}
7527
Eric Laurent59255e42011-07-27 19:49:51 -07007528void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007529{
Steve Block3856b092011-10-20 11:56:00 +01007530 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007531
7532 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007533 mEnabled = enabled;
7534
Mathias Agopian65ab4712010-07-14 17:59:35 -07007535 if (signal && mEffectClient != 0) {
7536 mEffectClient->controlStatusChanged(hasControl);
7537 }
7538}
7539
Eric Laurent25f43952010-07-28 05:40:18 -07007540void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7541 uint32_t cmdSize,
7542 void *pCmdData,
7543 uint32_t replySize,
7544 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007545{
7546 if (mEffectClient != 0) {
7547 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7548 }
7549}
7550
7551
7552
7553void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7554{
7555 if (mEffectClient != 0) {
7556 mEffectClient->enableStatusChanged(enabled);
7557 }
7558}
7559
7560status_t AudioFlinger::EffectHandle::onTransact(
7561 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7562{
7563 return BnEffect::onTransact(code, data, reply, flags);
7564}
7565
7566
7567void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7568{
Glenn Kastena0d68332012-01-27 16:47:15 -08007569 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007570
7571 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08007572 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007573 mPriority,
7574 mHasControl,
7575 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007576 mCblk ? mCblk->clientIndex : 0,
7577 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007578 );
7579
7580 if (locked) {
7581 mCblk->lock.unlock();
7582 }
7583}
7584
7585#undef LOG_TAG
7586#define LOG_TAG "AudioFlinger::EffectChain"
7587
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007588AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007589 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007590 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007591 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7592 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007593{
Dima Zavinfce7a472011-04-19 22:30:36 -07007594 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007595 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007596 return;
7597 }
7598 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7599 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007600}
7601
7602AudioFlinger::EffectChain::~EffectChain()
7603{
7604 if (mOwnInBuffer) {
7605 delete mInBuffer;
7606 }
7607
7608}
7609
Eric Laurent59255e42011-07-27 19:49:51 -07007610// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007611sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007612{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007613 size_t size = mEffects.size();
7614
7615 for (size_t i = 0; i < size; i++) {
7616 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007617 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007618 }
7619 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007620 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007621}
7622
Eric Laurent59255e42011-07-27 19:49:51 -07007623// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007624sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007625{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007626 size_t size = mEffects.size();
7627
7628 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007629 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7630 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007631 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007632 }
7633 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007634 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007635}
7636
Eric Laurent59255e42011-07-27 19:49:51 -07007637// getEffectFromType_l() must be called with ThreadBase::mLock held
7638sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7639 const effect_uuid_t *type)
7640{
Eric Laurent59255e42011-07-27 19:49:51 -07007641 size_t size = mEffects.size();
7642
7643 for (size_t i = 0; i < size; i++) {
7644 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007645 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007646 }
7647 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007648 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007649}
7650
Mathias Agopian65ab4712010-07-14 17:59:35 -07007651// Must be called with EffectChain::mLock locked
7652void AudioFlinger::EffectChain::process_l()
7653{
Eric Laurentdac69112010-09-28 14:09:57 -07007654 sp<ThreadBase> thread = mThread.promote();
7655 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007656 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007657 return;
7658 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007659 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7660 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007661 // always process effects unless no more tracks are on the session and the effect tail
7662 // has been rendered
7663 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007664 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007665 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007666
Eric Laurent544fe9b2011-11-11 15:42:52 -08007667 if (!tracksOnSession && mTailBufferCount == 0) {
7668 doProcess = false;
7669 }
7670
7671 if (activeTrackCnt() == 0) {
7672 // if no track is active and the effect tail has not been rendered,
7673 // the input buffer must be cleared here as the mixer process will not do it
7674 if (tracksOnSession || mTailBufferCount > 0) {
7675 size_t numSamples = thread->frameCount() * thread->channelCount();
7676 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7677 if (mTailBufferCount > 0) {
7678 mTailBufferCount--;
7679 }
7680 }
7681 }
Eric Laurentdac69112010-09-28 14:09:57 -07007682 }
7683
Mathias Agopian65ab4712010-07-14 17:59:35 -07007684 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007685 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007686 for (size_t i = 0; i < size; i++) {
7687 mEffects[i]->process();
7688 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007689 }
7690 for (size_t i = 0; i < size; i++) {
7691 mEffects[i]->updateState();
7692 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007693}
7694
Eric Laurentcab11242010-07-15 12:50:15 -07007695// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007696status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007697{
7698 effect_descriptor_t desc = effect->desc();
7699 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7700
7701 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007702 effect->setChain(this);
7703 sp<ThreadBase> thread = mThread.promote();
7704 if (thread == 0) {
7705 return NO_INIT;
7706 }
7707 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007708
7709 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7710 // Auxiliary effects are inserted at the beginning of mEffects vector as
7711 // they are processed first and accumulated in chain input buffer
7712 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007713
Mathias Agopian65ab4712010-07-14 17:59:35 -07007714 // the input buffer for auxiliary effect contains mono samples in
7715 // 32 bit format. This is to avoid saturation in AudoMixer
7716 // accumulation stage. Saturation is done in EffectModule::process() before
7717 // calling the process in effect engine
7718 size_t numSamples = thread->frameCount();
7719 int32_t *buffer = new int32_t[numSamples];
7720 memset(buffer, 0, numSamples * sizeof(int32_t));
7721 effect->setInBuffer((int16_t *)buffer);
7722 // auxiliary effects output samples to chain input buffer for further processing
7723 // by insert effects
7724 effect->setOutBuffer(mInBuffer);
7725 } else {
7726 // Insert effects are inserted at the end of mEffects vector as they are processed
7727 // after track and auxiliary effects.
7728 // Insert effect order as a function of indicated preference:
7729 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7730 // another effect is present
7731 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7732 // last effect claiming first position
7733 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7734 // first effect claiming last position
7735 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7736 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7737 // already present
7738
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007739 size_t size = mEffects.size();
7740 size_t idx_insert = size;
7741 ssize_t idx_insert_first = -1;
7742 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007743
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007744 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007745 effect_descriptor_t d = mEffects[i]->desc();
7746 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7747 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7748 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7749 // check invalid effect chaining combinations
7750 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7751 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007752 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007753 return INVALID_OPERATION;
7754 }
7755 // remember position of first insert effect and by default
7756 // select this as insert position for new effect
7757 if (idx_insert == size) {
7758 idx_insert = i;
7759 }
7760 // remember position of last insert effect claiming
7761 // first position
7762 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7763 idx_insert_first = i;
7764 }
7765 // remember position of first insert effect claiming
7766 // last position
7767 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7768 idx_insert_last == -1) {
7769 idx_insert_last = i;
7770 }
7771 }
7772 }
7773
7774 // modify idx_insert from first position if needed
7775 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7776 if (idx_insert_last != -1) {
7777 idx_insert = idx_insert_last;
7778 } else {
7779 idx_insert = size;
7780 }
7781 } else {
7782 if (idx_insert_first != -1) {
7783 idx_insert = idx_insert_first + 1;
7784 }
7785 }
7786
7787 // always read samples from chain input buffer
7788 effect->setInBuffer(mInBuffer);
7789
7790 // if last effect in the chain, output samples to chain
7791 // output buffer, otherwise to chain input buffer
7792 if (idx_insert == size) {
7793 if (idx_insert != 0) {
7794 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7795 mEffects[idx_insert-1]->configure();
7796 }
7797 effect->setOutBuffer(mOutBuffer);
7798 } else {
7799 effect->setOutBuffer(mInBuffer);
7800 }
7801 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007802
Steve Block3856b092011-10-20 11:56:00 +01007803 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007804 }
7805 effect->configure();
7806 return NO_ERROR;
7807}
7808
Eric Laurentcab11242010-07-15 12:50:15 -07007809// removeEffect_l() must be called with PlaybackThread::mLock held
7810size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007811{
7812 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007813 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007814 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7815
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007816 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007817 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007818 // calling stop here will remove pre-processing effect from the audio HAL.
7819 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7820 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007821 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7822 mEffects[i]->state() == EffectModule::STOPPING) {
7823 mEffects[i]->stop();
7824 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007825 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7826 delete[] effect->inBuffer();
7827 } else {
7828 if (i == size - 1 && i != 0) {
7829 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7830 mEffects[i - 1]->configure();
7831 }
7832 }
7833 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007834 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007835 break;
7836 }
7837 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007838
7839 return mEffects.size();
7840}
7841
Eric Laurentcab11242010-07-15 12:50:15 -07007842// setDevice_l() must be called with PlaybackThread::mLock held
7843void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007844{
7845 size_t size = mEffects.size();
7846 for (size_t i = 0; i < size; i++) {
7847 mEffects[i]->setDevice(device);
7848 }
7849}
7850
Eric Laurentcab11242010-07-15 12:50:15 -07007851// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007852void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007853{
7854 size_t size = mEffects.size();
7855 for (size_t i = 0; i < size; i++) {
7856 mEffects[i]->setMode(mode);
7857 }
7858}
7859
Eric Laurentcab11242010-07-15 12:50:15 -07007860// setVolume_l() must be called with PlaybackThread::mLock held
7861bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007862{
7863 uint32_t newLeft = *left;
7864 uint32_t newRight = *right;
7865 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007866 int ctrlIdx = -1;
7867 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007868
Eric Laurentcab11242010-07-15 12:50:15 -07007869 // first update volume controller
7870 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007871 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007872 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7873 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007874 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007875 break;
7876 }
7877 }
7878
7879 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007880 if (hasControl) {
7881 *left = mNewLeftVolume;
7882 *right = mNewRightVolume;
7883 }
7884 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007885 }
7886
7887 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007888 mLeftVolume = newLeft;
7889 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007890
7891 // second get volume update from volume controller
7892 if (ctrlIdx >= 0) {
7893 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007894 mNewLeftVolume = newLeft;
7895 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007896 }
7897 // then indicate volume to all other effects in chain.
7898 // Pass altered volume to effects before volume controller
7899 // and requested volume to effects after controller
7900 uint32_t lVol = newLeft;
7901 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007902
Mathias Agopian65ab4712010-07-14 17:59:35 -07007903 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007904 if ((int)i == ctrlIdx) continue;
7905 // this also works for ctrlIdx == -1 when there is no volume controller
7906 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007907 lVol = *left;
7908 rVol = *right;
7909 }
7910 mEffects[i]->setVolume(&lVol, &rVol, false);
7911 }
7912 *left = newLeft;
7913 *right = newRight;
7914
7915 return hasControl;
7916}
7917
Mathias Agopian65ab4712010-07-14 17:59:35 -07007918status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7919{
7920 const size_t SIZE = 256;
7921 char buffer[SIZE];
7922 String8 result;
7923
7924 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7925 result.append(buffer);
7926
7927 bool locked = tryLock(mLock);
7928 // failed to lock - AudioFlinger is probably deadlocked
7929 if (!locked) {
7930 result.append("\tCould not lock mutex:\n");
7931 }
7932
Eric Laurentcab11242010-07-15 12:50:15 -07007933 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7934 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007935 mEffects.size(),
7936 (uint32_t)mInBuffer,
7937 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007938 mActiveTrackCnt);
7939 result.append(buffer);
7940 write(fd, result.string(), result.size());
7941
7942 for (size_t i = 0; i < mEffects.size(); ++i) {
7943 sp<EffectModule> effect = mEffects[i];
7944 if (effect != 0) {
7945 effect->dump(fd, args);
7946 }
7947 }
7948
7949 if (locked) {
7950 mLock.unlock();
7951 }
7952
7953 return NO_ERROR;
7954}
7955
Eric Laurent59255e42011-07-27 19:49:51 -07007956// must be called with ThreadBase::mLock held
7957void AudioFlinger::EffectChain::setEffectSuspended_l(
7958 const effect_uuid_t *type, bool suspend)
7959{
7960 sp<SuspendedEffectDesc> desc;
7961 // use effect type UUID timelow as key as there is no real risk of identical
7962 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007963 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007964 if (suspend) {
7965 if (index >= 0) {
7966 desc = mSuspendedEffects.valueAt(index);
7967 } else {
7968 desc = new SuspendedEffectDesc();
7969 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7970 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007971 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007972 }
7973 if (desc->mRefCount++ == 0) {
7974 sp<EffectModule> effect = getEffectIfEnabled(type);
7975 if (effect != 0) {
7976 desc->mEffect = effect;
7977 effect->setSuspended(true);
7978 effect->setEnabled(false);
7979 }
7980 }
7981 } else {
7982 if (index < 0) {
7983 return;
7984 }
7985 desc = mSuspendedEffects.valueAt(index);
7986 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007987 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007988 desc->mRefCount = 1;
7989 }
7990 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007991 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007992 if (desc->mEffect != 0) {
7993 sp<EffectModule> effect = desc->mEffect.promote();
7994 if (effect != 0) {
7995 effect->setSuspended(false);
7996 sp<EffectHandle> handle = effect->controlHandle();
7997 if (handle != 0) {
7998 effect->setEnabled(handle->enabled());
7999 }
8000 }
8001 desc->mEffect.clear();
8002 }
8003 mSuspendedEffects.removeItemsAt(index);
8004 }
8005 }
8006}
8007
8008// must be called with ThreadBase::mLock held
8009void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
8010{
8011 sp<SuspendedEffectDesc> desc;
8012
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008013 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07008014 if (suspend) {
8015 if (index >= 0) {
8016 desc = mSuspendedEffects.valueAt(index);
8017 } else {
8018 desc = new SuspendedEffectDesc();
8019 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01008020 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07008021 }
8022 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08008023 Vector< sp<EffectModule> > effects;
8024 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07008025 for (size_t i = 0; i < effects.size(); i++) {
8026 setEffectSuspended_l(&effects[i]->desc().type, true);
8027 }
8028 }
8029 } else {
8030 if (index < 0) {
8031 return;
8032 }
8033 desc = mSuspendedEffects.valueAt(index);
8034 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008035 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008036 desc->mRefCount = 1;
8037 }
8038 if (--desc->mRefCount == 0) {
8039 Vector<const effect_uuid_t *> types;
8040 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
8041 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
8042 continue;
8043 }
8044 types.add(&mSuspendedEffects.valueAt(i)->mType);
8045 }
8046 for (size_t i = 0; i < types.size(); i++) {
8047 setEffectSuspended_l(types[i], false);
8048 }
Steve Block3856b092011-10-20 11:56:00 +01008049 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008050 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
8051 }
8052 }
8053}
8054
Eric Laurent6bffdb82011-09-23 08:40:41 -07008055
8056// The volume effect is used for automated tests only
8057#ifndef OPENSL_ES_H_
8058static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
8059 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
8060const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
8061#endif //OPENSL_ES_H_
8062
Eric Laurentdb7c0792011-08-10 10:37:50 -07008063bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
8064{
8065 // auxiliary effects and visualizer are never suspended on output mix
8066 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8067 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07008068 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8069 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008070 return false;
8071 }
8072 return true;
8073}
8074
Glenn Kastend0539712012-01-30 12:56:03 -08008075void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07008076{
Glenn Kastend0539712012-01-30 12:56:03 -08008077 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07008078 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08008079 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8080 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07008081 }
Eric Laurent59255e42011-07-27 19:49:51 -07008082 }
Eric Laurent59255e42011-07-27 19:49:51 -07008083}
8084
8085sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8086 const effect_uuid_t *type)
8087{
Glenn Kasten090f0192012-01-30 13:00:02 -08008088 sp<EffectModule> effect = getEffectFromType_l(type);
8089 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008090}
8091
8092void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8093 bool enabled)
8094{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008095 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008096 if (enabled) {
8097 if (index < 0) {
8098 // if the effect is not suspend check if all effects are suspended
8099 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8100 if (index < 0) {
8101 return;
8102 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07008103 if (!isEffectEligibleForSuspend(effect->desc())) {
8104 return;
8105 }
Eric Laurent59255e42011-07-27 19:49:51 -07008106 setEffectSuspended_l(&effect->desc().type, enabled);
8107 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07008108 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008109 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07008110 return;
8111 }
Eric Laurent59255e42011-07-27 19:49:51 -07008112 }
Steve Block3856b092011-10-20 11:56:00 +01008113 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008114 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008115 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8116 // if effect is requested to suspended but was not yet enabled, supend it now.
8117 if (desc->mEffect == 0) {
8118 desc->mEffect = effect;
8119 effect->setEnabled(false);
8120 effect->setSuspended(true);
8121 }
8122 } else {
8123 if (index < 0) {
8124 return;
8125 }
Steve Block3856b092011-10-20 11:56:00 +01008126 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008127 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008128 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8129 desc->mEffect.clear();
8130 effect->setSuspended(false);
8131 }
8132}
8133
Mathias Agopian65ab4712010-07-14 17:59:35 -07008134#undef LOG_TAG
8135#define LOG_TAG "AudioFlinger"
8136
8137// ----------------------------------------------------------------------------
8138
8139status_t AudioFlinger::onTransact(
8140 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8141{
8142 return BnAudioFlinger::onTransact(code, data, reply, flags);
8143}
8144
Mathias Agopian65ab4712010-07-14 17:59:35 -07008145}; // namespace android