blob: e92629297a98524940e15bfd74109a2cc00a3c0c [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[] = {
Eric Laurent1a9ed112012-03-20 18:36:01 -0700153 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
154 AUDIO_HARDWARE_MODULE_ID_A2DP,
155 AUDIO_HARDWARE_MODULE_ID_USB,
Dima Zavin799a70e2011-04-18 16:57:27 -0700156};
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,
Glenn Kasten73d22752012-03-19 13:38:30 -0700507 channelMask, frameCount, sharedBuffer, lSessionId, flags, &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 }
Eric Laurenta011e352012-03-29 15:51:43 -0700516
517 // Look for sync events awaiting for a session to be used.
518 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
519 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
520 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
521 track->setSyncEvent(mPendingSyncEvents[i]);
522 mPendingSyncEvents.removeAt(i);
523 i--;
524 }
525 }
526 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700527 }
528 if (lStatus == NO_ERROR) {
529 trackHandle = new TrackHandle(track);
530 } else {
531 // remove local strong reference to Client before deleting the Track so that the Client
532 // destructor is called by the TrackBase destructor with mLock held
533 client.clear();
534 track.clear();
535 }
536
537Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700538 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700539 *status = lStatus;
540 }
541 return trackHandle;
542}
543
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800544uint32_t AudioFlinger::sampleRate(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("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700550 return 0;
551 }
552 return thread->sampleRate();
553}
554
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800555int AudioFlinger::channelCount(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("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700561 return 0;
562 }
563 return thread->channelCount();
564}
565
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800566audio_format_t AudioFlinger::format(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("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800572 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700573 }
574 return thread->format();
575}
576
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800577size_t AudioFlinger::frameCount(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("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700583 return 0;
584 }
585 return thread->frameCount();
586}
587
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800588uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700589{
590 Mutex::Autolock _l(mLock);
591 PlaybackThread *thread = checkPlaybackThread_l(output);
592 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000593 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700594 return 0;
595 }
596 return thread->latency();
597}
598
599status_t AudioFlinger::setMasterVolume(float value)
600{
Eric Laurenta1884f92011-08-23 08:25:03 -0700601 status_t ret = initCheck();
602 if (ret != NO_ERROR) {
603 return ret;
604 }
605
Mathias Agopian65ab4712010-07-14 17:59:35 -0700606 // check calling permissions
607 if (!settingsAllowed()) {
608 return PERMISSION_DENIED;
609 }
610
John Grossman4ff14ba2012-02-08 16:37:41 -0800611 float swmv = value;
612
Mathias Agopian65ab4712010-07-14 17:59:35 -0700613 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800614 if (MVS_NONE != mMasterVolumeSupportLvl) {
615 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
616 AutoMutex lock(mHardwareLock);
617 audio_hw_device_t *dev = mAudioHwDevs[i];
618
619 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
620 if (NULL != dev->set_master_volume) {
621 dev->set_master_volume(dev, value);
622 }
623 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800624 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800625
626 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700627 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700628
Eric Laurent93575202011-01-18 18:39:02 -0800629 Mutex::Autolock _l(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -0800630 mMasterVolume = value;
631 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800632 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700633 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700634
635 return NO_ERROR;
636}
637
Glenn Kastenf78aee72012-01-04 11:00:47 -0800638status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700639{
Eric Laurenta1884f92011-08-23 08:25:03 -0700640 status_t ret = initCheck();
641 if (ret != NO_ERROR) {
642 return ret;
643 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700644
645 // check calling permissions
646 if (!settingsAllowed()) {
647 return PERMISSION_DENIED;
648 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800649 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000650 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700651 return BAD_VALUE;
652 }
653
654 { // scope for the lock
655 AutoMutex lock(mHardwareLock);
656 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700657 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700658 mHardwareStatus = AUDIO_HW_IDLE;
659 }
660
661 if (NO_ERROR == ret) {
662 Mutex::Autolock _l(mLock);
663 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800664 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700665 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700666 }
667
668 return ret;
669}
670
671status_t AudioFlinger::setMicMute(bool state)
672{
Eric Laurenta1884f92011-08-23 08:25:03 -0700673 status_t ret = initCheck();
674 if (ret != NO_ERROR) {
675 return ret;
676 }
677
Mathias Agopian65ab4712010-07-14 17:59:35 -0700678 // check calling permissions
679 if (!settingsAllowed()) {
680 return PERMISSION_DENIED;
681 }
682
683 AutoMutex lock(mHardwareLock);
684 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700685 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700686 mHardwareStatus = AUDIO_HW_IDLE;
687 return ret;
688}
689
690bool AudioFlinger::getMicMute() const
691{
Eric Laurenta1884f92011-08-23 08:25:03 -0700692 status_t ret = initCheck();
693 if (ret != NO_ERROR) {
694 return false;
695 }
696
Dima Zavinfce7a472011-04-19 22:30:36 -0700697 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800698 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700699 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700700 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700701 mHardwareStatus = AUDIO_HW_IDLE;
702 return state;
703}
704
705status_t AudioFlinger::setMasterMute(bool muted)
706{
707 // check calling permissions
708 if (!settingsAllowed()) {
709 return PERMISSION_DENIED;
710 }
711
Eric Laurent93575202011-01-18 18:39:02 -0800712 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800713 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700714 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800715 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700716 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700717
718 return NO_ERROR;
719}
720
721float AudioFlinger::masterVolume() const
722{
Glenn Kasten98067102011-12-13 11:47:54 -0800723 Mutex::Autolock _l(mLock);
724 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700725}
726
John Grossman4ff14ba2012-02-08 16:37:41 -0800727float AudioFlinger::masterVolumeSW() const
728{
729 Mutex::Autolock _l(mLock);
730 return masterVolumeSW_l();
731}
732
Mathias Agopian65ab4712010-07-14 17:59:35 -0700733bool AudioFlinger::masterMute() const
734{
Glenn Kasten98067102011-12-13 11:47:54 -0800735 Mutex::Autolock _l(mLock);
736 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700737}
738
John Grossman4ff14ba2012-02-08 16:37:41 -0800739float AudioFlinger::masterVolume_l() const
740{
741 if (MVS_FULL == mMasterVolumeSupportLvl) {
742 float ret_val;
743 AutoMutex lock(mHardwareLock);
744
745 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800746 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
747 (NULL != mPrimaryHardwareDev->get_master_volume),
748 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800749
750 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
751 mHardwareStatus = AUDIO_HW_IDLE;
752 return ret_val;
753 }
754
755 return mMasterVolume;
756}
757
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800758status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
759 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700760{
761 // check calling permissions
762 if (!settingsAllowed()) {
763 return PERMISSION_DENIED;
764 }
765
Glenn Kasten263709e2012-01-06 08:40:01 -0800766 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000767 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700768 return BAD_VALUE;
769 }
770
771 AutoMutex lock(mLock);
772 PlaybackThread *thread = NULL;
773 if (output) {
774 thread = checkPlaybackThread_l(output);
775 if (thread == NULL) {
776 return BAD_VALUE;
777 }
778 }
779
780 mStreamTypes[stream].volume = value;
781
782 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800783 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700784 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700785 }
786 } else {
787 thread->setStreamVolume(stream, value);
788 }
789
790 return NO_ERROR;
791}
792
Glenn Kastenfff6d712012-01-12 16:38:12 -0800793status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700794{
795 // check calling permissions
796 if (!settingsAllowed()) {
797 return PERMISSION_DENIED;
798 }
799
Glenn Kasten263709e2012-01-06 08:40:01 -0800800 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700801 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000802 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700803 return BAD_VALUE;
804 }
805
Eric Laurent93575202011-01-18 18:39:02 -0800806 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700807 mStreamTypes[stream].mute = muted;
808 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700809 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700810
811 return NO_ERROR;
812}
813
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800814float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700815{
Glenn Kasten263709e2012-01-06 08:40:01 -0800816 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700817 return 0.0f;
818 }
819
820 AutoMutex lock(mLock);
821 float volume;
822 if (output) {
823 PlaybackThread *thread = checkPlaybackThread_l(output);
824 if (thread == NULL) {
825 return 0.0f;
826 }
827 volume = thread->streamVolume(stream);
828 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800829 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700830 }
831
832 return volume;
833}
834
Glenn Kastenfff6d712012-01-12 16:38:12 -0800835bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700836{
Glenn Kasten263709e2012-01-06 08:40:01 -0800837 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700838 return true;
839 }
840
Glenn Kasten6637baa2012-01-09 09:40:36 -0800841 AutoMutex lock(mLock);
842 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700843}
844
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800845status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700846{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800847 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700848 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
849 // check calling permissions
850 if (!settingsAllowed()) {
851 return PERMISSION_DENIED;
852 }
853
Mathias Agopian65ab4712010-07-14 17:59:35 -0700854 // ioHandle == 0 means the parameters are global to the audio hardware interface
855 if (ioHandle == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700856 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800857 {
858 AutoMutex lock(mHardwareLock);
859 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700860 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
861 audio_hw_device_t *dev = mAudioHwDevs[i];
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800862 status_t result = dev->set_parameters(dev, keyValuePairs.string());
Dima Zavin799a70e2011-04-18 16:57:27 -0700863 final_result = result ?: final_result;
864 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700865 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800866 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700867 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
868 AudioParameter param = AudioParameter(keyValuePairs);
869 String8 value;
870 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
871 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700872 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
873 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700874 for (size_t i = 0; i < mRecordThreads.size(); i++) {
875 sp<RecordThread> thread = mRecordThreads.valueAt(i);
876 RecordThread::RecordTrack *track = thread->track();
877 if (track != NULL) {
878 audio_devices_t device = (audio_devices_t)(
879 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700880 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700881 thread->setEffectSuspended(FX_IID_AEC,
882 suspend,
883 track->sessionId());
884 thread->setEffectSuspended(FX_IID_NS,
885 suspend,
886 track->sessionId());
887 }
888 }
Eric Laurentbee53372011-08-29 12:42:48 -0700889 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700890 }
891 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700892 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700893 }
894
895 // hold a strong ref on thread in case closeOutput() or closeInput() is called
896 // and the thread is exited once the lock is released
897 sp<ThreadBase> thread;
898 {
899 Mutex::Autolock _l(mLock);
900 thread = checkPlaybackThread_l(ioHandle);
901 if (thread == NULL) {
902 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800903 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700904 // indicate output device change to all input threads for pre processing
905 AudioParameter param = AudioParameter(keyValuePairs);
906 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700907 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
908 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700909 for (size_t i = 0; i < mRecordThreads.size(); i++) {
910 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
911 }
912 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700913 }
914 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800915 if (thread != 0) {
916 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700917 }
918 return BAD_VALUE;
919}
920
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800921String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700922{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800923// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700924// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
925
926 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700927 String8 out_s8;
928
Dima Zavin799a70e2011-04-18 16:57:27 -0700929 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800930 char *s;
931 {
932 AutoMutex lock(mHardwareLock);
933 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700934 audio_hw_device_t *dev = mAudioHwDevs[i];
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800935 s = dev->get_parameters(dev, keys.string());
936 mHardwareStatus = AUDIO_HW_IDLE;
937 }
John Grossmanef7740b2012-02-09 11:28:36 -0800938 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700939 free(s);
940 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700941 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700942 }
943
944 Mutex::Autolock _l(mLock);
945
946 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
947 if (playbackThread != NULL) {
948 return playbackThread->getParameters(keys);
949 }
950 RecordThread *recordThread = checkRecordThread_l(ioHandle);
951 if (recordThread != NULL) {
952 return recordThread->getParameters(keys);
953 }
954 return String8("");
955}
956
Glenn Kastenf587ba52012-01-26 16:25:10 -0800957size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700958{
Eric Laurenta1884f92011-08-23 08:25:03 -0700959 status_t ret = initCheck();
960 if (ret != NO_ERROR) {
961 return 0;
962 }
963
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800964 AutoMutex lock(mHardwareLock);
965 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
966 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
967 mHardwareStatus = AUDIO_HW_IDLE;
968 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700969}
970
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800971unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700972{
973 if (ioHandle == 0) {
974 return 0;
975 }
976
977 Mutex::Autolock _l(mLock);
978
979 RecordThread *recordThread = checkRecordThread_l(ioHandle);
980 if (recordThread != NULL) {
981 return recordThread->getInputFramesLost();
982 }
983 return 0;
984}
985
986status_t AudioFlinger::setVoiceVolume(float value)
987{
Eric Laurenta1884f92011-08-23 08:25:03 -0700988 status_t ret = initCheck();
989 if (ret != NO_ERROR) {
990 return ret;
991 }
992
Mathias Agopian65ab4712010-07-14 17:59:35 -0700993 // check calling permissions
994 if (!settingsAllowed()) {
995 return PERMISSION_DENIED;
996 }
997
998 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800999 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -07001000 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001001 mHardwareStatus = AUDIO_HW_IDLE;
1002
1003 return ret;
1004}
1005
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001006status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1007 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001008{
1009 status_t status;
1010
1011 Mutex::Autolock _l(mLock);
1012
1013 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1014 if (playbackThread != NULL) {
1015 return playbackThread->getRenderPosition(halFrames, dspFrames);
1016 }
1017
1018 return BAD_VALUE;
1019}
1020
1021void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1022{
1023
1024 Mutex::Autolock _l(mLock);
1025
Glenn Kastenbb001922012-02-03 11:10:26 -08001026 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001027 if (mNotificationClients.indexOfKey(pid) < 0) {
1028 sp<NotificationClient> notificationClient = new NotificationClient(this,
1029 client,
1030 pid);
Steve Block3856b092011-10-20 11:56:00 +01001031 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001032
1033 mNotificationClients.add(pid, notificationClient);
1034
1035 sp<IBinder> binder = client->asBinder();
1036 binder->linkToDeath(notificationClient);
1037
1038 // the config change is always sent from playback or record threads to avoid deadlock
1039 // with AudioSystem::gLock
1040 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1041 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1042 }
1043
1044 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1045 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1046 }
1047 }
1048}
1049
1050void AudioFlinger::removeNotificationClient(pid_t pid)
1051{
1052 Mutex::Autolock _l(mLock);
1053
Glenn Kastena3b09252012-01-20 09:19:01 -08001054 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001055
Steve Block3856b092011-10-20 11:56:00 +01001056 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001057 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001058 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001059 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001060 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001061 ALOGV(" pid %d @ %d", ref->mPid, i);
1062 if (ref->mPid == pid) {
1063 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001064 mAudioSessionRefs.removeAt(i);
1065 delete ref;
1066 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001067 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001068 } else {
1069 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001070 }
1071 }
1072 if (removed) {
1073 purgeStaleEffects_l();
1074 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001075}
1076
1077// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001078void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001079{
1080 size_t size = mNotificationClients.size();
1081 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001082 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1083 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001084 }
1085}
1086
1087// removeClient_l() must be called with AudioFlinger::mLock held
1088void AudioFlinger::removeClient_l(pid_t pid)
1089{
Steve Block3856b092011-10-20 11:56:00 +01001090 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001091 mClients.removeItem(pid);
1092}
1093
1094
1095// ----------------------------------------------------------------------------
1096
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001097AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1098 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001099 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001100 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001101 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
1102 // mChannelMask
1103 mChannelCount(0),
1104 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1105 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001106 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001107 mDevice(device),
1108 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001109{
1110}
1111
1112AudioFlinger::ThreadBase::~ThreadBase()
1113{
1114 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001115 // do not lock the mutex in destructor
1116 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001117 if (mPowerManager != 0) {
1118 sp<IBinder> binder = mPowerManager->asBinder();
1119 binder->unlinkToDeath(mDeathRecipient);
1120 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001121}
1122
1123void AudioFlinger::ThreadBase::exit()
1124{
Steve Block3856b092011-10-20 11:56:00 +01001125 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001126 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001127 // This lock prevents the following race in thread (uniprocessor for illustration):
1128 // if (!exitPending()) {
1129 // // context switch from here to exit()
1130 // // exit() calls requestExit(), what exitPending() observes
1131 // // exit() calls signal(), which is dropped since no waiters
1132 // // context switch back from exit() to here
1133 // mWaitWorkCV.wait(...);
1134 // // now thread is hung
1135 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001136 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001137 requestExit();
1138 mWaitWorkCV.signal();
1139 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001140 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1141 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001142 requestExitAndWait();
1143}
1144
Mathias Agopian65ab4712010-07-14 17:59:35 -07001145status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1146{
1147 status_t status;
1148
Steve Block3856b092011-10-20 11:56:00 +01001149 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001150 Mutex::Autolock _l(mLock);
1151
1152 mNewParameters.add(keyValuePairs);
1153 mWaitWorkCV.signal();
1154 // wait condition with timeout in case the thread loop has exited
1155 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001156 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001157 status = mParamStatus;
1158 mWaitWorkCV.signal();
1159 } else {
1160 status = TIMED_OUT;
1161 }
1162 return status;
1163}
1164
1165void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1166{
1167 Mutex::Autolock _l(mLock);
1168 sendConfigEvent_l(event, param);
1169}
1170
1171// sendConfigEvent_l() must be called with ThreadBase::mLock held
1172void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1173{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001174 ConfigEvent configEvent;
1175 configEvent.mEvent = event;
1176 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001177 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001178 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001179 mWaitWorkCV.signal();
1180}
1181
1182void AudioFlinger::ThreadBase::processConfigEvents()
1183{
1184 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001185 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001186 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001187 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001188 mConfigEvents.removeAt(0);
1189 // release mLock before locking AudioFlinger mLock: lock order is always
1190 // AudioFlinger then ThreadBase to avoid cross deadlock
1191 mLock.unlock();
1192 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001193 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001194 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001195 mLock.lock();
1196 }
1197 mLock.unlock();
1198}
1199
1200status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1201{
1202 const size_t SIZE = 256;
1203 char buffer[SIZE];
1204 String8 result;
1205
1206 bool locked = tryLock(mLock);
1207 if (!locked) {
1208 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1209 write(fd, buffer, strlen(buffer));
1210 }
1211
Eric Laurent612bbb52012-03-14 15:03:26 -07001212 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1213 result.append(buffer);
1214 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1215 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001216 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1217 result.append(buffer);
1218 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1219 result.append(buffer);
1220 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1221 result.append(buffer);
1222 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1223 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001224 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1225 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001226 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1227 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001228 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001229 result.append(buffer);
1230
1231 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1232 result.append(buffer);
1233 result.append(" Index Command");
1234 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1235 snprintf(buffer, SIZE, "\n %02d ", i);
1236 result.append(buffer);
1237 result.append(mNewParameters[i]);
1238 }
1239
1240 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1241 result.append(buffer);
1242 snprintf(buffer, SIZE, " Index event param\n");
1243 result.append(buffer);
1244 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001245 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001246 result.append(buffer);
1247 }
1248 result.append("\n");
1249
1250 write(fd, result.string(), result.size());
1251
1252 if (locked) {
1253 mLock.unlock();
1254 }
1255 return NO_ERROR;
1256}
1257
Eric Laurent1d2bff02011-07-24 17:49:51 -07001258status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1259{
1260 const size_t SIZE = 256;
1261 char buffer[SIZE];
1262 String8 result;
1263
1264 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1265 write(fd, buffer, strlen(buffer));
1266
1267 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1268 sp<EffectChain> chain = mEffectChains[i];
1269 if (chain != 0) {
1270 chain->dump(fd, args);
1271 }
1272 }
1273 return NO_ERROR;
1274}
1275
Eric Laurentfeb0db62011-07-22 09:04:31 -07001276void AudioFlinger::ThreadBase::acquireWakeLock()
1277{
1278 Mutex::Autolock _l(mLock);
1279 acquireWakeLock_l();
1280}
1281
1282void AudioFlinger::ThreadBase::acquireWakeLock_l()
1283{
1284 if (mPowerManager == 0) {
1285 // use checkService() to avoid blocking if power service is not up yet
1286 sp<IBinder> binder =
1287 defaultServiceManager()->checkService(String16("power"));
1288 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001289 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001290 } else {
1291 mPowerManager = interface_cast<IPowerManager>(binder);
1292 binder->linkToDeath(mDeathRecipient);
1293 }
1294 }
1295 if (mPowerManager != 0) {
1296 sp<IBinder> binder = new BBinder();
1297 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1298 binder,
1299 String16(mName));
1300 if (status == NO_ERROR) {
1301 mWakeLockToken = binder;
1302 }
Steve Block3856b092011-10-20 11:56:00 +01001303 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001304 }
1305}
1306
1307void AudioFlinger::ThreadBase::releaseWakeLock()
1308{
1309 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001310 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001311}
1312
1313void AudioFlinger::ThreadBase::releaseWakeLock_l()
1314{
1315 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001316 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001317 if (mPowerManager != 0) {
1318 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1319 }
1320 mWakeLockToken.clear();
1321 }
1322}
1323
1324void AudioFlinger::ThreadBase::clearPowerManager()
1325{
1326 Mutex::Autolock _l(mLock);
1327 releaseWakeLock_l();
1328 mPowerManager.clear();
1329}
1330
1331void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1332{
1333 sp<ThreadBase> thread = mThread.promote();
1334 if (thread != 0) {
1335 thread->clearPowerManager();
1336 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001337 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001338}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001339
Eric Laurent59255e42011-07-27 19:49:51 -07001340void AudioFlinger::ThreadBase::setEffectSuspended(
1341 const effect_uuid_t *type, bool suspend, int sessionId)
1342{
1343 Mutex::Autolock _l(mLock);
1344 setEffectSuspended_l(type, suspend, sessionId);
1345}
1346
1347void AudioFlinger::ThreadBase::setEffectSuspended_l(
1348 const effect_uuid_t *type, bool suspend, int sessionId)
1349{
Glenn Kasten090f0192012-01-30 13:00:02 -08001350 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001351 if (chain != 0) {
1352 if (type != NULL) {
1353 chain->setEffectSuspended_l(type, suspend);
1354 } else {
1355 chain->setEffectSuspendedAll_l(suspend);
1356 }
1357 }
1358
1359 updateSuspendedSessions_l(type, suspend, sessionId);
1360}
1361
1362void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1363{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001364 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001365 if (index < 0) {
1366 return;
1367 }
1368
1369 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1370 mSuspendedSessions.editValueAt(index);
1371
1372 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001373 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001374 for (int j = 0; j < desc->mRefCount; j++) {
1375 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1376 chain->setEffectSuspendedAll_l(true);
1377 } else {
Steve Block3856b092011-10-20 11:56:00 +01001378 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001379 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001380 chain->setEffectSuspended_l(&desc->mType, true);
1381 }
1382 }
1383 }
1384}
1385
Eric Laurent59255e42011-07-27 19:49:51 -07001386void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1387 bool suspend,
1388 int sessionId)
1389{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001390 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001391
1392 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1393
1394 if (suspend) {
1395 if (index >= 0) {
1396 sessionEffects = mSuspendedSessions.editValueAt(index);
1397 } else {
1398 mSuspendedSessions.add(sessionId, sessionEffects);
1399 }
1400 } else {
1401 if (index < 0) {
1402 return;
1403 }
1404 sessionEffects = mSuspendedSessions.editValueAt(index);
1405 }
1406
1407
1408 int key = EffectChain::kKeyForSuspendAll;
1409 if (type != NULL) {
1410 key = type->timeLow;
1411 }
1412 index = sessionEffects.indexOfKey(key);
1413
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001414 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001415 if (suspend) {
1416 if (index >= 0) {
1417 desc = sessionEffects.valueAt(index);
1418 } else {
1419 desc = new SuspendedSessionDesc();
1420 if (type != NULL) {
1421 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1422 }
1423 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001424 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001425 }
1426 desc->mRefCount++;
1427 } else {
1428 if (index < 0) {
1429 return;
1430 }
1431 desc = sessionEffects.valueAt(index);
1432 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001433 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001434 sessionEffects.removeItemsAt(index);
1435 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001436 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001437 sessionId);
1438 mSuspendedSessions.removeItem(sessionId);
1439 }
1440 }
1441 }
1442 if (!sessionEffects.isEmpty()) {
1443 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1444 }
1445}
1446
1447void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1448 bool enabled,
1449 int sessionId)
1450{
1451 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001452 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1453}
Eric Laurent59255e42011-07-27 19:49:51 -07001454
Eric Laurenta85a74a2011-10-19 11:44:54 -07001455void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1456 bool enabled,
1457 int sessionId)
1458{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001459 if (mType != RECORD) {
1460 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1461 // another session. This gives the priority to well behaved effect control panels
1462 // and applications not using global effects.
1463 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1464 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1465 }
1466 }
Eric Laurent59255e42011-07-27 19:49:51 -07001467
1468 sp<EffectChain> chain = getEffectChain_l(sessionId);
1469 if (chain != 0) {
1470 chain->checkSuspendOnEffectEnabled(effect, enabled);
1471 }
1472}
1473
Mathias Agopian65ab4712010-07-14 17:59:35 -07001474// ----------------------------------------------------------------------------
1475
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001476AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1477 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001478 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001479 uint32_t device,
1480 type_t type)
1481 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001482 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1483 // Assumes constructor is called by AudioFlinger with it's mLock held,
1484 // but it would be safer to explicitly pass initial masterMute as parameter
1485 mMasterMute(audioFlinger->masterMute_l()),
1486 // mStreamTypes[] initialized in constructor body
1487 mOutput(output),
1488 // Assumes constructor is called by AudioFlinger with it's mLock held,
1489 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001490 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001491 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001492 mMixerStatus(MIXER_IDLE),
Glenn Kasten66fcab92012-02-24 14:59:21 -08001493 mPrevMixerStatus(MIXER_IDLE),
1494 standbyDelay(AudioFlinger::mStandbyTimeInNsecs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001495{
Glenn Kasten480b4682012-02-28 12:30:08 -08001496 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001497
Mathias Agopian65ab4712010-07-14 17:59:35 -07001498 readOutputParameters();
1499
Glenn Kasten263709e2012-01-06 08:40:01 -08001500 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001501 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1502 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1503 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001504 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1505 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001506 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001507 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1508 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001509}
1510
1511AudioFlinger::PlaybackThread::~PlaybackThread()
1512{
1513 delete [] mMixBuffer;
1514}
1515
1516status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1517{
1518 dumpInternals(fd, args);
1519 dumpTracks(fd, args);
1520 dumpEffectChains(fd, args);
1521 return NO_ERROR;
1522}
1523
1524status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1525{
1526 const size_t SIZE = 256;
1527 char buffer[SIZE];
1528 String8 result;
1529
1530 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1531 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001532 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 -07001533 for (size_t i = 0; i < mTracks.size(); ++i) {
1534 sp<Track> track = mTracks[i];
1535 if (track != 0) {
1536 track->dump(buffer, SIZE);
1537 result.append(buffer);
1538 }
1539 }
1540
1541 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1542 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001543 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 -07001544 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001545 sp<Track> track = mActiveTracks[i].promote();
1546 if (track != 0) {
1547 track->dump(buffer, SIZE);
1548 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001549 }
1550 }
1551 write(fd, result.string(), result.size());
1552 return NO_ERROR;
1553}
1554
Mathias Agopian65ab4712010-07-14 17:59:35 -07001555status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1556{
1557 const size_t SIZE = 256;
1558 char buffer[SIZE];
1559 String8 result;
1560
1561 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1562 result.append(buffer);
1563 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1564 result.append(buffer);
1565 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1566 result.append(buffer);
1567 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1568 result.append(buffer);
1569 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1570 result.append(buffer);
1571 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1572 result.append(buffer);
1573 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1574 result.append(buffer);
1575 write(fd, result.string(), result.size());
1576
1577 dumpBase(fd, args);
1578
1579 return NO_ERROR;
1580}
1581
1582// Thread virtuals
1583status_t AudioFlinger::PlaybackThread::readyToRun()
1584{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001585 status_t status = initCheck();
1586 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001587 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001588 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001589 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001590 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001591 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001592}
1593
1594void AudioFlinger::PlaybackThread::onFirstRef()
1595{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001596 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001597}
1598
1599// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001600sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001601 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001602 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001603 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001604 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001605 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001606 int frameCount,
1607 const sp<IMemory>& sharedBuffer,
1608 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001609 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610 status_t *status)
1611{
1612 sp<Track> track;
1613 status_t lStatus;
1614
Glenn Kasten73d22752012-03-19 13:38:30 -07001615 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1616
1617 // client expresses a preference for FAST, but we get the final say
1618 if ((flags & IAudioFlinger::TRACK_FAST) &&
1619 !(
1620 // not timed
1621 (!isTimed) &&
1622 // either of these use cases:
1623 (
1624 // use case 1: shared buffer with any frame count
1625 (
1626 (sharedBuffer != 0)
1627 ) ||
1628 // use case 2: callback handler and small power-of-2 frame count
1629 (
1630 // unfortunately we can't verify that there's a callback until start()
1631 // FIXME supported frame counts should not be hard-coded
1632 (
1633 (frameCount == 128) ||
1634 (frameCount == 256) ||
1635 (frameCount == 512)
1636 )
1637 )
1638 ) &&
1639 // PCM data
1640 audio_is_linear_pcm(format) &&
1641 // mono or stereo
1642 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1643 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1644 // hardware sample rate
1645 (sampleRate == mSampleRate)
1646 // FIXME test that MixerThread for this fast track has a capable output HAL
1647 // FIXME add a permission test also?
1648 ) ) {
1649 ALOGW("AUDIO_POLICY_OUTPUT_FLAG_FAST denied");
1650 flags &= ~IAudioFlinger::TRACK_FAST;
1651 }
1652
Mathias Agopian65ab4712010-07-14 17:59:35 -07001653 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001654 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1655 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001656 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001657 "for output %p with format %d",
1658 sampleRate, format, channelMask, mOutput, mFormat);
1659 lStatus = BAD_VALUE;
1660 goto Exit;
1661 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001662 }
1663 } else {
1664 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1665 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001666 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001667 lStatus = BAD_VALUE;
1668 goto Exit;
1669 }
1670 }
1671
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001672 lStatus = initCheck();
1673 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001674 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001675 goto Exit;
1676 }
1677
1678 { // scope for mLock
1679 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001680
1681 // all tracks in same audio session must share the same routing strategy otherwise
1682 // conflicts will happen when tracks are moved from one output to another by audio policy
1683 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001684 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001685 for (size_t i = 0; i < mTracks.size(); ++i) {
1686 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001687 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001688 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001689 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001690 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001691 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001692 lStatus = BAD_VALUE;
1693 goto Exit;
1694 }
1695 }
1696 }
1697
John Grossman4ff14ba2012-02-08 16:37:41 -08001698 if (!isTimed) {
1699 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001700 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001701 } else {
1702 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1703 channelMask, frameCount, sharedBuffer, sessionId);
1704 }
1705 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001706 lStatus = NO_MEMORY;
1707 goto Exit;
1708 }
1709 mTracks.add(track);
1710
1711 sp<EffectChain> chain = getEffectChain_l(sessionId);
1712 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001713 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001714 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001715 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001716 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001717 }
1718 }
1719 lStatus = NO_ERROR;
1720
1721Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001722 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001723 *status = lStatus;
1724 }
1725 return track;
1726}
1727
1728uint32_t AudioFlinger::PlaybackThread::latency() const
1729{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001730 Mutex::Autolock _l(mLock);
1731 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001732 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001733 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001734 return 0;
1735 }
1736}
1737
Glenn Kasten6637baa2012-01-09 09:40:36 -08001738void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001739{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001740 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001741 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742}
1743
Glenn Kasten6637baa2012-01-09 09:40:36 -08001744void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001745{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001746 Mutex::Autolock _l(mLock);
1747 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001748}
1749
Glenn Kasten6637baa2012-01-09 09:40:36 -08001750void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001751{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001752 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001753 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001754}
1755
Glenn Kasten6637baa2012-01-09 09:40:36 -08001756void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001757{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001758 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001759 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001760}
1761
Glenn Kastenfff6d712012-01-12 16:38:12 -08001762float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001763{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001764 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001765 return mStreamTypes[stream].volume;
1766}
1767
Mathias Agopian65ab4712010-07-14 17:59:35 -07001768// addTrack_l() must be called with ThreadBase::mLock held
1769status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1770{
1771 status_t status = ALREADY_EXISTS;
1772
1773 // set retry count for buffer fill
1774 track->mRetryCount = kMaxTrackStartupRetries;
1775 if (mActiveTracks.indexOf(track) < 0) {
1776 // the track is newly added, make sure it fills up all its
1777 // buffers before playing. This is to ensure the client will
1778 // effectively get the latency it requested.
1779 track->mFillingUpStatus = Track::FS_FILLING;
1780 track->mResetDone = false;
1781 mActiveTracks.add(track);
1782 if (track->mainBuffer() != mMixBuffer) {
1783 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1784 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001785 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001786 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001787 }
1788 }
1789
1790 status = NO_ERROR;
1791 }
1792
Steve Block3856b092011-10-20 11:56:00 +01001793 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001794 mWaitWorkCV.broadcast();
1795
1796 return status;
1797}
1798
1799// destroyTrack_l() must be called with ThreadBase::mLock held
1800void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1801{
1802 track->mState = TrackBase::TERMINATED;
1803 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001804 removeTrack_l(track);
1805 }
1806}
1807
1808void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1809{
1810 mTracks.remove(track);
1811 deleteTrackName_l(track->name());
1812 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1813 if (chain != 0) {
1814 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001815 }
1816}
1817
1818String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1819{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001820 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001821 char *s;
1822
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001823 Mutex::Autolock _l(mLock);
1824 if (initCheck() != NO_ERROR) {
1825 return out_s8;
1826 }
1827
Dima Zavin799a70e2011-04-18 16:57:27 -07001828 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001829 out_s8 = String8(s);
1830 free(s);
1831 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001832}
1833
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001834// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001835void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1836 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001837 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001838
Steve Block3856b092011-10-20 11:56:00 +01001839 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001840
1841 switch (event) {
1842 case AudioSystem::OUTPUT_OPENED:
1843 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001844 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001845 desc.samplingRate = mSampleRate;
1846 desc.format = mFormat;
1847 desc.frameCount = mFrameCount;
1848 desc.latency = latency();
1849 param2 = &desc;
1850 break;
1851
1852 case AudioSystem::STREAM_CONFIG_CHANGED:
1853 param2 = &param;
1854 case AudioSystem::OUTPUT_CLOSED:
1855 default:
1856 break;
1857 }
1858 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1859}
1860
1861void AudioFlinger::PlaybackThread::readOutputParameters()
1862{
Dima Zavin799a70e2011-04-18 16:57:27 -07001863 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001864 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1865 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001866 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001867 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001868 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001869
1870 // FIXME - Current mixer implementation only supports stereo output: Always
1871 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001872 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001873 mMixBuffer = new int16_t[mFrameCount * 2];
1874 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1875
Eric Laurentde070132010-07-13 04:45:46 -07001876 // force reconfiguration of effect chains and engines to take new buffer size and audio
1877 // parameters into account
1878 // Note that mLock is not held when readOutputParameters() is called from the constructor
1879 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1880 // matter.
1881 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1882 Vector< sp<EffectChain> > effectChains = mEffectChains;
1883 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001884 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001885 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001886}
1887
1888status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1889{
Glenn Kastena0d68332012-01-27 16:47:15 -08001890 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001891 return BAD_VALUE;
1892 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001893 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001894 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001895 return INVALID_OPERATION;
1896 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001897 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001898
Dima Zavin799a70e2011-04-18 16:57:27 -07001899 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001900}
1901
Eric Laurent39e94f82010-07-28 01:32:47 -07001902uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001903{
1904 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001905 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001906 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001907 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001908 }
1909
1910 for (size_t i = 0; i < mTracks.size(); ++i) {
1911 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001912 if (sessionId == track->sessionId() &&
1913 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001914 result |= TRACK_SESSION;
1915 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001916 }
1917 }
1918
Eric Laurent39e94f82010-07-28 01:32:47 -07001919 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001920}
1921
Eric Laurentde070132010-07-13 04:45:46 -07001922uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1923{
Dima Zavinfce7a472011-04-19 22:30:36 -07001924 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001925 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001926 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1927 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001928 }
1929 for (size_t i = 0; i < mTracks.size(); i++) {
1930 sp<Track> track = mTracks[i];
1931 if (sessionId == track->sessionId() &&
1932 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001933 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07001934 }
1935 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001936 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001937}
1938
Mathias Agopian65ab4712010-07-14 17:59:35 -07001939
Glenn Kastenaed850d2012-01-26 09:46:34 -08001940AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001941{
1942 Mutex::Autolock _l(mLock);
1943 return mOutput;
1944}
1945
1946AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1947{
1948 Mutex::Autolock _l(mLock);
1949 AudioStreamOut *output = mOutput;
1950 mOutput = NULL;
1951 return output;
1952}
1953
1954// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08001955audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001956{
1957 if (mOutput == NULL) {
1958 return NULL;
1959 }
1960 return &mOutput->stream->common;
1961}
1962
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08001963uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08001964{
1965 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1966 // decoding and transfer time. So sleeping for half of the latency would likely cause
1967 // underruns
1968 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1969 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1970 } else {
1971 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1972 }
1973}
1974
Eric Laurenta011e352012-03-29 15:51:43 -07001975status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1976{
1977 if (!isValidSyncEvent(event)) {
1978 return BAD_VALUE;
1979 }
1980
1981 Mutex::Autolock _l(mLock);
1982
1983 for (size_t i = 0; i < mTracks.size(); ++i) {
1984 sp<Track> track = mTracks[i];
1985 if (event->triggerSession() == track->sessionId()) {
1986 track->setSyncEvent(event);
1987 return NO_ERROR;
1988 }
1989 }
1990
1991 return NAME_NOT_FOUND;
1992}
1993
1994bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
1995{
1996 switch (event->type()) {
1997 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
1998 return true;
1999 default:
2000 break;
2001 }
2002 return false;
2003}
2004
Mathias Agopian65ab4712010-07-14 17:59:35 -07002005// ----------------------------------------------------------------------------
2006
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002007AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002008 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten000f0e32012-03-01 17:10:56 -08002009 : PlaybackThread(audioFlinger, output, id, device, type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002010{
Glenn Kasten000f0e32012-03-01 17:10:56 -08002011 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002012 // FIXME - Current mixer implementation only supports stereo output
2013 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002014 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002015 }
2016}
2017
2018AudioFlinger::MixerThread::~MixerThread()
2019{
2020 delete mAudioMixer;
2021}
2022
Glenn Kasten83efdd02012-02-24 07:21:32 -08002023class CpuStats {
2024public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002025 CpuStats();
2026 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002027#ifdef DEBUG_CPU_USAGE
2028private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002029 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2030 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2031
2032 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2033
2034 int mCpuNum; // thread's current CPU number
2035 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002036#endif
2037};
2038
Glenn Kasten190a46f2012-03-06 11:27:10 -08002039CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002040#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002041 : mCpuNum(-1), mCpukHz(-1)
2042#endif
2043{
2044}
2045
2046void CpuStats::sample(const String8 &title) {
2047#ifdef DEBUG_CPU_USAGE
2048 // get current thread's delta CPU time in wall clock ns
2049 double wcNs;
2050 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2051
2052 // record sample for wall clock statistics
2053 if (valid) {
2054 mWcStats.sample(wcNs);
2055 }
2056
2057 // get the current CPU number
2058 int cpuNum = sched_getcpu();
2059
2060 // get the current CPU frequency in kHz
2061 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2062
2063 // check if either CPU number or frequency changed
2064 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2065 mCpuNum = cpuNum;
2066 mCpukHz = cpukHz;
2067 // ignore sample for purposes of cycles
2068 valid = false;
2069 }
2070
2071 // if no change in CPU number or frequency, then record sample for cycle statistics
2072 if (valid && mCpukHz > 0) {
2073 double cycles = wcNs * cpukHz * 0.000001;
2074 mHzStats.sample(cycles);
2075 }
2076
2077 unsigned n = mWcStats.n();
2078 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002079 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002080 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002081 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2082 double perLoop = elapsed / (double) n;
2083 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002084 double perLoop1k = perLoop * 0.001;
2085 double mean = mWcStats.mean();
2086 double stddev = mWcStats.stddev();
2087 double minimum = mWcStats.minimum();
2088 double maximum = mWcStats.maximum();
2089 double meanCycles = mHzStats.mean();
2090 double stddevCycles = mHzStats.stddev();
2091 double minCycles = mHzStats.minimum();
2092 double maxCycles = mHzStats.maximum();
2093 mCpuUsage.resetElapsed();
2094 mWcStats.reset();
2095 mHzStats.reset();
2096 ALOGD("CPU usage for %s over past %.1f secs\n"
2097 " (%u mixer loops at %.1f mean ms per loop):\n"
2098 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2099 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2100 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2101 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002102 elapsed * .000000001, n, perLoop * .000001,
2103 mean * .001,
2104 stddev * .001,
2105 minimum * .001,
2106 maximum * .001,
2107 mean / perLoop100,
2108 stddev / perLoop100,
2109 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002110 maximum / perLoop100,
2111 meanCycles / perLoop1k,
2112 stddevCycles / perLoop1k,
2113 minCycles / perLoop1k,
2114 maxCycles / perLoop1k);
2115
Glenn Kasten83efdd02012-02-24 07:21:32 -08002116 }
2117 }
2118#endif
2119};
2120
Glenn Kasten37d825e2012-02-24 07:21:48 -08002121void AudioFlinger::PlaybackThread::checkSilentMode_l()
2122{
2123 if (!mMasterMute) {
2124 char value[PROPERTY_VALUE_MAX];
2125 if (property_get("ro.audio.silent", value, "0") > 0) {
2126 char *endptr;
2127 unsigned long ul = strtoul(value, &endptr, 0);
2128 if (*endptr == '\0' && ul != 0) {
2129 ALOGD("Silence is golden");
2130 // The setprop command will not allow a property to be changed after
2131 // the first time it is set, so we don't have to worry about un-muting.
2132 setMasterMute_l(true);
2133 }
2134 }
2135 }
2136}
2137
Glenn Kasten000f0e32012-03-01 17:10:56 -08002138bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002139{
2140 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002141
Glenn Kasten000f0e32012-03-01 17:10:56 -08002142 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002143
2144 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002145 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002146if (mType == MIXER) {
2147 longStandbyExit = false;
2148}
Glenn Kasten688a6402012-02-29 07:57:06 -08002149
Glenn Kasten000f0e32012-03-01 17:10:56 -08002150 // DUPLICATING
2151 // FIXME could this be made local to while loop?
2152 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002153
Glenn Kasten66fcab92012-02-24 14:59:21 -08002154 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002155 sleepTime = idleSleepTime;
2156
2157if (mType == MIXER) {
2158 sleepTimeShift = 0;
2159}
2160
Glenn Kasten83efdd02012-02-24 07:21:32 -08002161 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002162 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002163
Eric Laurentfeb0db62011-07-22 09:04:31 -07002164 acquireWakeLock();
2165
Mathias Agopian65ab4712010-07-14 17:59:35 -07002166 while (!exitPending())
2167 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002168 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002169
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002170 Vector< sp<EffectChain> > effectChains;
2171
Mathias Agopian65ab4712010-07-14 17:59:35 -07002172 processConfigEvents();
2173
Mathias Agopian65ab4712010-07-14 17:59:35 -07002174 { // scope for mLock
2175
2176 Mutex::Autolock _l(mLock);
2177
2178 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002179 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002180 }
2181
Glenn Kastenfa26a852012-03-06 11:28:04 -08002182 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002183
Mathias Agopian65ab4712010-07-14 17:59:35 -07002184 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002185 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002186 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002187 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002188
2189 threadLoop_standby();
2190
Mathias Agopian65ab4712010-07-14 17:59:35 -07002191 mStandby = true;
2192 mBytesWritten = 0;
2193 }
2194
Glenn Kasten3e074702012-02-28 18:40:35 -08002195 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002196 // we're about to wait, flush the binder command buffer
2197 IPCThreadState::self()->flushCommands();
2198
Glenn Kastenfa26a852012-03-06 11:28:04 -08002199 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002200
Mathias Agopian65ab4712010-07-14 17:59:35 -07002201 if (exitPending()) break;
2202
Eric Laurentfeb0db62011-07-22 09:04:31 -07002203 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002204 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002205 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002206 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002207 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002208 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002209
Eric Laurent27741442012-01-17 19:20:12 -08002210 mPrevMixerStatus = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002211
Glenn Kasten37d825e2012-02-24 07:21:48 -08002212 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002213
Glenn Kasten000f0e32012-03-01 17:10:56 -08002214 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002215 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002216 if (mType == MIXER) {
2217 sleepTimeShift = 0;
2218 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002219
Mathias Agopian65ab4712010-07-14 17:59:35 -07002220 continue;
2221 }
2222 }
2223
Glenn Kastenfec279f2012-03-08 07:47:15 -08002224 mixer_state newMixerStatus = prepareTracks_l(&tracksToRemove);
2225 // Shift in the new status; this could be a queue if it's
2226 // useful to filter the mixer status over several cycles.
2227 mPrevMixerStatus = mMixerStatus;
2228 mMixerStatus = newMixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002229
2230 // prevent any changes in effect chain list and in each effect chain
2231 // during mixing and effect process as the audio buffers could be deleted
2232 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002233 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002234 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002235
Glenn Kastenfec279f2012-03-08 07:47:15 -08002236 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002237 threadLoop_mix();
2238 } else {
2239 threadLoop_sleepTime();
2240 }
2241
2242 if (mSuspended > 0) {
2243 sleepTime = suspendSleepTimeUs();
2244 }
2245
2246 // only process effects if we're going to write
2247 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002248 for (size_t i = 0; i < effectChains.size(); i ++) {
2249 effectChains[i]->process_l();
2250 }
2251 }
2252
2253 // enable changes in effect chain
2254 unlockEffectChains(effectChains);
2255
2256 // sleepTime == 0 means we must write to audio hardware
2257 if (sleepTime == 0) {
2258
2259 threadLoop_write();
2260
2261if (mType == MIXER) {
2262 // write blocked detection
2263 nsecs_t now = systemTime();
2264 nsecs_t delta = now - mLastWriteTime;
2265 if (!mStandby && delta > maxPeriod) {
2266 mNumDelayedWrites++;
2267 if ((now - lastWarning) > kWarningThrottleNs) {
2268 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2269 ns2ms(delta), mNumDelayedWrites, this);
2270 lastWarning = now;
2271 }
2272 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2273 // a different threshold. Or completely removed for what it is worth anyway...
2274 if (mStandby) {
2275 longStandbyExit = true;
2276 }
2277 }
2278}
2279
2280 mStandby = false;
2281 } else {
2282 usleep(sleepTime);
2283 }
2284
2285 // finally let go of removed track(s), without the lock held
2286 // since we can't guarantee the destructors won't acquire that
2287 // same lock.
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002288 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002289
Glenn Kastenfa26a852012-03-06 11:28:04 -08002290 // FIXME I don't understand the need for this here;
2291 // it was in the original code but maybe the
2292 // assignment in saveOutputTracks() makes this unnecessary?
2293 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002294
2295 // Effect chains will be actually deleted here if they were removed from
2296 // mEffectChains list during mixing or effects processing
2297 effectChains.clear();
2298
2299 // FIXME Note that the above .clear() is no longer necessary since effectChains
2300 // is now local to this block, but will keep it for now (at least until merge done).
2301 }
2302
2303if (mType == MIXER || mType == DIRECT) {
2304 // put output stream into standby mode
2305 if (!mStandby) {
2306 mOutput->stream->common.standby(&mOutput->stream->common);
2307 }
2308}
2309if (mType == DUPLICATING) {
2310 // for DuplicatingThread, standby mode is handled by the outputTracks
2311}
2312
2313 releaseWakeLock();
2314
2315 ALOGV("Thread %p type %d exiting", this, mType);
2316 return false;
2317}
2318
2319// shared by MIXER and DIRECT, overridden by DUPLICATING
2320void AudioFlinger::PlaybackThread::threadLoop_write()
2321{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002322 // FIXME rewrite to reduce number of system calls
2323 mLastWriteTime = systemTime();
2324 mInWrite = true;
2325 mBytesWritten += mixBufferSize;
2326 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2327 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2328 mNumWrites++;
2329 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002330}
2331
2332// shared by MIXER and DIRECT, overridden by DUPLICATING
2333void AudioFlinger::PlaybackThread::threadLoop_standby()
2334{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002335 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2336 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002337}
2338
2339void AudioFlinger::MixerThread::threadLoop_mix()
2340{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002341 // obtain the presentation timestamp of the next output buffer
2342 int64_t pts;
2343 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002344
Glenn Kasten952eeb22012-03-06 11:30:57 -08002345 if (NULL != mOutput->stream->get_next_write_timestamp) {
2346 status = mOutput->stream->get_next_write_timestamp(
2347 mOutput->stream, &pts);
2348 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002349
Glenn Kasten952eeb22012-03-06 11:30:57 -08002350 if (status != NO_ERROR) {
2351 pts = AudioBufferProvider::kInvalidPTS;
2352 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002353
Glenn Kasten952eeb22012-03-06 11:30:57 -08002354 // mix buffers...
2355 mAudioMixer->process(pts);
2356 // increase sleep time progressively when application underrun condition clears.
2357 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2358 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2359 // such that we would underrun the audio HAL.
2360 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2361 sleepTimeShift--;
2362 }
2363 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002364 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002365 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002366}
2367
2368void AudioFlinger::MixerThread::threadLoop_sleepTime()
2369{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002370 // If no tracks are ready, sleep once for the duration of an output
2371 // buffer size, then write 0s to the output
2372 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002373 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002374 sleepTime = activeSleepTime >> sleepTimeShift;
2375 if (sleepTime < kMinThreadSleepTimeUs) {
2376 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002377 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002378 // reduce sleep time in case of consecutive application underruns to avoid
2379 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2380 // duration we would end up writing less data than needed by the audio HAL if
2381 // the condition persists.
2382 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2383 sleepTimeShift++;
2384 }
2385 } else {
2386 sleepTime = idleSleepTime;
2387 }
2388 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002389 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002390 memset (mMixBuffer, 0, mixBufferSize);
2391 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002392 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002393 }
2394 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002395}
2396
2397// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002398AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002399 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002400{
2401
Glenn Kasten29c23c32012-01-26 13:37:52 -08002402 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002403 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002404 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002405 size_t mixedTracks = 0;
2406 size_t tracksWithEffect = 0;
2407
2408 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002409 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002410
Eric Laurent571d49c2010-08-11 05:20:11 -07002411 if (masterMute) {
2412 masterVolume = 0;
2413 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002414 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002415 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002416 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002417 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002418 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002419 masterVolume = (float)((v + (1 << 23)) >> 24);
2420 chain.clear();
2421 }
2422
2423 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002424 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002425 if (t == 0) continue;
2426
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002427 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002428 Track* const track = t.get();
2429 audio_track_cblk_t* cblk = track->cblk();
2430
2431 // The first time a track is added we wait
2432 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002433 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002434 // make sure that we have enough frames to mix one full buffer.
2435 // enforce this condition only once to enable draining the buffer in case the client
2436 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002437 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002438 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002439 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002440 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002441 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002442 if (t->sampleRate() == (int)mSampleRate) {
2443 minFrames = mFrameCount;
2444 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002445 // +1 for rounding and +1 for additional sample needed for interpolation
2446 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2447 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07002448 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08002449 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2450 // the minimum track buffer size is normally twice the number of frames necessary
2451 // to fill one buffer and the resampler should not leave more than one buffer worth
2452 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002453 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002454 }
2455 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002456 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002457 !track->isPaused() && !track->isTerminated())
2458 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002459 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002460
2461 mixedTracks++;
2462
2463 // track->mainBuffer() != mMixBuffer means there is an effect chain
2464 // connected to the track
2465 chain.clear();
2466 if (track->mainBuffer() != mMixBuffer) {
2467 chain = getEffectChain_l(track->sessionId());
2468 // Delegate volume control to effect in track effect chain if needed
2469 if (chain != 0) {
2470 tracksWithEffect++;
2471 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002472 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002473 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002474 }
2475 }
2476
2477
2478 int param = AudioMixer::VOLUME;
2479 if (track->mFillingUpStatus == Track::FS_FILLED) {
2480 // no ramp for the first volume setting
2481 track->mFillingUpStatus = Track::FS_ACTIVE;
2482 if (track->mState == TrackBase::RESUMING) {
2483 track->mState = TrackBase::ACTIVE;
2484 param = AudioMixer::RAMP_VOLUME;
2485 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002486 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002487 } else if (cblk->server != 0) {
2488 // If the track is stopped before the first frame was mixed,
2489 // do not apply ramp
2490 param = AudioMixer::RAMP_VOLUME;
2491 }
2492
2493 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002494 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002495 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002496 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002497 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002498 if (track->isPausing()) {
2499 track->setPaused();
2500 }
2501 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002502
Mathias Agopian65ab4712010-07-14 17:59:35 -07002503 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002504 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002505 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002506 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002507 vl = vlr & 0xFFFF;
2508 vr = vlr >> 16;
2509 // track volumes come from shared memory, so can't be trusted and must be clamped
2510 if (vl > MAX_GAIN_INT) {
2511 ALOGV("Track left volume out of range: %04X", vl);
2512 vl = MAX_GAIN_INT;
2513 }
2514 if (vr > MAX_GAIN_INT) {
2515 ALOGV("Track right volume out of range: %04X", vr);
2516 vr = MAX_GAIN_INT;
2517 }
2518 // now apply the master volume and stream type volume
2519 vl = (uint32_t)(v * vl) << 12;
2520 vr = (uint32_t)(v * vr) << 12;
2521 // assuming master volume and stream type volume each go up to 1.0,
2522 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002523
Glenn Kasten05632a52012-01-03 14:22:33 -08002524 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2525 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002526 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002527 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002528 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002529 }
2530 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002531 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002532 // Delegate volume control to effect in track effect chain if needed
2533 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2534 // Do not ramp volume if volume is controlled by effect
2535 param = AudioMixer::VOLUME;
2536 track->mHasVolumeController = true;
2537 } else {
2538 // force no volume ramp when volume controller was just disabled or removed
2539 // from effect chain to avoid volume spike
2540 if (track->mHasVolumeController) {
2541 param = AudioMixer::VOLUME;
2542 }
2543 track->mHasVolumeController = false;
2544 }
2545
2546 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002547 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002548 vl = (vl + (1 << 11)) >> 12;
2549 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2550 vr = (vr + (1 << 11)) >> 12;
2551 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002552
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002553 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 -07002554
Mathias Agopian65ab4712010-07-14 17:59:35 -07002555 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002556 mAudioMixer->setBufferProvider(name, track);
2557 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002558
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002559 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2560 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2561 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002562 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002563 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002564 AudioMixer::TRACK,
2565 AudioMixer::FORMAT, (void *)track->format());
2566 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002567 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002568 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002569 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002570 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002571 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002572 AudioMixer::RESAMPLE,
2573 AudioMixer::SAMPLE_RATE,
2574 (void *)(cblk->sampleRate));
2575 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002576 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002577 AudioMixer::TRACK,
2578 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2579 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002580 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002581 AudioMixer::TRACK,
2582 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2583
2584 // reset retry count
2585 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002586
Eric Laurent27741442012-01-17 19:20:12 -08002587 // If one track is ready, set the mixer ready if:
2588 // - the mixer was not ready during previous round OR
2589 // - no other track is not ready
2590 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2591 mixerStatus != MIXER_TRACKS_ENABLED) {
2592 mixerStatus = MIXER_TRACKS_READY;
2593 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002594 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002595 //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 -07002596 if (track->isStopped()) {
2597 track->reset();
2598 }
2599 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2600 // We have consumed all the buffers of this track.
2601 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07002602 // TODO: use actual buffer filling status instead of latency when available from
2603 // audio HAL
2604 size_t audioHALFrames =
2605 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2606 size_t framesWritten =
2607 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2608 if (track->presentationComplete(framesWritten, audioHALFrames)) {
2609 tracksToRemove->add(track);
2610 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002611 } else {
2612 // No buffers for this track. Give it a few chances to
2613 // fill a buffer, then remove it from active list.
2614 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002615 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002616 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002617 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002618 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002619 // If one track is not ready, mark the mixer also not ready if:
2620 // - the mixer was ready during previous round OR
2621 // - no other track is ready
2622 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2623 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002624 mixerStatus = MIXER_TRACKS_ENABLED;
2625 }
2626 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002627 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002628 }
2629 }
2630
2631 // remove all the tracks that need to be...
2632 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002633 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002634 for (size_t i=0 ; i<count ; i++) {
2635 const sp<Track>& track = tracksToRemove->itemAt(i);
2636 mActiveTracks.remove(track);
2637 if (track->mainBuffer() != mMixBuffer) {
2638 chain = getEffectChain_l(track->sessionId());
2639 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002640 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002641 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002642 }
2643 }
2644 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002645 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002646 }
2647 }
2648 }
2649
2650 // mix buffer must be cleared if all tracks are connected to an
2651 // effect chain as in this case the mixer will not write to
2652 // mix buffer and track effects will accumulate into it
2653 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2654 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2655 }
2656
2657 return mixerStatus;
2658}
2659
Glenn Kasten66fcab92012-02-24 14:59:21 -08002660/*
2661The derived values that are cached:
2662 - mixBufferSize from frame count * frame size
2663 - activeSleepTime from activeSleepTimeUs()
2664 - idleSleepTime from idleSleepTimeUs()
2665 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2666 - maxPeriod from frame count and sample rate (MIXER only)
2667
2668The parameters that affect these derived values are:
2669 - frame count
2670 - frame size
2671 - sample rate
2672 - device type: A2DP or not
2673 - device latency
2674 - format: PCM or not
2675 - active sleep time
2676 - idle sleep time
2677*/
2678
2679void AudioFlinger::PlaybackThread::cacheParameters_l()
2680{
2681 mixBufferSize = mFrameCount * mFrameSize;
2682 activeSleepTime = activeSleepTimeUs();
2683 idleSleepTime = idleSleepTimeUs();
2684}
2685
Glenn Kastenfff6d712012-01-12 16:38:12 -08002686void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002687{
Steve Block3856b092011-10-20 11:56:00 +01002688 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002689 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002690 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002691
Mathias Agopian65ab4712010-07-14 17:59:35 -07002692 size_t size = mTracks.size();
2693 for (size_t i = 0; i < size; i++) {
2694 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08002695 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002696 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002697 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002698 }
2699 }
2700}
2701
Mathias Agopian65ab4712010-07-14 17:59:35 -07002702// getTrackName_l() must be called with ThreadBase::mLock held
2703int AudioFlinger::MixerThread::getTrackName_l()
2704{
2705 return mAudioMixer->getTrackName();
2706}
2707
2708// deleteTrackName_l() must be called with ThreadBase::mLock held
2709void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2710{
Steve Block3856b092011-10-20 11:56:00 +01002711 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002712 mAudioMixer->deleteTrackName(name);
2713}
2714
2715// checkForNewParameters_l() must be called with ThreadBase::mLock held
2716bool AudioFlinger::MixerThread::checkForNewParameters_l()
2717{
2718 bool reconfig = false;
2719
2720 while (!mNewParameters.isEmpty()) {
2721 status_t status = NO_ERROR;
2722 String8 keyValuePair = mNewParameters[0];
2723 AudioParameter param = AudioParameter(keyValuePair);
2724 int value;
2725
2726 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2727 reconfig = true;
2728 }
2729 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002730 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002731 status = BAD_VALUE;
2732 } else {
2733 reconfig = true;
2734 }
2735 }
2736 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002737 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002738 status = BAD_VALUE;
2739 } else {
2740 reconfig = true;
2741 }
2742 }
2743 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2744 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002745 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002746 // if frame count is changed after track creation
2747 if (!mTracks.isEmpty()) {
2748 status = INVALID_OPERATION;
2749 } else {
2750 reconfig = true;
2751 }
2752 }
2753 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07002754#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08002755 // when changing the audio output device, call addBatteryData to notify
2756 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002757 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002758 uint32_t params = 0;
2759 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002760 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002761 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2762 }
2763
2764 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002765 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002766 // check if any other device (except speaker) is on
2767 if (value & deviceWithoutSpeaker ) {
2768 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2769 }
2770
2771 if (params != 0) {
2772 addBatteryData(params);
2773 }
2774 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07002775#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08002776
Mathias Agopian65ab4712010-07-14 17:59:35 -07002777 // forward device change to effects that have requested to be
2778 // aware of attached audio device.
2779 mDevice = (uint32_t)value;
2780 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002781 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002782 }
2783 }
2784
2785 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002786 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002787 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002788 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002789 mOutput->stream->common.standby(&mOutput->stream->common);
2790 mStandby = true;
2791 mBytesWritten = 0;
2792 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002793 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002794 }
2795 if (status == NO_ERROR && reconfig) {
2796 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002797 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2798 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002799 readOutputParameters();
2800 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2801 for (size_t i = 0; i < mTracks.size() ; i++) {
2802 int name = getTrackName_l();
2803 if (name < 0) break;
2804 mTracks[i]->mName = name;
2805 // limit track sample rate to 2 x new output sample rate
2806 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2807 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2808 }
2809 }
2810 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2811 }
2812 }
2813
2814 mNewParameters.removeAt(0);
2815
2816 mParamStatus = status;
2817 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002818 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2819 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002820 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002821 }
2822 return reconfig;
2823}
2824
2825status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2826{
2827 const size_t SIZE = 256;
2828 char buffer[SIZE];
2829 String8 result;
2830
2831 PlaybackThread::dumpInternals(fd, args);
2832
2833 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2834 result.append(buffer);
2835 write(fd, result.string(), result.size());
2836 return NO_ERROR;
2837}
2838
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002839uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002840{
Eric Laurent60e18242010-07-29 06:50:24 -07002841 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002842}
2843
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002844uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002845{
2846 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2847}
2848
Glenn Kasten66fcab92012-02-24 14:59:21 -08002849void AudioFlinger::MixerThread::cacheParameters_l()
2850{
2851 PlaybackThread::cacheParameters_l();
2852
2853 // FIXME: Relaxed timing because of a certain device that can't meet latency
2854 // Should be reduced to 2x after the vendor fixes the driver issue
2855 // increase threshold again due to low power audio mode. The way this warning
2856 // threshold is calculated and its usefulness should be reconsidered anyway.
2857 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
2858}
2859
Mathias Agopian65ab4712010-07-14 17:59:35 -07002860// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002861AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2862 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002863 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002864 // mLeftVolFloat, mRightVolFloat
2865 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002866{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002867}
2868
2869AudioFlinger::DirectOutputThread::~DirectOutputThread()
2870{
2871}
2872
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002873AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
2874 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08002875)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002876{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002877 sp<Track> trackToRemove;
2878
Glenn Kastenfec279f2012-03-08 07:47:15 -08002879 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002880
Glenn Kasten952eeb22012-03-06 11:30:57 -08002881 // find out which tracks need to be processed
2882 if (mActiveTracks.size() != 0) {
2883 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08002884 // The track died recently
2885 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002886
Glenn Kasten952eeb22012-03-06 11:30:57 -08002887 Track* const track = t.get();
2888 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002889
Glenn Kasten952eeb22012-03-06 11:30:57 -08002890 // The first time a track is added we wait
2891 // for all its buffers to be filled before processing it
2892 if (cblk->framesReady() && track->isReady() &&
2893 !track->isPaused() && !track->isTerminated())
2894 {
2895 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002896
Glenn Kasten952eeb22012-03-06 11:30:57 -08002897 if (track->mFillingUpStatus == Track::FS_FILLED) {
2898 track->mFillingUpStatus = Track::FS_ACTIVE;
2899 mLeftVolFloat = mRightVolFloat = 0;
2900 mLeftVolShort = mRightVolShort = 0;
2901 if (track->mState == TrackBase::RESUMING) {
2902 track->mState = TrackBase::ACTIVE;
2903 rampVolume = true;
2904 }
2905 } else if (cblk->server != 0) {
2906 // If the track is stopped before the first frame was mixed,
2907 // do not apply ramp
2908 rampVolume = true;
2909 }
2910 // compute volume for this track
2911 float left, right;
2912 if (track->isMuted() || mMasterMute || track->isPausing() ||
2913 mStreamTypes[track->streamType()].mute) {
2914 left = right = 0;
2915 if (track->isPausing()) {
2916 track->setPaused();
2917 }
2918 } else {
2919 float typeVolume = mStreamTypes[track->streamType()].volume;
2920 float v = mMasterVolume * typeVolume;
2921 uint32_t vlr = cblk->getVolumeLR();
2922 float v_clamped = v * (vlr & 0xFFFF);
2923 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2924 left = v_clamped/MAX_GAIN;
2925 v_clamped = v * (vlr >> 16);
2926 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2927 right = v_clamped/MAX_GAIN;
2928 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002929
Glenn Kasten952eeb22012-03-06 11:30:57 -08002930 if (left != mLeftVolFloat || right != mRightVolFloat) {
2931 mLeftVolFloat = left;
2932 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002933
Glenn Kasten952eeb22012-03-06 11:30:57 -08002934 // If audio HAL implements volume control,
2935 // force software volume to nominal value
2936 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
2937 left = 1.0f;
2938 right = 1.0f;
2939 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002940
Glenn Kasten952eeb22012-03-06 11:30:57 -08002941 // Convert volumes from float to 8.24
2942 uint32_t vl = (uint32_t)(left * (1 << 24));
2943 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002944
Glenn Kasten952eeb22012-03-06 11:30:57 -08002945 // Delegate volume control to effect in track effect chain if needed
2946 // only one effect chain can be present on DirectOutputThread, so if
2947 // there is one, the track is connected to it
2948 if (!mEffectChains.isEmpty()) {
2949 // Do not ramp volume if volume is controlled by effect
2950 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002951 rampVolume = false;
2952 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002953 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002954
Glenn Kasten952eeb22012-03-06 11:30:57 -08002955 // Convert volumes from 8.24 to 4.12 format
2956 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2957 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2958 leftVol = (uint16_t)v_clamped;
2959 v_clamped = (vr + (1 << 11)) >> 12;
2960 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2961 rightVol = (uint16_t)v_clamped;
2962 } else {
2963 leftVol = mLeftVolShort;
2964 rightVol = mRightVolShort;
2965 rampVolume = false;
2966 }
2967
2968 // reset retry count
2969 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002970 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002971 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002972 } else {
2973 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2974 if (track->isStopped()) {
2975 track->reset();
2976 }
2977 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2978 // We have consumed all the buffers of this track.
2979 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07002980 // TODO: implement behavior for compressed audio
2981 size_t audioHALFrames =
2982 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2983 size_t framesWritten =
2984 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2985 if (track->presentationComplete(framesWritten, audioHALFrames)) {
2986 trackToRemove = track;
2987 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002988 } else {
2989 // No buffers for this track. Give it a few chances to
2990 // fill a buffer, then remove it from active list.
2991 if (--(track->mRetryCount) <= 0) {
2992 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2993 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002994 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002995 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002996 }
2997 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002998 }
2999 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003000
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003001 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003002 // remove all the tracks that need to be...
3003 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003004 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003005 mActiveTracks.remove(trackToRemove);
3006 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003007 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003008 trackToRemove->sessionId());
3009 mEffectChains[0]->decActiveTrackCnt();
3010 }
3011 if (trackToRemove->isTerminated()) {
3012 removeTrack_l(trackToRemove);
3013 }
3014 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003015
Glenn Kastenfec279f2012-03-08 07:47:15 -08003016 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003017}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003018
Glenn Kasten000f0e32012-03-01 17:10:56 -08003019void AudioFlinger::DirectOutputThread::threadLoop_mix()
3020{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003021 AudioBufferProvider::Buffer buffer;
3022 size_t frameCount = mFrameCount;
3023 int8_t *curBuf = (int8_t *)mMixBuffer;
3024 // output audio to hardware
3025 while (frameCount) {
3026 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003027 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003028 if (CC_UNLIKELY(buffer.raw == NULL)) {
3029 memset(curBuf, 0, frameCount * mFrameSize);
3030 break;
3031 }
3032 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3033 frameCount -= buffer.frameCount;
3034 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003035 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003036 }
3037 sleepTime = 0;
3038 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003039 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003040
3041 // apply volume
3042
3043 // Do not apply volume on compressed audio
3044 if (!audio_is_linear_pcm(mFormat)) {
3045 return;
3046 }
3047
3048 // convert to signed 16 bit before volume calculation
3049 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3050 size_t count = mFrameCount * mChannelCount;
3051 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
3052 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003053 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003054 *dst-- = (int16_t)(*src--^0x80) << 8;
3055 }
3056 }
3057
3058 frameCount = mFrameCount;
3059 int16_t *out = mMixBuffer;
3060 if (rampVolume) {
3061 if (mChannelCount == 1) {
3062 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3063 int32_t vlInc = d / (int32_t)frameCount;
3064 int32_t vl = ((int32_t)mLeftVolShort << 16);
3065 do {
3066 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3067 out++;
3068 vl += vlInc;
3069 } while (--frameCount);
3070
3071 } else {
3072 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3073 int32_t vlInc = d / (int32_t)frameCount;
3074 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
3075 int32_t vrInc = d / (int32_t)frameCount;
3076 int32_t vl = ((int32_t)mLeftVolShort << 16);
3077 int32_t vr = ((int32_t)mRightVolShort << 16);
3078 do {
3079 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3080 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3081 out += 2;
3082 vl += vlInc;
3083 vr += vrInc;
3084 } while (--frameCount);
3085 }
3086 } else {
3087 if (mChannelCount == 1) {
3088 do {
3089 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3090 out++;
3091 } while (--frameCount);
3092 } else {
3093 do {
3094 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3095 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3096 out += 2;
3097 } while (--frameCount);
3098 }
3099 }
3100
3101 // convert back to unsigned 8 bit after volume calculation
3102 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3103 size_t count = mFrameCount * mChannelCount;
3104 int16_t *src = mMixBuffer;
3105 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003106 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003107 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3108 }
3109 }
3110
3111 mLeftVolShort = leftVol;
3112 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003113}
3114
3115void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3116{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003117 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003118 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003119 sleepTime = activeSleepTime;
3120 } else {
3121 sleepTime = idleSleepTime;
3122 }
3123 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3124 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
3125 sleepTime = 0;
3126 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003127}
3128
3129// getTrackName_l() must be called with ThreadBase::mLock held
3130int AudioFlinger::DirectOutputThread::getTrackName_l()
3131{
3132 return 0;
3133}
3134
3135// deleteTrackName_l() must be called with ThreadBase::mLock held
3136void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3137{
3138}
3139
3140// checkForNewParameters_l() must be called with ThreadBase::mLock held
3141bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3142{
3143 bool reconfig = false;
3144
3145 while (!mNewParameters.isEmpty()) {
3146 status_t status = NO_ERROR;
3147 String8 keyValuePair = mNewParameters[0];
3148 AudioParameter param = AudioParameter(keyValuePair);
3149 int value;
3150
3151 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3152 // do not accept frame count changes if tracks are open as the track buffer
3153 // size depends on frame count and correct behavior would not be garantied
3154 // if frame count is changed after track creation
3155 if (!mTracks.isEmpty()) {
3156 status = INVALID_OPERATION;
3157 } else {
3158 reconfig = true;
3159 }
3160 }
3161 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003162 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003163 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003164 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003165 mOutput->stream->common.standby(&mOutput->stream->common);
3166 mStandby = true;
3167 mBytesWritten = 0;
3168 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003169 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003170 }
3171 if (status == NO_ERROR && reconfig) {
3172 readOutputParameters();
3173 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3174 }
3175 }
3176
3177 mNewParameters.removeAt(0);
3178
3179 mParamStatus = status;
3180 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003181 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3182 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003183 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184 }
3185 return reconfig;
3186}
3187
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003188uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003189{
3190 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003191 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003192 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003193 } else {
3194 time = 10000;
3195 }
3196 return time;
3197}
3198
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003199uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003200{
3201 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003202 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003203 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003204 } else {
3205 time = 10000;
3206 }
3207 return time;
3208}
3209
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003210uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003211{
3212 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003213 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003214 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3215 } else {
3216 time = 10000;
3217 }
3218 return time;
3219}
3220
Glenn Kasten66fcab92012-02-24 14:59:21 -08003221void AudioFlinger::DirectOutputThread::cacheParameters_l()
3222{
3223 PlaybackThread::cacheParameters_l();
3224
3225 // use shorter standby delay as on normal output to release
3226 // hardware resources as soon as possible
3227 standbyDelay = microseconds(activeSleepTime*2);
3228}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003229
Mathias Agopian65ab4712010-07-14 17:59:35 -07003230// ----------------------------------------------------------------------------
3231
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003232AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003233 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003234 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3235 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003236{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003237 addOutputTrack(mainThread);
3238}
3239
3240AudioFlinger::DuplicatingThread::~DuplicatingThread()
3241{
3242 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3243 mOutputTracks[i]->destroy();
3244 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003245}
3246
Glenn Kasten000f0e32012-03-01 17:10:56 -08003247void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003248{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003249 // mix buffers...
3250 if (outputsReady(outputTracks)) {
3251 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3252 } else {
3253 memset(mMixBuffer, 0, mixBufferSize);
3254 }
3255 sleepTime = 0;
3256 writeFrames = mFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003257}
3258
3259void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3260{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003261 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003262 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003263 sleepTime = activeSleepTime;
3264 } else {
3265 sleepTime = idleSleepTime;
3266 }
3267 } else if (mBytesWritten != 0) {
3268 // flush remaining overflow buffers in output tracks
3269 for (size_t i = 0; i < outputTracks.size(); i++) {
3270 if (outputTracks[i]->isActive()) {
3271 sleepTime = 0;
3272 writeFrames = 0;
3273 memset(mMixBuffer, 0, mixBufferSize);
3274 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003275 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003276 }
3277 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003278}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003279
Glenn Kasten000f0e32012-03-01 17:10:56 -08003280void AudioFlinger::DuplicatingThread::threadLoop_write()
3281{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003282 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003283 for (size_t i = 0; i < outputTracks.size(); i++) {
3284 outputTracks[i]->write(mMixBuffer, writeFrames);
3285 }
3286 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003287}
Glenn Kasten688a6402012-02-29 07:57:06 -08003288
Glenn Kasten000f0e32012-03-01 17:10:56 -08003289void AudioFlinger::DuplicatingThread::threadLoop_standby()
3290{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003291 // DuplicatingThread implements standby by stopping all tracks
3292 for (size_t i = 0; i < outputTracks.size(); i++) {
3293 outputTracks[i]->stop();
3294 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003295}
3296
Glenn Kastenfa26a852012-03-06 11:28:04 -08003297void AudioFlinger::DuplicatingThread::saveOutputTracks()
3298{
3299 outputTracks = mOutputTracks;
3300}
3301
3302void AudioFlinger::DuplicatingThread::clearOutputTracks()
3303{
3304 outputTracks.clear();
3305}
3306
Mathias Agopian65ab4712010-07-14 17:59:35 -07003307void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3308{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003309 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003310 // FIXME explain this formula
Mathias Agopian65ab4712010-07-14 17:59:35 -07003311 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003312 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003313 this,
3314 mSampleRate,
3315 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003316 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003317 frameCount);
3318 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003319 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003320 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003321 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003322 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003323 }
3324}
3325
3326void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3327{
3328 Mutex::Autolock _l(mLock);
3329 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003330 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003331 mOutputTracks[i]->destroy();
3332 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003333 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003334 return;
3335 }
3336 }
Steve Block3856b092011-10-20 11:56:00 +01003337 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003338}
3339
Glenn Kasten438b0362012-03-06 11:24:48 -08003340// caller must hold mLock
3341void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003342{
3343 mWaitTimeMs = UINT_MAX;
3344 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3345 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003346 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003347 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3348 if (waitTimeMs < mWaitTimeMs) {
3349 mWaitTimeMs = waitTimeMs;
3350 }
3351 }
3352 }
3353}
3354
3355
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003356bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003357{
3358 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003359 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003360 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003361 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003362 return false;
3363 }
3364 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3365 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003366 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003367 return false;
3368 }
3369 }
3370 return true;
3371}
3372
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003373uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003374{
3375 return (mWaitTimeMs * 1000) / 2;
3376}
3377
Glenn Kasten66fcab92012-02-24 14:59:21 -08003378void AudioFlinger::DuplicatingThread::cacheParameters_l()
3379{
3380 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3381 updateWaitTime_l();
3382
3383 MixerThread::cacheParameters_l();
3384}
3385
Mathias Agopian65ab4712010-07-14 17:59:35 -07003386// ----------------------------------------------------------------------------
3387
3388// TrackBase constructor must be called with AudioFlinger::mLock held
3389AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003390 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003391 const sp<Client>& client,
3392 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003393 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003394 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003395 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003396 const sp<IMemory>& sharedBuffer,
3397 int sessionId)
3398 : RefBase(),
3399 mThread(thread),
3400 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003401 mCblk(NULL),
3402 // mBuffer
3403 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003404 mFrameCount(0),
3405 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003406 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003407 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003408 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003409 // mChannelCount
3410 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003411{
Steve Block3856b092011-10-20 11:56:00 +01003412 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003413
Steve Blockb8a80522011-12-20 16:23:08 +00003414 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003415 size_t size = sizeof(audio_track_cblk_t);
3416 uint8_t channelCount = popcount(channelMask);
3417 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3418 if (sharedBuffer == 0) {
3419 size += bufferSize;
3420 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003421
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003422 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003423 mCblkMemory = client->heap()->allocate(size);
3424 if (mCblkMemory != 0) {
3425 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003426 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003427 new(mCblk) audio_track_cblk_t();
3428 // clear all buffers
3429 mCblk->frameCount = frameCount;
3430 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003431// uncomment the following lines to quickly test 32-bit wraparound
3432// mCblk->user = 0xffff0000;
3433// mCblk->server = 0xffff0000;
3434// mCblk->userBase = 0xffff0000;
3435// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003436 mChannelCount = channelCount;
3437 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003438 if (sharedBuffer == 0) {
3439 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3440 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3441 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003442 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003443 mCblk->flags = CBLK_UNDERRUN_ON;
3444 } else {
3445 mBuffer = sharedBuffer->pointer();
3446 }
3447 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3448 }
3449 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003450 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003451 client->heap()->dump("AudioTrack");
3452 return;
3453 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003454 } else {
3455 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07003456 // construct the shared structure in-place.
3457 new(mCblk) audio_track_cblk_t();
3458 // clear all buffers
3459 mCblk->frameCount = frameCount;
3460 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003461// uncomment the following lines to quickly test 32-bit wraparound
3462// mCblk->user = 0xffff0000;
3463// mCblk->server = 0xffff0000;
3464// mCblk->userBase = 0xffff0000;
3465// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003466 mChannelCount = channelCount;
3467 mChannelMask = channelMask;
3468 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3469 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3470 // Force underrun condition to avoid false underrun callback until first data is
3471 // written to buffer (other flags are cleared)
3472 mCblk->flags = CBLK_UNDERRUN_ON;
3473 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003474 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003475}
3476
3477AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3478{
Glenn Kastena0d68332012-01-27 16:47:15 -08003479 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003480 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003481 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003482 } else {
3483 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003484 }
3485 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003486 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003487 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003488 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003489 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003490 // If the client's reference count drops to zero, the associated destructor
3491 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3492 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003493 mClient.clear();
3494 }
3495}
3496
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003497// AudioBufferProvider interface
3498// getNextBuffer() = 0;
3499// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07003500void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3501{
Glenn Kastene0feee32011-12-13 11:53:26 -08003502 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003503 mFrameCount = buffer->frameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003504 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003505 buffer->frameCount = 0;
3506}
3507
3508bool AudioFlinger::ThreadBase::TrackBase::step() {
3509 bool result;
3510 audio_track_cblk_t* cblk = this->cblk();
3511
3512 result = cblk->stepServer(mFrameCount);
3513 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003514 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003515 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003516 }
3517 return result;
3518}
3519
3520void AudioFlinger::ThreadBase::TrackBase::reset() {
3521 audio_track_cblk_t* cblk = this->cblk();
3522
3523 cblk->user = 0;
3524 cblk->server = 0;
3525 cblk->userBase = 0;
3526 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003527 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01003528 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003529}
3530
Mathias Agopian65ab4712010-07-14 17:59:35 -07003531int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3532 return (int)mCblk->sampleRate;
3533}
3534
Mathias Agopian65ab4712010-07-14 17:59:35 -07003535void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3536 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003537 size_t frameSize = cblk->frameSize;
3538 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3539 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003540
3541 // Check validity of returned pointer in case the track control block would have been corrupted.
3542 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003543 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003544 ALOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Marco Nelissena1472d92012-03-30 14:36:54 -07003545 server %u, serverBase %u, user %u, userBase %u",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003546 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003547 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003548 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003549 }
3550
3551 return bufferStart;
3552}
3553
Eric Laurenta011e352012-03-29 15:51:43 -07003554status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
3555{
3556 mSyncEvents.add(event);
3557 return NO_ERROR;
3558}
3559
Mathias Agopian65ab4712010-07-14 17:59:35 -07003560// ----------------------------------------------------------------------------
3561
3562// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3563AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003564 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003565 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003566 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003567 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003568 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003569 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003570 int frameCount,
3571 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07003572 int sessionId,
3573 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003574 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07003575 mMute(false),
3576 // mFillingUpStatus ?
3577 // mRetryCount initialized later when needed
3578 mSharedBuffer(sharedBuffer),
3579 mStreamType(streamType),
3580 mName(-1), // see note below
3581 mMainBuffer(thread->mixBuffer()),
3582 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07003583 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07003584 mPresentationCompleteFrames(0),
3585 mFlags(flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003586{
3587 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003588 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3589 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003590 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kastenf9959012012-03-19 11:14:37 -07003591 // to avoid leaking a track name, do not allocate one unless there is an mCblk
3592 mName = thread->getTrackName_l();
3593 if (mName < 0) {
3594 ALOGE("no more track names available");
3595 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003596 }
Glenn Kastenf9959012012-03-19 11:14:37 -07003597 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003598}
3599
3600AudioFlinger::PlaybackThread::Track::~Track()
3601{
Steve Block3856b092011-10-20 11:56:00 +01003602 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003603 sp<ThreadBase> thread = mThread.promote();
3604 if (thread != 0) {
3605 Mutex::Autolock _l(thread->mLock);
3606 mState = TERMINATED;
3607 }
3608}
3609
3610void AudioFlinger::PlaybackThread::Track::destroy()
3611{
3612 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3613 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08003614 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003615 // we must acquire a strong reference on this Track before locking mLock
3616 // here so that the destructor is called only when exiting this function.
3617 // On the other hand, as long as Track::destroy() is only called by
3618 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3619 // this Track with its member mTrack.
3620 sp<Track> keep(this);
3621 { // scope for mLock
3622 sp<ThreadBase> thread = mThread.promote();
3623 if (thread != 0) {
3624 if (!isOutputTrack()) {
3625 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08003626 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003627
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003628#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003629 // to track the speaker usage
3630 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003631#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003632 }
3633 AudioSystem::releaseOutput(thread->id());
3634 }
3635 Mutex::Autolock _l(thread->mLock);
3636 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3637 playbackThread->destroyTrack_l(this);
3638 }
3639 }
3640}
3641
3642void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3643{
Glenn Kasten83d86532012-01-17 14:39:34 -08003644 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003645 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 -07003646 mName - AudioMixer::TRACK0,
Glenn Kasten44deb052012-02-05 18:09:08 -08003647 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003648 mStreamType,
3649 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003650 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003651 mSessionId,
3652 mFrameCount,
3653 mState,
3654 mMute,
3655 mFillingUpStatus,
3656 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003657 vlr & 0xFFFF,
3658 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003659 mCblk->server,
3660 mCblk->user,
3661 (int)mMainBuffer,
3662 (int)mAuxBuffer);
3663}
3664
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003665// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08003666status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003667 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003668{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003669 audio_track_cblk_t* cblk = this->cblk();
3670 uint32_t framesReady;
3671 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003672
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003673 // Check if last stepServer failed, try to step now
3674 if (mStepServerFailed) {
3675 if (!step()) goto getNextBuffer_exit;
3676 ALOGV("stepServer recovered");
3677 mStepServerFailed = false;
3678 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003679
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003680 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003681
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003682 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003683 uint32_t s = cblk->server;
3684 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3685
3686 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3687 if (framesReq > framesReady) {
3688 framesReq = framesReady;
3689 }
Marco Nelissena1472d92012-03-30 14:36:54 -07003690 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003691 framesReq = bufferEnd - s;
3692 }
3693
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003694 buffer->raw = getBuffer(s, framesReq);
3695 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003696
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003697 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003698 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003699 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003700
3701getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003702 buffer->raw = NULL;
3703 buffer->frameCount = 0;
3704 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3705 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003706}
3707
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003708uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08003709 return mCblk->framesReady();
3710}
3711
Mathias Agopian65ab4712010-07-14 17:59:35 -07003712bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003713 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003714
John Grossman4ff14ba2012-02-08 16:37:41 -08003715 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003716 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3717 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003718 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003719 return true;
3720 }
3721 return false;
3722}
3723
Eric Laurenta011e352012-03-29 15:51:43 -07003724status_t AudioFlinger::PlaybackThread::Track::start(pid_t tid,
3725 AudioSystem::sync_event_t event,
3726 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003727{
3728 status_t status = NO_ERROR;
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003729 ALOGV("start(%d), calling pid %d session %d tid %d",
3730 mName, IPCThreadState::self()->getCallingPid(), mSessionId, tid);
Glenn Kasten73d22752012-03-19 13:38:30 -07003731 // check for use case 2 with missing callback
3732 if (isFastTrack() && (mSharedBuffer == 0) && (tid == 0)) {
3733 ALOGW("AUDIO_POLICY_OUTPUT_FLAG_FAST denied");
3734 mFlags &= ~IAudioFlinger::TRACK_FAST;
3735 // FIXME the track must be invalidated and moved to another thread or
3736 // attached directly to the normal mixer now
3737 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003738 sp<ThreadBase> thread = mThread.promote();
3739 if (thread != 0) {
3740 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003741 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003742 // here the track could be either new, or restarted
3743 // in both cases "unstop" the track
3744 if (mState == PAUSED) {
3745 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003746 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003747 } else {
3748 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003749 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003750 }
3751
3752 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3753 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003754 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003755 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003756
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003757#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003758 // to track the speaker usage
3759 if (status == NO_ERROR) {
3760 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3761 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003762#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003763 }
3764 if (status == NO_ERROR) {
3765 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3766 playbackThread->addTrack_l(this);
3767 } else {
3768 mState = state;
3769 }
3770 } else {
3771 status = BAD_VALUE;
3772 }
3773 return status;
3774}
3775
3776void AudioFlinger::PlaybackThread::Track::stop()
3777{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003778 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003779 sp<ThreadBase> thread = mThread.promote();
3780 if (thread != 0) {
3781 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003782 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003783 if (mState > STOPPED) {
3784 mState = STOPPED;
3785 // If the track is not active (PAUSED and buffers full), flush buffers
3786 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3787 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3788 reset();
3789 }
Steve Block3856b092011-10-20 11:56:00 +01003790 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003791 }
3792 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3793 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003794 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003795 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003796
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003797#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003798 // to track the speaker usage
3799 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003800#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003801 }
3802 }
3803}
3804
3805void AudioFlinger::PlaybackThread::Track::pause()
3806{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003807 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003808 sp<ThreadBase> thread = mThread.promote();
3809 if (thread != 0) {
3810 Mutex::Autolock _l(thread->mLock);
3811 if (mState == ACTIVE || mState == RESUMING) {
3812 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003813 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003814 if (!isOutputTrack()) {
3815 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003816 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003817 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003818
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003819#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003820 // to track the speaker usage
3821 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003822#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003823 }
3824 }
3825 }
3826}
3827
3828void AudioFlinger::PlaybackThread::Track::flush()
3829{
Steve Block3856b092011-10-20 11:56:00 +01003830 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003831 sp<ThreadBase> thread = mThread.promote();
3832 if (thread != 0) {
3833 Mutex::Autolock _l(thread->mLock);
3834 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3835 return;
3836 }
3837 // No point remaining in PAUSED state after a flush => go to
3838 // STOPPED state
3839 mState = STOPPED;
3840
Eric Laurent38ccae22011-03-28 18:37:07 -07003841 // do not reset the track if it is still in the process of being stopped or paused.
3842 // this will be done by prepareTracks_l() when the track is stopped.
3843 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3844 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3845 reset();
3846 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003847 }
3848}
3849
3850void AudioFlinger::PlaybackThread::Track::reset()
3851{
3852 // Do not reset twice to avoid discarding data written just after a flush and before
3853 // the audioflinger thread detects the track is stopped.
3854 if (!mResetDone) {
3855 TrackBase::reset();
3856 // Force underrun condition to avoid false underrun callback until first data is
3857 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003858 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3859 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003860 mFillingUpStatus = FS_FILLING;
3861 mResetDone = true;
Eric Laurenta011e352012-03-29 15:51:43 -07003862 mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003863 }
3864}
3865
3866void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3867{
3868 mMute = muted;
3869}
3870
Mathias Agopian65ab4712010-07-14 17:59:35 -07003871status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3872{
3873 status_t status = DEAD_OBJECT;
3874 sp<ThreadBase> thread = mThread.promote();
3875 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003876 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3877 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003878 }
3879 return status;
3880}
3881
3882void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3883{
3884 mAuxEffectId = EffectId;
3885 mAuxBuffer = buffer;
3886}
3887
Eric Laurenta011e352012-03-29 15:51:43 -07003888bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
3889 size_t audioHalFrames)
3890{
3891 // a track is considered presented when the total number of frames written to audio HAL
3892 // corresponds to the number of frames written when presentationComplete() is called for the
3893 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
3894 if (mPresentationCompleteFrames == 0) {
3895 mPresentationCompleteFrames = framesWritten + audioHalFrames;
3896 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
3897 mPresentationCompleteFrames, audioHalFrames);
3898 }
3899 if (framesWritten >= mPresentationCompleteFrames) {
3900 ALOGV("presentationComplete() session %d complete: framesWritten %d",
3901 mSessionId, framesWritten);
3902 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
3903 mPresentationCompleteFrames = 0;
3904 return true;
3905 }
3906 return false;
3907}
3908
3909void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
3910{
3911 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
3912 if (mSyncEvents[i]->type() == type) {
3913 mSyncEvents[i]->trigger();
3914 mSyncEvents.removeAt(i);
3915 i--;
3916 }
3917 }
3918}
3919
3920
John Grossman4ff14ba2012-02-08 16:37:41 -08003921// timed audio tracks
3922
3923sp<AudioFlinger::PlaybackThread::TimedTrack>
3924AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003925 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003926 const sp<Client>& client,
3927 audio_stream_type_t streamType,
3928 uint32_t sampleRate,
3929 audio_format_t format,
3930 uint32_t channelMask,
3931 int frameCount,
3932 const sp<IMemory>& sharedBuffer,
3933 int sessionId) {
3934 if (!client->reserveTimedTrack())
3935 return NULL;
3936
Glenn Kastena0356762012-03-19 10:38:51 -07003937 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08003938 thread, client, streamType, sampleRate, format, channelMask, frameCount,
3939 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08003940}
3941
3942AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003943 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003944 const sp<Client>& client,
3945 audio_stream_type_t streamType,
3946 uint32_t sampleRate,
3947 audio_format_t format,
3948 uint32_t channelMask,
3949 int frameCount,
3950 const sp<IMemory>& sharedBuffer,
3951 int sessionId)
3952 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07003953 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman4ff14ba2012-02-08 16:37:41 -08003954 mTimedSilenceBuffer(NULL),
3955 mTimedSilenceBufferSize(0),
3956 mTimedAudioOutputOnTime(false),
3957 mMediaTimeTransformValid(false)
3958{
3959 LocalClock lc;
3960 mLocalTimeFreq = lc.getLocalFreq();
3961
3962 mLocalTimeToSampleTransform.a_zero = 0;
3963 mLocalTimeToSampleTransform.b_zero = 0;
3964 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3965 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3966 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3967 &mLocalTimeToSampleTransform.a_to_b_denom);
3968}
3969
3970AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3971 mClient->releaseTimedTrack();
3972 delete [] mTimedSilenceBuffer;
3973}
3974
3975status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3976 size_t size, sp<IMemory>* buffer) {
3977
3978 Mutex::Autolock _l(mTimedBufferQueueLock);
3979
3980 trimTimedBufferQueue_l();
3981
3982 // lazily initialize the shared memory heap for timed buffers
3983 if (mTimedMemoryDealer == NULL) {
3984 const int kTimedBufferHeapSize = 512 << 10;
3985
3986 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3987 "AudioFlingerTimed");
3988 if (mTimedMemoryDealer == NULL)
3989 return NO_MEMORY;
3990 }
3991
3992 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3993 if (newBuffer == NULL) {
3994 newBuffer = mTimedMemoryDealer->allocate(size);
3995 if (newBuffer == NULL)
3996 return NO_MEMORY;
3997 }
3998
3999 *buffer = newBuffer;
4000 return NO_ERROR;
4001}
4002
4003// caller must hold mTimedBufferQueueLock
4004void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4005 int64_t mediaTimeNow;
4006 {
4007 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4008 if (!mMediaTimeTransformValid)
4009 return;
4010
4011 int64_t targetTimeNow;
4012 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4013 ? mCCHelper.getCommonTime(&targetTimeNow)
4014 : mCCHelper.getLocalTime(&targetTimeNow);
4015
4016 if (OK != res)
4017 return;
4018
4019 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4020 &mediaTimeNow)) {
4021 return;
4022 }
4023 }
4024
4025 size_t trimIndex;
4026 for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
4027 if (mTimedBufferQueue[trimIndex].pts() > mediaTimeNow)
4028 break;
4029 }
4030
4031 if (trimIndex) {
4032 mTimedBufferQueue.removeItemsAt(0, trimIndex);
4033 }
4034}
4035
4036status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4037 const sp<IMemory>& buffer, int64_t pts) {
4038
4039 {
4040 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4041 if (!mMediaTimeTransformValid)
4042 return INVALID_OPERATION;
4043 }
4044
4045 Mutex::Autolock _l(mTimedBufferQueueLock);
4046
4047 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4048
4049 return NO_ERROR;
4050}
4051
4052status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4053 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4054
4055 ALOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
4056 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4057 target);
4058
4059 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4060 target == TimedAudioTrack::COMMON_TIME)) {
4061 return BAD_VALUE;
4062 }
4063
4064 Mutex::Autolock lock(mMediaTimeTransformLock);
4065 mMediaTimeTransform = xform;
4066 mMediaTimeTransformTarget = target;
4067 mMediaTimeTransformValid = true;
4068
4069 return NO_ERROR;
4070}
4071
4072#define min(a, b) ((a) < (b) ? (a) : (b))
4073
4074// implementation of getNextBuffer for tracks whose buffers have timestamps
4075status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4076 AudioBufferProvider::Buffer* buffer, int64_t pts)
4077{
4078 if (pts == AudioBufferProvider::kInvalidPTS) {
4079 buffer->raw = 0;
4080 buffer->frameCount = 0;
4081 return INVALID_OPERATION;
4082 }
4083
John Grossman4ff14ba2012-02-08 16:37:41 -08004084 Mutex::Autolock _l(mTimedBufferQueueLock);
4085
4086 while (true) {
4087
4088 // if we have no timed buffers, then fail
4089 if (mTimedBufferQueue.isEmpty()) {
4090 buffer->raw = 0;
4091 buffer->frameCount = 0;
4092 return NOT_ENOUGH_DATA;
4093 }
4094
4095 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4096
4097 // calculate the PTS of the head of the timed buffer queue expressed in
4098 // local time
4099 int64_t headLocalPTS;
4100 {
4101 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4102
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004103 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08004104
4105 if (mMediaTimeTransform.a_to_b_denom == 0) {
4106 // the transform represents a pause, so yield silence
4107 timedYieldSilence(buffer->frameCount, buffer);
4108 return NO_ERROR;
4109 }
4110
4111 int64_t transformedPTS;
4112 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4113 &transformedPTS)) {
4114 // the transform failed. this shouldn't happen, but if it does
4115 // then just drop this buffer
4116 ALOGW("timedGetNextBuffer transform failed");
4117 buffer->raw = 0;
4118 buffer->frameCount = 0;
4119 mTimedBufferQueue.removeAt(0);
4120 return NO_ERROR;
4121 }
4122
4123 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
4124 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
4125 &headLocalPTS)) {
4126 buffer->raw = 0;
4127 buffer->frameCount = 0;
4128 return INVALID_OPERATION;
4129 }
4130 } else {
4131 headLocalPTS = transformedPTS;
4132 }
4133 }
4134
4135 // adjust the head buffer's PTS to reflect the portion of the head buffer
4136 // that has already been consumed
4137 int64_t effectivePTS = headLocalPTS +
4138 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4139
4140 // Calculate the delta in samples between the head of the input buffer
4141 // queue and the start of the next output buffer that will be written.
4142 // If the transformation fails because of over or underflow, it means
4143 // that the sample's position in the output stream is so far out of
4144 // whack that it should just be dropped.
4145 int64_t sampleDelta;
4146 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4147 ALOGV("*** head buffer is too far from PTS: dropped buffer");
4148 mTimedBufferQueue.removeAt(0);
4149 continue;
4150 }
4151 if (!mLocalTimeToSampleTransform.doForwardTransform(
4152 (effectivePTS - pts) << 32, &sampleDelta)) {
4153 ALOGV("*** too late during sample rate transform: dropped buffer");
4154 mTimedBufferQueue.removeAt(0);
4155 continue;
4156 }
4157
4158 ALOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
4159 __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
4160 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
4161 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
4162
4163 // if the delta between the ideal placement for the next input sample and
4164 // the current output position is within this threshold, then we will
4165 // concatenate the next input samples to the previous output
4166 const int64_t kSampleContinuityThreshold =
4167 (static_cast<int64_t>(sampleRate()) << 32) / 10;
4168
4169 // if this is the first buffer of audio that we're emitting from this track
4170 // then it should be almost exactly on time.
4171 const int64_t kSampleStartupThreshold = 1LL << 32;
4172
4173 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
4174 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
4175 // the next input is close enough to being on time, so concatenate it
4176 // with the last output
4177 timedYieldSamples(buffer);
4178
4179 ALOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4180 return NO_ERROR;
4181 } else if (sampleDelta > 0) {
4182 // the gap between the current output position and the proper start of
4183 // the next input sample is too big, so fill it with silence
4184 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4185
4186 timedYieldSilence(framesUntilNextInput, buffer);
4187 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4188 return NO_ERROR;
4189 } else {
4190 // the next input sample is late
4191 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4192 size_t onTimeSamplePosition =
4193 head.position() + lateFrames * mCblk->frameSize;
4194
4195 if (onTimeSamplePosition > head.buffer()->size()) {
4196 // all the remaining samples in the head are too late, so
4197 // drop it and move on
4198 ALOGV("*** too late: dropped buffer");
4199 mTimedBufferQueue.removeAt(0);
4200 continue;
4201 } else {
4202 // skip over the late samples
4203 head.setPosition(onTimeSamplePosition);
4204
4205 // yield the available samples
4206 timedYieldSamples(buffer);
4207
4208 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4209 return NO_ERROR;
4210 }
4211 }
4212 }
4213}
4214
4215// Yield samples from the timed buffer queue head up to the given output
4216// buffer's capacity.
4217//
4218// Caller must hold mTimedBufferQueueLock
4219void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples(
4220 AudioBufferProvider::Buffer* buffer) {
4221
4222 const TimedBuffer& head = mTimedBufferQueue[0];
4223
4224 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4225 head.position());
4226
4227 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4228 mCblk->frameSize);
4229 size_t framesRequested = buffer->frameCount;
4230 buffer->frameCount = min(framesLeftInHead, framesRequested);
4231
4232 mTimedAudioOutputOnTime = true;
4233}
4234
4235// Yield samples of silence up to the given output buffer's capacity
4236//
4237// Caller must hold mTimedBufferQueueLock
4238void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence(
4239 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4240
4241 // lazily allocate a buffer filled with silence
4242 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4243 delete [] mTimedSilenceBuffer;
4244 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4245 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4246 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4247 }
4248
4249 buffer->raw = mTimedSilenceBuffer;
4250 size_t framesRequested = buffer->frameCount;
4251 buffer->frameCount = min(numFrames, framesRequested);
4252
4253 mTimedAudioOutputOnTime = false;
4254}
4255
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004256// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004257void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4258 AudioBufferProvider::Buffer* buffer) {
4259
4260 Mutex::Autolock _l(mTimedBufferQueueLock);
4261
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004262 // If the buffer which was just released is part of the buffer at the head
4263 // of the queue, be sure to update the amt of the buffer which has been
4264 // consumed. If the buffer being returned is not part of the head of the
4265 // queue, its either because the buffer is part of the silence buffer, or
4266 // because the head of the timed queue was trimmed after the mixer called
4267 // getNextBuffer but before the mixer called releaseBuffer.
4268 if ((buffer->raw != mTimedSilenceBuffer) && mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004269 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004270
4271 void* start = head.buffer()->pointer();
Glenn Kastenf063b492012-02-17 16:24:10 -08004272 void* end = (char *) head.buffer()->pointer() + head.buffer()->size();
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004273
4274 if ((buffer->raw >= start) && (buffer->raw <= end)) {
4275 head.setPosition(head.position() +
4276 (buffer->frameCount * mCblk->frameSize));
4277 if (static_cast<size_t>(head.position()) >= head.buffer()->size()) {
4278 mTimedBufferQueue.removeAt(0);
4279 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004280 }
4281 }
4282
4283 buffer->raw = 0;
4284 buffer->frameCount = 0;
4285}
4286
4287uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4288 Mutex::Autolock _l(mTimedBufferQueueLock);
4289
4290 uint32_t frames = 0;
4291 for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4292 const TimedBuffer& tb = mTimedBufferQueue[i];
4293 frames += (tb.buffer()->size() - tb.position()) / mCblk->frameSize;
4294 }
4295
4296 return frames;
4297}
4298
4299AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4300 : mPTS(0), mPosition(0) {}
4301
4302AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4303 const sp<IMemory>& buffer, int64_t pts)
4304 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4305
Mathias Agopian65ab4712010-07-14 17:59:35 -07004306// ----------------------------------------------------------------------------
4307
4308// RecordTrack constructor must be called with AudioFlinger::mLock held
4309AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004310 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004311 const sp<Client>& client,
4312 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004313 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004314 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004315 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004316 int sessionId)
4317 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004318 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004319 mOverflow(false)
4320{
4321 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004322 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
4323 if (format == AUDIO_FORMAT_PCM_16_BIT) {
4324 mCblk->frameSize = mChannelCount * sizeof(int16_t);
4325 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
4326 mCblk->frameSize = mChannelCount * sizeof(int8_t);
4327 } else {
4328 mCblk->frameSize = sizeof(int8_t);
4329 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004330 }
4331}
4332
4333AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4334{
4335 sp<ThreadBase> thread = mThread.promote();
4336 if (thread != 0) {
4337 AudioSystem::releaseInput(thread->id());
4338 }
4339}
4340
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004341// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004342status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004343{
4344 audio_track_cblk_t* cblk = this->cblk();
4345 uint32_t framesAvail;
4346 uint32_t framesReq = buffer->frameCount;
4347
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004348 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004349 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004350 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004351 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004352 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004353 }
4354
4355 framesAvail = cblk->framesAvailable_l();
4356
Glenn Kastenf6b16782011-12-15 09:51:17 -08004357 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004358 uint32_t s = cblk->server;
4359 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4360
4361 if (framesReq > framesAvail) {
4362 framesReq = framesAvail;
4363 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004364 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004365 framesReq = bufferEnd - s;
4366 }
4367
4368 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004369 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004370
4371 buffer->frameCount = framesReq;
4372 return NO_ERROR;
4373 }
4374
4375getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004376 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004377 buffer->frameCount = 0;
4378 return NOT_ENOUGH_DATA;
4379}
4380
Eric Laurenta011e352012-03-29 15:51:43 -07004381status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid,
4382 AudioSystem::sync_event_t event,
4383 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004384{
4385 sp<ThreadBase> thread = mThread.promote();
4386 if (thread != 0) {
4387 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurenta011e352012-03-29 15:51:43 -07004388 return recordThread->start(this, tid, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004389 } else {
4390 return BAD_VALUE;
4391 }
4392}
4393
4394void AudioFlinger::RecordThread::RecordTrack::stop()
4395{
4396 sp<ThreadBase> thread = mThread.promote();
4397 if (thread != 0) {
4398 RecordThread *recordThread = (RecordThread *)thread.get();
4399 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004400 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08004401 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07004402 // read from buffer
4403 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004404 }
4405}
4406
4407void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4408{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004409 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004410 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004411 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004412 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004413 mSessionId,
4414 mFrameCount,
4415 mState,
4416 mCblk->sampleRate,
4417 mCblk->server,
4418 mCblk->user);
4419}
4420
4421
4422// ----------------------------------------------------------------------------
4423
4424AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004425 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004426 DuplicatingThread *sourceThread,
4427 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004428 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004429 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004430 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07004431 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
4432 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004433 mActive(false), mSourceThread(sourceThread)
4434{
4435
Mathias Agopian65ab4712010-07-14 17:59:35 -07004436 if (mCblk != NULL) {
4437 mCblk->flags |= CBLK_DIRECTION_OUT;
4438 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004439 mOutBuffer.frameCount = 0;
4440 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01004441 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004442 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4443 mCblk, mBuffer, mCblk->buffers,
4444 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004445 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004446 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004447 }
4448}
4449
4450AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4451{
4452 clearBufferQueue();
4453}
4454
Eric Laurenta011e352012-03-29 15:51:43 -07004455status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid,
4456 AudioSystem::sync_event_t event,
4457 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004458{
Eric Laurenta011e352012-03-29 15:51:43 -07004459 status_t status = Track::start(tid, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004460 if (status != NO_ERROR) {
4461 return status;
4462 }
4463
4464 mActive = true;
4465 mRetryCount = 127;
4466 return status;
4467}
4468
4469void AudioFlinger::PlaybackThread::OutputTrack::stop()
4470{
4471 Track::stop();
4472 clearBufferQueue();
4473 mOutBuffer.frameCount = 0;
4474 mActive = false;
4475}
4476
4477bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4478{
4479 Buffer *pInBuffer;
4480 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004481 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004482 bool outputBufferFull = false;
4483 inBuffer.frameCount = frames;
4484 inBuffer.i16 = data;
4485
4486 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4487
4488 if (!mActive && frames != 0) {
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004489 start(0);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004490 sp<ThreadBase> thread = mThread.promote();
4491 if (thread != 0) {
4492 MixerThread *mixerThread = (MixerThread *)thread.get();
4493 if (mCblk->frameCount > frames){
4494 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4495 uint32_t startFrames = (mCblk->frameCount - frames);
4496 pInBuffer = new Buffer;
4497 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4498 pInBuffer->frameCount = startFrames;
4499 pInBuffer->i16 = pInBuffer->mBuffer;
4500 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4501 mBufferQueue.add(pInBuffer);
4502 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004503 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004504 }
4505 }
4506 }
4507 }
4508
4509 while (waitTimeLeftMs) {
4510 // First write pending buffers, then new data
4511 if (mBufferQueue.size()) {
4512 pInBuffer = mBufferQueue.itemAt(0);
4513 } else {
4514 pInBuffer = &inBuffer;
4515 }
4516
4517 if (pInBuffer->frameCount == 0) {
4518 break;
4519 }
4520
4521 if (mOutBuffer.frameCount == 0) {
4522 mOutBuffer.frameCount = pInBuffer->frameCount;
4523 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08004524 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01004525 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004526 outputBufferFull = true;
4527 break;
4528 }
4529 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4530 if (waitTimeLeftMs >= waitTimeMs) {
4531 waitTimeLeftMs -= waitTimeMs;
4532 } else {
4533 waitTimeLeftMs = 0;
4534 }
4535 }
4536
4537 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4538 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4539 mCblk->stepUser(outFrames);
4540 pInBuffer->frameCount -= outFrames;
4541 pInBuffer->i16 += outFrames * channelCount;
4542 mOutBuffer.frameCount -= outFrames;
4543 mOutBuffer.i16 += outFrames * channelCount;
4544
4545 if (pInBuffer->frameCount == 0) {
4546 if (mBufferQueue.size()) {
4547 mBufferQueue.removeAt(0);
4548 delete [] pInBuffer->mBuffer;
4549 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01004550 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004551 } else {
4552 break;
4553 }
4554 }
4555 }
4556
4557 // If we could not write all frames, allocate a buffer and queue it for next time.
4558 if (inBuffer.frameCount) {
4559 sp<ThreadBase> thread = mThread.promote();
4560 if (thread != 0 && !thread->standby()) {
4561 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4562 pInBuffer = new Buffer;
4563 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4564 pInBuffer->frameCount = inBuffer.frameCount;
4565 pInBuffer->i16 = pInBuffer->mBuffer;
4566 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4567 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01004568 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004569 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004570 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004571 }
4572 }
4573 }
4574
4575 // Calling write() with a 0 length buffer, means that no more data will be written:
4576 // If no more buffers are pending, fill output track buffer to make sure it is started
4577 // by output mixer.
4578 if (frames == 0 && mBufferQueue.size() == 0) {
4579 if (mCblk->user < mCblk->frameCount) {
4580 frames = mCblk->frameCount - mCblk->user;
4581 pInBuffer = new Buffer;
4582 pInBuffer->mBuffer = new int16_t[frames * channelCount];
4583 pInBuffer->frameCount = frames;
4584 pInBuffer->i16 = pInBuffer->mBuffer;
4585 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4586 mBufferQueue.add(pInBuffer);
4587 } else if (mActive) {
4588 stop();
4589 }
4590 }
4591
4592 return outputBufferFull;
4593}
4594
4595status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4596{
4597 int active;
4598 status_t result;
4599 audio_track_cblk_t* cblk = mCblk;
4600 uint32_t framesReq = buffer->frameCount;
4601
Steve Block3856b092011-10-20 11:56:00 +01004602// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004603 buffer->frameCount = 0;
4604
4605 uint32_t framesAvail = cblk->framesAvailable();
4606
4607
4608 if (framesAvail == 0) {
4609 Mutex::Autolock _l(cblk->lock);
4610 goto start_loop_here;
4611 while (framesAvail == 0) {
4612 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004613 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004614 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004615 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004616 }
4617 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4618 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004619 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004620 }
4621 // read the server count again
4622 start_loop_here:
4623 framesAvail = cblk->framesAvailable_l();
4624 }
4625 }
4626
4627// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004628// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004629// }
4630
4631 if (framesReq > framesAvail) {
4632 framesReq = framesAvail;
4633 }
4634
4635 uint32_t u = cblk->user;
4636 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4637
Marco Nelissena1472d92012-03-30 14:36:54 -07004638 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004639 framesReq = bufferEnd - u;
4640 }
4641
4642 buffer->frameCount = framesReq;
4643 buffer->raw = (void *)cblk->buffer(u);
4644 return NO_ERROR;
4645}
4646
4647
4648void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4649{
4650 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004651
4652 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004653 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004654 delete [] pBuffer->mBuffer;
4655 delete pBuffer;
4656 }
4657 mBufferQueue.clear();
4658}
4659
4660// ----------------------------------------------------------------------------
4661
4662AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4663 : RefBase(),
4664 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08004665 // 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 -07004666 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08004667 mPid(pid),
4668 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004669{
4670 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4671}
4672
4673// Client destructor must be called with AudioFlinger::mLock held
4674AudioFlinger::Client::~Client()
4675{
4676 mAudioFlinger->removeClient_l(mPid);
4677}
4678
Glenn Kasten435dbe62012-01-30 10:15:48 -08004679sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004680{
4681 return mMemoryDealer;
4682}
4683
John Grossman4ff14ba2012-02-08 16:37:41 -08004684// Reserve one of the limited slots for a timed audio track associated
4685// with this client
4686bool AudioFlinger::Client::reserveTimedTrack()
4687{
4688 const int kMaxTimedTracksPerClient = 4;
4689
4690 Mutex::Autolock _l(mTimedTrackLock);
4691
4692 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4693 ALOGW("can not create timed track - pid %d has exceeded the limit",
4694 mPid);
4695 return false;
4696 }
4697
4698 mTimedTrackCount++;
4699 return true;
4700}
4701
4702// Release a slot for a timed audio track
4703void AudioFlinger::Client::releaseTimedTrack()
4704{
4705 Mutex::Autolock _l(mTimedTrackLock);
4706 mTimedTrackCount--;
4707}
4708
Mathias Agopian65ab4712010-07-14 17:59:35 -07004709// ----------------------------------------------------------------------------
4710
4711AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4712 const sp<IAudioFlingerClient>& client,
4713 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004714 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004715{
4716}
4717
4718AudioFlinger::NotificationClient::~NotificationClient()
4719{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004720}
4721
4722void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4723{
4724 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08004725 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004726}
4727
4728// ----------------------------------------------------------------------------
4729
4730AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4731 : BnAudioTrack(),
4732 mTrack(track)
4733{
4734}
4735
4736AudioFlinger::TrackHandle::~TrackHandle() {
4737 // just stop the track on deletion, associated resources
4738 // will be freed from the main thread once all pending buffers have
4739 // been played. Unless it's not in the active track list, in which
4740 // case we free everything now...
4741 mTrack->destroy();
4742}
4743
Glenn Kasten90716c52012-01-26 13:40:12 -08004744sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4745 return mTrack->getCblk();
4746}
4747
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004748status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4749 return mTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004750}
4751
4752void AudioFlinger::TrackHandle::stop() {
4753 mTrack->stop();
4754}
4755
4756void AudioFlinger::TrackHandle::flush() {
4757 mTrack->flush();
4758}
4759
4760void AudioFlinger::TrackHandle::mute(bool e) {
4761 mTrack->mute(e);
4762}
4763
4764void AudioFlinger::TrackHandle::pause() {
4765 mTrack->pause();
4766}
4767
Mathias Agopian65ab4712010-07-14 17:59:35 -07004768status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4769{
4770 return mTrack->attachAuxEffect(EffectId);
4771}
4772
John Grossman4ff14ba2012-02-08 16:37:41 -08004773status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4774 sp<IMemory>* buffer) {
4775 if (!mTrack->isTimedTrack())
4776 return INVALID_OPERATION;
4777
4778 PlaybackThread::TimedTrack* tt =
4779 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4780 return tt->allocateTimedBuffer(size, buffer);
4781}
4782
4783status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4784 int64_t pts) {
4785 if (!mTrack->isTimedTrack())
4786 return INVALID_OPERATION;
4787
4788 PlaybackThread::TimedTrack* tt =
4789 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4790 return tt->queueTimedBuffer(buffer, pts);
4791}
4792
4793status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4794 const LinearTransform& xform, int target) {
4795
4796 if (!mTrack->isTimedTrack())
4797 return INVALID_OPERATION;
4798
4799 PlaybackThread::TimedTrack* tt =
4800 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4801 return tt->setMediaTimeTransform(
4802 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4803}
4804
Mathias Agopian65ab4712010-07-14 17:59:35 -07004805status_t AudioFlinger::TrackHandle::onTransact(
4806 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4807{
4808 return BnAudioTrack::onTransact(code, data, reply, flags);
4809}
4810
4811// ----------------------------------------------------------------------------
4812
4813sp<IAudioRecord> AudioFlinger::openRecord(
4814 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004815 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004816 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004817 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004818 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004819 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08004820 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004821 int *sessionId,
4822 status_t *status)
4823{
4824 sp<RecordThread::RecordTrack> recordTrack;
4825 sp<RecordHandle> recordHandle;
4826 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004827 status_t lStatus;
4828 RecordThread *thread;
4829 size_t inFrameCount;
4830 int lSessionId;
4831
4832 // check calling permissions
4833 if (!recordingAllowed()) {
4834 lStatus = PERMISSION_DENIED;
4835 goto Exit;
4836 }
4837
4838 // add client to list
4839 { // scope for mLock
4840 Mutex::Autolock _l(mLock);
4841 thread = checkRecordThread_l(input);
4842 if (thread == NULL) {
4843 lStatus = BAD_VALUE;
4844 goto Exit;
4845 }
4846
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004847 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004848
4849 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004850 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004851 lSessionId = *sessionId;
4852 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004853 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004854 if (sessionId != NULL) {
4855 *sessionId = lSessionId;
4856 }
4857 }
4858 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004859 recordTrack = thread->createRecordTrack_l(client,
4860 sampleRate,
4861 format,
4862 channelMask,
4863 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004864 lSessionId,
4865 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004866 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004867 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004868 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4869 // destructor is called by the TrackBase destructor with mLock held
4870 client.clear();
4871 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004872 goto Exit;
4873 }
4874
4875 // return to handle to client
4876 recordHandle = new RecordHandle(recordTrack);
4877 lStatus = NO_ERROR;
4878
4879Exit:
4880 if (status) {
4881 *status = lStatus;
4882 }
4883 return recordHandle;
4884}
4885
4886// ----------------------------------------------------------------------------
4887
4888AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4889 : BnAudioRecord(),
4890 mRecordTrack(recordTrack)
4891{
4892}
4893
4894AudioFlinger::RecordHandle::~RecordHandle() {
4895 stop();
4896}
4897
Glenn Kasten90716c52012-01-26 13:40:12 -08004898sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4899 return mRecordTrack->getCblk();
4900}
4901
Eric Laurenta011e352012-03-29 15:51:43 -07004902status_t AudioFlinger::RecordHandle::start(pid_t tid, int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01004903 ALOGV("RecordHandle::start()");
Eric Laurenta011e352012-03-29 15:51:43 -07004904 return mRecordTrack->start(tid, (AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004905}
4906
4907void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004908 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004909 mRecordTrack->stop();
4910}
4911
Mathias Agopian65ab4712010-07-14 17:59:35 -07004912status_t AudioFlinger::RecordHandle::onTransact(
4913 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4914{
4915 return BnAudioRecord::onTransact(code, data, reply, flags);
4916}
4917
4918// ----------------------------------------------------------------------------
4919
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004920AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4921 AudioStreamIn *input,
4922 uint32_t sampleRate,
4923 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004924 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004925 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004926 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004927 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4928 // mRsmpInIndex and mInputBytes set by readInputParameters()
4929 mReqChannelCount(popcount(channels)),
4930 mReqSampleRate(sampleRate)
4931 // mBytesRead is only meaningful while active, and so is cleared in start()
4932 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004933{
Glenn Kasten480b4682012-02-28 12:30:08 -08004934 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07004935
Mathias Agopian65ab4712010-07-14 17:59:35 -07004936 readInputParameters();
4937}
4938
4939
4940AudioFlinger::RecordThread::~RecordThread()
4941{
4942 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004943 delete mResampler;
4944 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004945}
4946
4947void AudioFlinger::RecordThread::onFirstRef()
4948{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004949 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004950}
4951
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004952status_t AudioFlinger::RecordThread::readyToRun()
4953{
4954 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004955 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004956 return status;
4957}
4958
Mathias Agopian65ab4712010-07-14 17:59:35 -07004959bool AudioFlinger::RecordThread::threadLoop()
4960{
4961 AudioBufferProvider::Buffer buffer;
4962 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004963 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004964
Eric Laurent44d98482010-09-30 16:12:31 -07004965 nsecs_t lastWarning = 0;
4966
Eric Laurentfeb0db62011-07-22 09:04:31 -07004967 acquireWakeLock();
4968
Mathias Agopian65ab4712010-07-14 17:59:35 -07004969 // start recording
4970 while (!exitPending()) {
4971
4972 processConfigEvents();
4973
4974 { // scope for mLock
4975 Mutex::Autolock _l(mLock);
4976 checkForNewParameters_l();
4977 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4978 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004979 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004980 mStandby = true;
4981 }
4982
4983 if (exitPending()) break;
4984
Eric Laurentfeb0db62011-07-22 09:04:31 -07004985 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004986 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004987 // go to sleep
4988 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004989 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004990 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004991 continue;
4992 }
4993 if (mActiveTrack != 0) {
4994 if (mActiveTrack->mState == TrackBase::PAUSING) {
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 mStandby = true;
4998 }
4999 mActiveTrack.clear();
5000 mStartStopCond.broadcast();
5001 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5002 if (mReqChannelCount != mActiveTrack->channelCount()) {
5003 mActiveTrack.clear();
5004 mStartStopCond.broadcast();
5005 } else if (mBytesRead != 0) {
5006 // record start succeeds only if first read from audio input
5007 // succeeds
5008 if (mBytesRead > 0) {
5009 mActiveTrack->mState = TrackBase::ACTIVE;
5010 } else {
5011 mActiveTrack.clear();
5012 }
5013 mStartStopCond.broadcast();
5014 }
5015 mStandby = false;
5016 }
5017 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005018 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005019 }
5020
5021 if (mActiveTrack != 0) {
5022 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5023 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005024 unlockEffectChains(effectChains);
5025 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005026 continue;
5027 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005028 for (size_t i = 0; i < effectChains.size(); i ++) {
5029 effectChains[i]->process_l();
5030 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005031
Mathias Agopian65ab4712010-07-14 17:59:35 -07005032 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005033 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005034 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08005035 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005036 // no resampling
5037 while (framesOut) {
5038 size_t framesIn = mFrameCount - mRsmpInIndex;
5039 if (framesIn) {
5040 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
5041 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
5042 if (framesIn > framesOut)
5043 framesIn = framesOut;
5044 mRsmpInIndex += framesIn;
5045 framesOut -= framesIn;
5046 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07005047 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005048 memcpy(dst, src, framesIn * mFrameSize);
5049 } else {
5050 int16_t *src16 = (int16_t *)src;
5051 int16_t *dst16 = (int16_t *)dst;
5052 if (mChannelCount == 1) {
5053 while (framesIn--) {
5054 *dst16++ = *src16;
5055 *dst16++ = *src16++;
5056 }
5057 } else {
5058 while (framesIn--) {
5059 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
5060 src16 += 2;
5061 }
5062 }
5063 }
5064 }
5065 if (framesOut && mFrameCount == mRsmpInIndex) {
5066 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005067 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005068 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005069 framesOut = 0;
5070 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07005071 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005072 mRsmpInIndex = 0;
5073 }
5074 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005075 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005076 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5077 // Force input into standby so that it tries to
5078 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005079 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005080 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005081 }
5082 mRsmpInIndex = mFrameCount;
5083 framesOut = 0;
5084 buffer.frameCount = 0;
5085 }
5086 }
5087 }
5088 } else {
5089 // resampling
5090
5091 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
5092 // alter output frame count as if we were expecting stereo samples
5093 if (mChannelCount == 1 && mReqChannelCount == 1) {
5094 framesOut >>= 1;
5095 }
5096 mResampler->resample(mRsmpOutBuffer, framesOut, this);
5097 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
5098 // are 32 bit aligned which should be always true.
5099 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005100 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005101 // the resampler always outputs stereo samples: do post stereo to mono conversion
5102 int16_t *src = (int16_t *)mRsmpOutBuffer;
5103 int16_t *dst = buffer.i16;
5104 while (framesOut--) {
5105 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
5106 src += 2;
5107 }
5108 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005109 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005110 }
5111
5112 }
Eric Laurenta011e352012-03-29 15:51:43 -07005113 if (mFramestoDrop == 0) {
5114 mActiveTrack->releaseBuffer(&buffer);
5115 } else {
5116 if (mFramestoDrop > 0) {
5117 mFramestoDrop -= buffer.frameCount;
5118 if (mFramestoDrop < 0) {
5119 mFramestoDrop = 0;
5120 }
5121 }
5122 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005123 mActiveTrack->overflow();
5124 }
5125 // client isn't retrieving buffers fast enough
5126 else {
Eric Laurent44d98482010-09-30 16:12:31 -07005127 if (!mActiveTrack->setOverflow()) {
5128 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08005129 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005130 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07005131 lastWarning = now;
5132 }
5133 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005134 // Release the processor for a while before asking for a new buffer.
5135 // This will give the application more chance to read from the buffer and
5136 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005137 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005138 }
5139 }
Eric Laurentec437d82011-07-26 20:54:46 -07005140 // enable changes in effect chain
5141 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005142 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005143 }
5144
5145 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005146 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005147 }
5148 mActiveTrack.clear();
5149
5150 mStartStopCond.broadcast();
5151
Eric Laurentfeb0db62011-07-22 09:04:31 -07005152 releaseWakeLock();
5153
Steve Block3856b092011-10-20 11:56:00 +01005154 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005155 return false;
5156}
5157
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005158
5159sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5160 const sp<AudioFlinger::Client>& client,
5161 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005162 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005163 int channelMask,
5164 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005165 int sessionId,
5166 status_t *status)
5167{
5168 sp<RecordTrack> track;
5169 status_t lStatus;
5170
5171 lStatus = initCheck();
5172 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005173 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005174 goto Exit;
5175 }
5176
5177 { // scope for mLock
5178 Mutex::Autolock _l(mLock);
5179
5180 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005181 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005182
Glenn Kasten7378ca52012-01-20 13:44:40 -08005183 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005184 lStatus = NO_MEMORY;
5185 goto Exit;
5186 }
5187
5188 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005189 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5190 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005191 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005192 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5193 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005194 }
5195 lStatus = NO_ERROR;
5196
5197Exit:
5198 if (status) {
5199 *status = lStatus;
5200 }
5201 return track;
5202}
5203
Eric Laurenta011e352012-03-29 15:51:43 -07005204status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5205 pid_t tid, AudioSystem::sync_event_t event,
5206 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005207{
Eric Laurenta011e352012-03-29 15:51:43 -07005208 ALOGV("RecordThread::start tid=%d, event %d, triggerSession %d", tid, event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005209 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005210 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07005211
5212 if (event == AudioSystem::SYNC_EVENT_NONE) {
5213 mSyncStartEvent.clear();
5214 mFramestoDrop = 0;
5215 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
5216 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
5217 triggerSession,
5218 recordTrack->sessionId(),
5219 syncStartEventCallback,
5220 this);
5221 mFramestoDrop = -1;
5222 }
5223
Mathias Agopian65ab4712010-07-14 17:59:35 -07005224 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005225 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005226 if (mActiveTrack != 0) {
5227 if (recordTrack != mActiveTrack.get()) {
5228 status = -EBUSY;
5229 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5230 mActiveTrack->mState = TrackBase::ACTIVE;
5231 }
5232 return status;
5233 }
5234
5235 recordTrack->mState = TrackBase::IDLE;
5236 mActiveTrack = recordTrack;
5237 mLock.unlock();
5238 status_t status = AudioSystem::startInput(mId);
5239 mLock.lock();
5240 if (status != NO_ERROR) {
5241 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07005242 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005243 return status;
5244 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005245 mRsmpInIndex = mFrameCount;
5246 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005247 if (mResampler != NULL) {
5248 mResampler->reset();
5249 }
5250 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005251 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005252 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005253 mWaitWorkCV.signal();
5254 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005255 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005256 mActiveTrack.clear();
5257 status = INVALID_OPERATION;
5258 goto startError;
5259 }
5260 mStartStopCond.wait(mLock);
5261 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005262 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005263 status = BAD_VALUE;
5264 goto startError;
5265 }
Steve Block3856b092011-10-20 11:56:00 +01005266 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005267 return status;
5268 }
5269startError:
5270 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07005271 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005272 return status;
5273}
5274
Eric Laurenta011e352012-03-29 15:51:43 -07005275void AudioFlinger::RecordThread::clearSyncStartEvent()
5276{
5277 if (mSyncStartEvent != 0) {
5278 mSyncStartEvent->cancel();
5279 }
5280 mSyncStartEvent.clear();
5281}
5282
5283void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5284{
5285 sp<SyncEvent> strongEvent = event.promote();
5286
5287 if (strongEvent != 0) {
5288 RecordThread *me = (RecordThread *)strongEvent->cookie();
5289 me->handleSyncStartEvent(strongEvent);
5290 }
5291}
5292
5293void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
5294{
5295 ALOGV("handleSyncStartEvent() mActiveTrack %p session %d event->listenerSession() %d",
5296 mActiveTrack.get(),
5297 mActiveTrack.get() ? mActiveTrack->sessionId() : 0,
5298 event->listenerSession());
5299
5300 if (mActiveTrack != 0 &&
5301 event == mSyncStartEvent) {
5302 // TODO: use actual buffer filling status instead of 2 buffers when info is available
5303 // from audio HAL
5304 mFramestoDrop = mFrameCount * 2;
5305 mSyncStartEvent.clear();
5306 }
5307}
5308
Mathias Agopian65ab4712010-07-14 17:59:35 -07005309void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005310 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005311 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005312 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005313 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005314 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5315 mActiveTrack->mState = TrackBase::PAUSING;
5316 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005317 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005318 return;
5319 }
5320 mStartStopCond.wait(mLock);
5321 // if we have been restarted, recordTrack == mActiveTrack.get() here
5322 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5323 mLock.unlock();
5324 AudioSystem::stopInput(mId);
5325 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005326 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005327 }
5328 }
5329 }
5330}
5331
Eric Laurenta011e352012-03-29 15:51:43 -07005332bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
5333{
5334 return false;
5335}
5336
5337status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
5338{
5339 if (!isValidSyncEvent(event)) {
5340 return BAD_VALUE;
5341 }
5342
5343 Mutex::Autolock _l(mLock);
5344
5345 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
5346 mTrack->setSyncEvent(event);
5347 return NO_ERROR;
5348 }
5349 return NAME_NOT_FOUND;
5350}
5351
Mathias Agopian65ab4712010-07-14 17:59:35 -07005352status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5353{
5354 const size_t SIZE = 256;
5355 char buffer[SIZE];
5356 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005357
5358 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5359 result.append(buffer);
5360
5361 if (mActiveTrack != 0) {
5362 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005363 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005364 mActiveTrack->dump(buffer, SIZE);
5365 result.append(buffer);
5366
5367 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5368 result.append(buffer);
5369 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5370 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005371 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005372 result.append(buffer);
5373 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5374 result.append(buffer);
5375 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5376 result.append(buffer);
5377
5378
5379 } else {
5380 result.append("No record client\n");
5381 }
5382 write(fd, result.string(), result.size());
5383
5384 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005385 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005386
5387 return NO_ERROR;
5388}
5389
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005390// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005391status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005392{
5393 size_t framesReq = buffer->frameCount;
5394 size_t framesReady = mFrameCount - mRsmpInIndex;
5395 int channelCount;
5396
5397 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005398 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005399 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005400 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005401 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5402 // Force input into standby so that it tries to
5403 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005404 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005405 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005406 }
Glenn Kastene0feee32011-12-13 11:53:26 -08005407 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005408 buffer->frameCount = 0;
5409 return NOT_ENOUGH_DATA;
5410 }
5411 mRsmpInIndex = 0;
5412 framesReady = mFrameCount;
5413 }
5414
5415 if (framesReq > framesReady) {
5416 framesReq = framesReady;
5417 }
5418
5419 if (mChannelCount == 1 && mReqChannelCount == 2) {
5420 channelCount = 1;
5421 } else {
5422 channelCount = 2;
5423 }
5424 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5425 buffer->frameCount = framesReq;
5426 return NO_ERROR;
5427}
5428
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005429// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07005430void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5431{
5432 mRsmpInIndex += buffer->frameCount;
5433 buffer->frameCount = 0;
5434}
5435
5436bool AudioFlinger::RecordThread::checkForNewParameters_l()
5437{
5438 bool reconfig = false;
5439
5440 while (!mNewParameters.isEmpty()) {
5441 status_t status = NO_ERROR;
5442 String8 keyValuePair = mNewParameters[0];
5443 AudioParameter param = AudioParameter(keyValuePair);
5444 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08005445 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005446 int reqSamplingRate = mReqSampleRate;
5447 int reqChannelCount = mReqChannelCount;
5448
5449 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5450 reqSamplingRate = value;
5451 reconfig = true;
5452 }
5453 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08005454 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005455 reconfig = true;
5456 }
5457 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005458 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005459 reconfig = true;
5460 }
5461 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5462 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08005463 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005464 // if frame count is changed after track creation
5465 if (mActiveTrack != 0) {
5466 status = INVALID_OPERATION;
5467 } else {
5468 reconfig = true;
5469 }
5470 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005471 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5472 // forward device change to effects that have requested to be
5473 // aware of attached audio device.
5474 for (size_t i = 0; i < mEffectChains.size(); i++) {
5475 mEffectChains[i]->setDevice_l(value);
5476 }
5477 // store input device and output device but do not forward output device to audio HAL.
5478 // Note that status is ignored by the caller for output device
5479 // (see AudioFlinger::setParameters()
5480 if (value & AUDIO_DEVICE_OUT_ALL) {
5481 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5482 status = BAD_VALUE;
5483 } else {
5484 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07005485 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5486 if (mTrack != NULL) {
5487 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005488 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005489 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5490 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5491 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005492 }
5493 mDevice |= (uint32_t)value;
5494 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005495 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005496 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005497 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005498 mInput->stream->common.standby(&mInput->stream->common);
5499 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5500 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005501 }
5502 if (reconfig) {
5503 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005504 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005505 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005506 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08005507 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
5508 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005509 status = NO_ERROR;
5510 }
5511 if (status == NO_ERROR) {
5512 readInputParameters();
5513 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5514 }
5515 }
5516 }
5517
5518 mNewParameters.removeAt(0);
5519
5520 mParamStatus = status;
5521 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07005522 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5523 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08005524 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005525 }
5526 return reconfig;
5527}
5528
5529String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5530{
Dima Zavinfce7a472011-04-19 22:30:36 -07005531 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005532 String8 out_s8 = String8();
5533
5534 Mutex::Autolock _l(mLock);
5535 if (initCheck() != NO_ERROR) {
5536 return out_s8;
5537 }
Dima Zavinfce7a472011-04-19 22:30:36 -07005538
Dima Zavin799a70e2011-04-18 16:57:27 -07005539 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07005540 out_s8 = String8(s);
5541 free(s);
5542 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005543}
5544
5545void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5546 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08005547 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005548
5549 switch (event) {
5550 case AudioSystem::INPUT_OPENED:
5551 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005552 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005553 desc.samplingRate = mSampleRate;
5554 desc.format = mFormat;
5555 desc.frameCount = mFrameCount;
5556 desc.latency = 0;
5557 param2 = &desc;
5558 break;
5559
5560 case AudioSystem::INPUT_CLOSED:
5561 default:
5562 break;
5563 }
5564 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5565}
5566
5567void AudioFlinger::RecordThread::readInputParameters()
5568{
Glenn Kastene9dd0172012-01-27 18:08:45 -08005569 delete mRsmpInBuffer;
5570 // mRsmpInBuffer is always assigned a new[] below
5571 delete mRsmpOutBuffer;
5572 mRsmpOutBuffer = NULL;
5573 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08005574 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005575
Dima Zavin799a70e2011-04-18 16:57:27 -07005576 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005577 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5578 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07005579 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08005580 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07005581 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005582 mFrameCount = mInputBytes / mFrameSize;
5583 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5584
Glenn Kasten53d76db2012-03-08 12:32:47 -08005585 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005586 {
5587 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005588 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5589 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005590 if (mChannelCount == 1 && mReqChannelCount == 2) {
5591 channelCount = 1;
5592 } else {
5593 channelCount = 2;
5594 }
5595 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5596 mResampler->setSampleRate(mSampleRate);
5597 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5598 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5599
5600 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5601 if (mChannelCount == 1 && mReqChannelCount == 1) {
5602 mFrameCount >>= 1;
5603 }
5604
5605 }
5606 mRsmpInIndex = mFrameCount;
5607}
5608
5609unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5610{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005611 Mutex::Autolock _l(mLock);
5612 if (initCheck() != NO_ERROR) {
5613 return 0;
5614 }
5615
Dima Zavin799a70e2011-04-18 16:57:27 -07005616 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005617}
5618
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005619uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5620{
5621 Mutex::Autolock _l(mLock);
5622 uint32_t result = 0;
5623 if (getEffectChain_l(sessionId) != 0) {
5624 result = EFFECT_SESSION;
5625 }
5626
5627 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5628 result |= TRACK_SESSION;
5629 }
5630
5631 return result;
5632}
5633
Eric Laurent59bd0da2011-08-01 09:52:20 -07005634AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5635{
5636 Mutex::Autolock _l(mLock);
5637 return mTrack;
5638}
5639
Glenn Kastenaed850d2012-01-26 09:46:34 -08005640AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005641{
5642 Mutex::Autolock _l(mLock);
5643 return mInput;
5644}
5645
5646AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5647{
5648 Mutex::Autolock _l(mLock);
5649 AudioStreamIn *input = mInput;
5650 mInput = NULL;
5651 return input;
5652}
5653
5654// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08005655audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005656{
5657 if (mInput == NULL) {
5658 return NULL;
5659 }
5660 return &mInput->stream->common;
5661}
5662
5663
Mathias Agopian65ab4712010-07-14 17:59:35 -07005664// ----------------------------------------------------------------------------
5665
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005666audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005667 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005668 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005669 uint32_t *pChannels,
5670 uint32_t *pLatencyMs,
Glenn Kasten18868c52012-03-07 09:15:37 -08005671 audio_policy_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005672{
5673 status_t status;
5674 PlaybackThread *thread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005675 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005676 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005677 uint32_t channels = pChannels ? *pChannels : 0;
5678 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07005679 audio_stream_out_t *outStream;
5680 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005681
Steve Block3856b092011-10-20 11:56:00 +01005682 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07005683 pDevices ? *pDevices : 0,
5684 samplingRate,
5685 format,
5686 channels,
5687 flags);
5688
5689 if (pDevices == NULL || *pDevices == 0) {
5690 return 0;
5691 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005692
Mathias Agopian65ab4712010-07-14 17:59:35 -07005693 Mutex::Autolock _l(mLock);
5694
Dima Zavin799a70e2011-04-18 16:57:27 -07005695 outHwDev = findSuitableHwDev_l(*pDevices);
5696 if (outHwDev == NULL)
5697 return 0;
5698
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005699 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Glenn Kasten58f30212012-01-12 12:27:51 -08005700 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005701 &channels, &samplingRate, &outStream);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005702 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01005703 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005704 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005705 samplingRate,
5706 format,
5707 channels,
5708 status);
5709
Dima Zavin799a70e2011-04-18 16:57:27 -07005710 if (outStream != NULL) {
5711 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005712 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07005713
Dima Zavinfce7a472011-04-19 22:30:36 -07005714 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5715 (format != AUDIO_FORMAT_PCM_16_BIT) ||
5716 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005717 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005718 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005719 } else {
5720 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005721 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005722 }
5723 mPlaybackThreads.add(id, thread);
5724
Glenn Kastena0d68332012-01-27 16:47:15 -08005725 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5726 if (pFormat != NULL) *pFormat = format;
5727 if (pChannels != NULL) *pChannels = channels;
5728 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005729
5730 // notify client processes of the new output creation
5731 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5732 return id;
5733 }
5734
5735 return 0;
5736}
5737
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005738audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
5739 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005740{
5741 Mutex::Autolock _l(mLock);
5742 MixerThread *thread1 = checkMixerThread_l(output1);
5743 MixerThread *thread2 = checkMixerThread_l(output2);
5744
5745 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005746 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005747 return 0;
5748 }
5749
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005750 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005751 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5752 thread->addOutputTrack(thread2);
5753 mPlaybackThreads.add(id, thread);
5754 // notify client processes of the new output creation
5755 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5756 return id;
5757}
5758
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005759status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005760{
5761 // keep strong reference on the playback thread so that
5762 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005763 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005764 {
5765 Mutex::Autolock _l(mLock);
5766 thread = checkPlaybackThread_l(output);
5767 if (thread == NULL) {
5768 return BAD_VALUE;
5769 }
5770
Steve Block3856b092011-10-20 11:56:00 +01005771 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005772
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005773 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005774 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005775 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005776 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5777 dupThread->removeOutputTrack((MixerThread *)thread.get());
5778 }
5779 }
5780 }
Glenn Kastena1117922012-01-26 10:53:32 -08005781 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005782 mPlaybackThreads.removeItem(output);
5783 }
5784 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005785 // The thread entity (active unit of execution) is no longer running here,
5786 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005787
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005788 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005789 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005790 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005791 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005792 out->hwDev->close_output_stream(out->hwDev, out->stream);
5793 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005794 }
5795 return NO_ERROR;
5796}
5797
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005798status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005799{
5800 Mutex::Autolock _l(mLock);
5801 PlaybackThread *thread = checkPlaybackThread_l(output);
5802
5803 if (thread == NULL) {
5804 return BAD_VALUE;
5805 }
5806
Steve Block3856b092011-10-20 11:56:00 +01005807 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005808 thread->suspend();
5809
5810 return NO_ERROR;
5811}
5812
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005813status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005814{
5815 Mutex::Autolock _l(mLock);
5816 PlaybackThread *thread = checkPlaybackThread_l(output);
5817
5818 if (thread == NULL) {
5819 return BAD_VALUE;
5820 }
5821
Steve Block3856b092011-10-20 11:56:00 +01005822 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005823
5824 thread->restore();
5825
5826 return NO_ERROR;
5827}
5828
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005829audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005830 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005831 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005832 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005833 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005834{
5835 status_t status;
5836 RecordThread *thread = NULL;
5837 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005838 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005839 uint32_t channels = pChannels ? *pChannels : 0;
5840 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005841 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005842 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005843 audio_stream_in_t *inStream;
5844 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005845
5846 if (pDevices == NULL || *pDevices == 0) {
5847 return 0;
5848 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005849
Mathias Agopian65ab4712010-07-14 17:59:35 -07005850 Mutex::Autolock _l(mLock);
5851
Dima Zavin799a70e2011-04-18 16:57:27 -07005852 inHwDev = findSuitableHwDev_l(*pDevices);
5853 if (inHwDev == NULL)
5854 return 0;
5855
Glenn Kasten58f30212012-01-12 12:27:51 -08005856 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005857 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005858 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005859 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005860 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005861 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005862 samplingRate,
5863 format,
5864 channels,
5865 acoustics,
5866 status);
5867
5868 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5869 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5870 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005871 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005872 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005873 (samplingRate <= 2 * reqSamplingRate) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08005874 (popcount(channels) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01005875 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005876 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005877 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005878 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005879 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005880 }
5881
Dima Zavin799a70e2011-04-18 16:57:27 -07005882 if (inStream != NULL) {
5883 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5884
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005885 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005886 // Start record thread
5887 // RecorThread require both input and output device indication to forward to audio
5888 // pre processing modules
5889 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5890 thread = new RecordThread(this,
5891 input,
5892 reqSamplingRate,
5893 reqChannels,
5894 id,
5895 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005896 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005897 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005898 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5899 if (pFormat != NULL) *pFormat = format;
5900 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005901
Dima Zavin799a70e2011-04-18 16:57:27 -07005902 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005903
5904 // notify client processes of the new input creation
5905 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5906 return id;
5907 }
5908
5909 return 0;
5910}
5911
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005912status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005913{
5914 // keep strong reference on the record thread so that
5915 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005916 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005917 {
5918 Mutex::Autolock _l(mLock);
5919 thread = checkRecordThread_l(input);
5920 if (thread == NULL) {
5921 return BAD_VALUE;
5922 }
5923
Steve Block3856b092011-10-20 11:56:00 +01005924 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08005925 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005926 mRecordThreads.removeItem(input);
5927 }
5928 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005929 // The thread entity (active unit of execution) is no longer running here,
5930 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005931
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005932 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005933 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005934 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005935 in->hwDev->close_input_stream(in->hwDev, in->stream);
5936 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005937
5938 return NO_ERROR;
5939}
5940
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005941status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005942{
5943 Mutex::Autolock _l(mLock);
5944 MixerThread *dstThread = checkMixerThread_l(output);
5945 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005946 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005947 return BAD_VALUE;
5948 }
5949
Steve Block3856b092011-10-20 11:56:00 +01005950 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005951 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5952
5953 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5954 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08005955 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005956 MixerThread *srcThread = (MixerThread *)thread;
5957 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005958 }
Eric Laurentde070132010-07-13 04:45:46 -07005959 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005960
5961 return NO_ERROR;
5962}
5963
5964
5965int AudioFlinger::newAudioSessionId()
5966{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005967 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005968}
5969
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005970void AudioFlinger::acquireAudioSessionId(int audioSession)
5971{
5972 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005973 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005974 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005975 size_t num = mAudioSessionRefs.size();
5976 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005977 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005978 if (ref->mSessionid == audioSession && ref->mPid == caller) {
5979 ref->mCnt++;
5980 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005981 return;
5982 }
5983 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005984 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5985 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005986}
5987
5988void AudioFlinger::releaseAudioSessionId(int audioSession)
5989{
5990 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005991 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005992 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005993 size_t num = mAudioSessionRefs.size();
5994 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005995 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005996 if (ref->mSessionid == audioSession && ref->mPid == caller) {
5997 ref->mCnt--;
5998 ALOGV(" decremented refcount to %d", ref->mCnt);
5999 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006000 mAudioSessionRefs.removeAt(i);
6001 delete ref;
6002 purgeStaleEffects_l();
6003 }
6004 return;
6005 }
6006 }
Steve Block5ff1dd52012-01-05 23:22:43 +00006007 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006008}
6009
6010void AudioFlinger::purgeStaleEffects_l() {
6011
Steve Block3856b092011-10-20 11:56:00 +01006012 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006013
6014 Vector< sp<EffectChain> > chains;
6015
6016 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6017 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
6018 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6019 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07006020 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
6021 chains.push(ec);
6022 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006023 }
6024 }
6025 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6026 sp<RecordThread> t = mRecordThreads.valueAt(i);
6027 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6028 sp<EffectChain> ec = t->mEffectChains[j];
6029 chains.push(ec);
6030 }
6031 }
6032
6033 for (size_t i = 0; i < chains.size(); i++) {
6034 sp<EffectChain> ec = chains[i];
6035 int sessionid = ec->sessionId();
6036 sp<ThreadBase> t = ec->mThread.promote();
6037 if (t == 0) {
6038 continue;
6039 }
6040 size_t numsessionrefs = mAudioSessionRefs.size();
6041 bool found = false;
6042 for (size_t k = 0; k < numsessionrefs; k++) {
6043 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006044 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01006045 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006046 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006047 found = true;
6048 break;
6049 }
6050 }
6051 if (!found) {
6052 // remove all effects from the chain
6053 while (ec->mEffects.size()) {
6054 sp<EffectModule> effect = ec->mEffects[0];
6055 effect->unPin();
6056 Mutex::Autolock _l (t->mLock);
6057 t->removeEffect_l(effect);
6058 for (size_t j = 0; j < effect->mHandles.size(); j++) {
6059 sp<EffectHandle> handle = effect->mHandles[j].promote();
6060 if (handle != 0) {
6061 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07006062 if (handle->mHasControl && handle->mEnabled) {
6063 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
6064 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006065 }
6066 }
6067 AudioSystem::unregisterEffect(effect->id());
6068 }
6069 }
6070 }
6071 return;
6072}
6073
Mathias Agopian65ab4712010-07-14 17:59:35 -07006074// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006075AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006076{
Glenn Kastena1117922012-01-26 10:53:32 -08006077 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006078}
6079
6080// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006081AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006082{
6083 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08006084 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006085}
6086
6087// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006088AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006089{
Glenn Kastena1117922012-01-26 10:53:32 -08006090 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006091}
6092
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006093uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07006094{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006095 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006096}
6097
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006098AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006099{
6100 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6101 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006102 AudioStreamOut *output = thread->getOutput();
6103 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006104 return thread;
6105 }
6106 }
6107 return NULL;
6108}
6109
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006110uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006111{
6112 PlaybackThread *thread = primaryPlaybackThread_l();
6113
6114 if (thread == NULL) {
6115 return 0;
6116 }
6117
6118 return thread->device();
6119}
6120
Eric Laurenta011e352012-03-29 15:51:43 -07006121sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
6122 int triggerSession,
6123 int listenerSession,
6124 sync_event_callback_t callBack,
6125 void *cookie)
6126{
6127 Mutex::Autolock _l(mLock);
6128
6129 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
6130 status_t playStatus = NAME_NOT_FOUND;
6131 status_t recStatus = NAME_NOT_FOUND;
6132 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6133 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
6134 if (playStatus == NO_ERROR) {
6135 return event;
6136 }
6137 }
6138 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6139 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
6140 if (recStatus == NO_ERROR) {
6141 return event;
6142 }
6143 }
6144 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
6145 mPendingSyncEvents.add(event);
6146 } else {
6147 ALOGV("createSyncEvent() invalid event %d", event->type());
6148 event.clear();
6149 }
6150 return event;
6151}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006152
Mathias Agopian65ab4712010-07-14 17:59:35 -07006153// ----------------------------------------------------------------------------
6154// Effect management
6155// ----------------------------------------------------------------------------
6156
6157
Glenn Kastenf587ba52012-01-26 16:25:10 -08006158status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006159{
6160 Mutex::Autolock _l(mLock);
6161 return EffectQueryNumberEffects(numEffects);
6162}
6163
Glenn Kastenf587ba52012-01-26 16:25:10 -08006164status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006165{
6166 Mutex::Autolock _l(mLock);
6167 return EffectQueryEffect(index, descriptor);
6168}
6169
Glenn Kasten5e92a782012-01-30 07:40:52 -08006170status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08006171 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006172{
6173 Mutex::Autolock _l(mLock);
6174 return EffectGetDescriptor(pUuid, descriptor);
6175}
6176
6177
Mathias Agopian65ab4712010-07-14 17:59:35 -07006178sp<IEffect> AudioFlinger::createEffect(pid_t pid,
6179 effect_descriptor_t *pDesc,
6180 const sp<IEffectClient>& effectClient,
6181 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006182 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006183 int sessionId,
6184 status_t *status,
6185 int *id,
6186 int *enabled)
6187{
6188 status_t lStatus = NO_ERROR;
6189 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006190 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006191
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006192 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006193 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006194
6195 if (pDesc == NULL) {
6196 lStatus = BAD_VALUE;
6197 goto Exit;
6198 }
6199
Eric Laurent84e9a102010-09-23 16:10:16 -07006200 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006201 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006202 lStatus = PERMISSION_DENIED;
6203 goto Exit;
6204 }
6205
Dima Zavinfce7a472011-04-19 22:30:36 -07006206 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07006207 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08006208 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006209 lStatus = PERMISSION_DENIED;
6210 goto Exit;
6211 }
6212
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006213 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006214 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006215 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07006216 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07006217 lStatus = BAD_VALUE;
6218 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07006219 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006220 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006221 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07006222 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006223 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07006224 }
6225 }
6226
Mathias Agopian65ab4712010-07-14 17:59:35 -07006227 {
6228 Mutex::Autolock _l(mLock);
6229
Mathias Agopian65ab4712010-07-14 17:59:35 -07006230
6231 if (!EffectIsNullUuid(&pDesc->uuid)) {
6232 // if uuid is specified, request effect descriptor
6233 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
6234 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006235 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006236 goto Exit;
6237 }
6238 } else {
6239 // if uuid is not specified, look for an available implementation
6240 // of the required type in effect factory
6241 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006242 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006243 lStatus = BAD_VALUE;
6244 goto Exit;
6245 }
6246 uint32_t numEffects = 0;
6247 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006248 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07006249 bool found = false;
6250
6251 lStatus = EffectQueryNumberEffects(&numEffects);
6252 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006253 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006254 goto Exit;
6255 }
6256 for (uint32_t i = 0; i < numEffects; i++) {
6257 lStatus = EffectQueryEffect(i, &desc);
6258 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006259 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006260 continue;
6261 }
6262 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
6263 // If matching type found save effect descriptor. If the session is
6264 // 0 and the effect is not auxiliary, continue enumeration in case
6265 // an auxiliary version of this effect type is available
6266 found = true;
6267 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07006268 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006269 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6270 break;
6271 }
6272 }
6273 }
6274 if (!found) {
6275 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00006276 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006277 goto Exit;
6278 }
6279 // For same effect type, chose auxiliary version over insert version if
6280 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07006281 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006282 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
6283 memcpy(&desc, &d, sizeof(effect_descriptor_t));
6284 }
6285 }
6286
6287 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07006288 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006289 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6290 lStatus = INVALID_OPERATION;
6291 goto Exit;
6292 }
6293
Eric Laurent59255e42011-07-27 19:49:51 -07006294 // check recording permission for visualizer
6295 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
6296 !recordingAllowed()) {
6297 lStatus = PERMISSION_DENIED;
6298 goto Exit;
6299 }
6300
Mathias Agopian65ab4712010-07-14 17:59:35 -07006301 // return effect descriptor
6302 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
6303
6304 // If output is not specified try to find a matching audio session ID in one of the
6305 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07006306 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
6307 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006308 // Note: io is never 0 when creating an effect on an input
6309 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006310 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07006311 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6312 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006313 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07006314 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07006315 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006316 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006317 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006318 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6319 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6320 io = mRecordThreads.keyAt(i);
6321 break;
6322 }
6323 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006324 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006325 // If no output thread contains the requested session ID, default to
6326 // first output. The effect chain will be moved to the correct output
6327 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006328 if (io == 0 && mPlaybackThreads.size()) {
6329 io = mPlaybackThreads.keyAt(0);
6330 }
Steve Block3856b092011-10-20 11:56:00 +01006331 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006332 }
6333 ThreadBase *thread = checkRecordThread_l(io);
6334 if (thread == NULL) {
6335 thread = checkPlaybackThread_l(io);
6336 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00006337 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006338 lStatus = BAD_VALUE;
6339 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07006340 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006341 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006342
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006343 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006344
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006345 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07006346 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6347 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006348 if (handle != 0 && id != NULL) {
6349 *id = handle->id();
6350 }
6351 }
6352
6353Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006354 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006355 *status = lStatus;
6356 }
6357 return handle;
6358}
6359
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006360status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
6361 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07006362{
Steve Block3856b092011-10-20 11:56:00 +01006363 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07006364 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006365 Mutex::Autolock _l(mLock);
6366 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006367 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006368 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006369 }
Eric Laurentde070132010-07-13 04:45:46 -07006370 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6371 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006372 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006373 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006374 }
Eric Laurentde070132010-07-13 04:45:46 -07006375 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6376 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006377 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006378 return BAD_VALUE;
6379 }
6380
6381 Mutex::Autolock _dl(dstThread->mLock);
6382 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07006383 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07006384
Mathias Agopian65ab4712010-07-14 17:59:35 -07006385 return NO_ERROR;
6386}
6387
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006388// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07006389status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07006390 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07006391 AudioFlinger::PlaybackThread *dstThread,
6392 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07006393{
Steve Block3856b092011-10-20 11:56:00 +01006394 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006395 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07006396
Eric Laurent59255e42011-07-27 19:49:51 -07006397 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006398 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006399 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006400 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07006401 return INVALID_OPERATION;
6402 }
6403
Eric Laurent39e94f82010-07-28 01:32:47 -07006404 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07006405 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07006406 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07006407 // removed.
6408 srcThread->removeEffectChain_l(chain);
6409
6410 // transfer all effects one by one so that new effect chain is created on new thread with
6411 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006412 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07006413 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006414 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07006415 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6416 while (effect != 0) {
6417 srcThread->removeEffect_l(effect);
6418 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07006419 // removeEffect_l() has stopped the effect if it was active so it must be restarted
6420 if (effect->state() == EffectModule::ACTIVE ||
6421 effect->state() == EffectModule::STOPPING) {
6422 effect->start();
6423 }
Eric Laurent39e94f82010-07-28 01:32:47 -07006424 // if the move request is not received from audio policy manager, the effect must be
6425 // re-registered with the new strategy and output
6426 if (dstChain == 0) {
6427 dstChain = effect->chain().promote();
6428 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006429 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07006430 srcThread->addEffect_l(effect);
6431 return NO_INIT;
6432 }
6433 strategy = dstChain->strategy();
6434 }
6435 if (reRegister) {
6436 AudioSystem::unregisterEffect(effect->id());
6437 AudioSystem::registerEffect(&effect->desc(),
6438 dstOutput,
6439 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07006440 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07006441 effect->id());
6442 }
Eric Laurentde070132010-07-13 04:45:46 -07006443 effect = chain->getEffectFromId_l(0);
6444 }
6445
6446 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006447}
6448
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006449
Mathias Agopian65ab4712010-07-14 17:59:35 -07006450// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006451sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07006452 const sp<AudioFlinger::Client>& client,
6453 const sp<IEffectClient>& effectClient,
6454 int32_t priority,
6455 int sessionId,
6456 effect_descriptor_t *desc,
6457 int *enabled,
6458 status_t *status
6459 )
6460{
6461 sp<EffectModule> effect;
6462 sp<EffectHandle> handle;
6463 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006464 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07006465 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006466 bool effectCreated = false;
6467 bool effectRegistered = false;
6468
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006469 lStatus = initCheck();
6470 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006471 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006472 goto Exit;
6473 }
6474
6475 // Do not allow effects with session ID 0 on direct output or duplicating threads
6476 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07006477 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006478 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07006479 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006480 lStatus = BAD_VALUE;
6481 goto Exit;
6482 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006483 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08006484 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006485 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006486 desc->name, desc->flags, mType);
6487 lStatus = BAD_VALUE;
6488 goto Exit;
6489 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006490
Steve Block3856b092011-10-20 11:56:00 +01006491 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006492
6493 { // scope for mLock
6494 Mutex::Autolock _l(mLock);
6495
6496 // check for existing effect chain with the requested audio session
6497 chain = getEffectChain_l(sessionId);
6498 if (chain == 0) {
6499 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006500 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006501 chain = new EffectChain(this, sessionId);
6502 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07006503 chain->setStrategy(getStrategyForSession_l(sessionId));
6504 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006505 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07006506 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006507 }
6508
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08006509 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006510
6511 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006512 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006513 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07006514 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006515 if (lStatus != NO_ERROR) {
6516 goto Exit;
6517 }
6518 effectRegistered = true;
6519 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07006520 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006521 lStatus = effect->status();
6522 if (lStatus != NO_ERROR) {
6523 goto Exit;
6524 }
Eric Laurentcab11242010-07-15 12:50:15 -07006525 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006526 if (lStatus != NO_ERROR) {
6527 goto Exit;
6528 }
6529 effectCreated = true;
6530
6531 effect->setDevice(mDevice);
6532 effect->setMode(mAudioFlinger->getMode());
6533 }
6534 // create effect handle and connect it to effect module
6535 handle = new EffectHandle(effect, client, effectClient, priority);
6536 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08006537 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006538 *enabled = (int)effect->isEnabled();
6539 }
6540 }
6541
6542Exit:
6543 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07006544 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006545 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07006546 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006547 }
6548 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07006549 AudioSystem::unregisterEffect(effect->id());
6550 }
6551 if (chainCreated) {
6552 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006553 }
6554 handle.clear();
6555 }
6556
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006557 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006558 *status = lStatus;
6559 }
6560 return handle;
6561}
6562
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006563sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6564{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006565 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08006566 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006567}
6568
Eric Laurentde070132010-07-13 04:45:46 -07006569// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6570// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006571status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07006572{
6573 // check for existing effect chain with the requested audio session
6574 int sessionId = effect->sessionId();
6575 sp<EffectChain> chain = getEffectChain_l(sessionId);
6576 bool chainCreated = false;
6577
6578 if (chain == 0) {
6579 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006580 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006581 chain = new EffectChain(this, sessionId);
6582 addEffectChain_l(chain);
6583 chain->setStrategy(getStrategyForSession_l(sessionId));
6584 chainCreated = true;
6585 }
Steve Block3856b092011-10-20 11:56:00 +01006586 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006587
6588 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006589 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07006590 this, effect->desc().name, chain.get());
6591 return BAD_VALUE;
6592 }
6593
6594 status_t status = chain->addEffect_l(effect);
6595 if (status != NO_ERROR) {
6596 if (chainCreated) {
6597 removeEffectChain_l(chain);
6598 }
6599 return status;
6600 }
6601
6602 effect->setDevice(mDevice);
6603 effect->setMode(mAudioFlinger->getMode());
6604 return NO_ERROR;
6605}
6606
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006607void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07006608
Steve Block3856b092011-10-20 11:56:00 +01006609 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006610 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07006611 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6612 detachAuxEffect_l(effect->id());
6613 }
6614
6615 sp<EffectChain> chain = effect->chain().promote();
6616 if (chain != 0) {
6617 // remove effect chain if removing last effect
6618 if (chain->removeEffect_l(effect) == 0) {
6619 removeEffectChain_l(chain);
6620 }
6621 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00006622 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006623 }
6624}
6625
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006626void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006627 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006628{
6629 effectChains = mEffectChains;
6630 for (size_t i = 0; i < mEffectChains.size(); i++) {
6631 mEffectChains[i]->lock();
6632 }
6633}
6634
6635void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006636 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006637{
6638 for (size_t i = 0; i < effectChains.size(); i++) {
6639 effectChains[i]->unlock();
6640 }
6641}
6642
6643sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6644{
6645 Mutex::Autolock _l(mLock);
6646 return getEffectChain_l(sessionId);
6647}
6648
6649sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6650{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006651 size_t size = mEffectChains.size();
6652 for (size_t i = 0; i < size; i++) {
6653 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08006654 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006655 }
6656 }
Glenn Kasten090f0192012-01-30 13:00:02 -08006657 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006658}
6659
Glenn Kastenf78aee72012-01-04 11:00:47 -08006660void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006661{
6662 Mutex::Autolock _l(mLock);
6663 size_t size = mEffectChains.size();
6664 for (size_t i = 0; i < size; i++) {
6665 mEffectChains[i]->setMode_l(mode);
6666 }
6667}
6668
6669void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006670 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08006671 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07006672
Mathias Agopian65ab4712010-07-14 17:59:35 -07006673 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006674 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006675 // delete the effect module if removing last handle on it
6676 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006677 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006678 removeEffect_l(effect);
6679 AudioSystem::unregisterEffect(effect->id());
6680 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006681 }
6682}
6683
6684status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6685{
6686 int session = chain->sessionId();
6687 int16_t *buffer = mMixBuffer;
6688 bool ownsBuffer = false;
6689
Steve Block3856b092011-10-20 11:56:00 +01006690 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006691 if (session > 0) {
6692 // Only one effect chain can be present in direct output thread and it uses
6693 // the mix buffer as input
6694 if (mType != DIRECT) {
6695 size_t numSamples = mFrameCount * mChannelCount;
6696 buffer = new int16_t[numSamples];
6697 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01006698 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006699 ownsBuffer = true;
6700 }
6701
6702 // Attach all tracks with same session ID to this chain.
6703 for (size_t i = 0; i < mTracks.size(); ++i) {
6704 sp<Track> track = mTracks[i];
6705 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006706 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006707 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006708 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006709 }
6710 }
6711
6712 // indicate all active tracks in the chain
6713 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6714 sp<Track> track = mActiveTracks[i].promote();
6715 if (track == 0) continue;
6716 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006717 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07006718 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006719 }
6720 }
6721 }
6722
6723 chain->setInBuffer(buffer, ownsBuffer);
6724 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006725 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006726 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006727 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6728 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006729 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006730 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6731 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006732 // Effect chain for other sessions are inserted at beginning of effect
6733 // chains list to be processed before output mix effects. Relative order between other
6734 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006735 size_t size = mEffectChains.size();
6736 size_t i = 0;
6737 for (i = 0; i < size; i++) {
6738 if (mEffectChains[i]->sessionId() < session) break;
6739 }
6740 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006741 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006742
6743 return NO_ERROR;
6744}
6745
6746size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6747{
6748 int session = chain->sessionId();
6749
Steve Block3856b092011-10-20 11:56:00 +01006750 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006751
6752 for (size_t i = 0; i < mEffectChains.size(); i++) {
6753 if (chain == mEffectChains[i]) {
6754 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006755 // detach all active tracks from the chain
6756 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6757 sp<Track> track = mActiveTracks[i].promote();
6758 if (track == 0) continue;
6759 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006760 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006761 chain.get(), session);
6762 chain->decActiveTrackCnt();
6763 }
6764 }
6765
Mathias Agopian65ab4712010-07-14 17:59:35 -07006766 // detach all tracks with same session ID from this chain
6767 for (size_t i = 0; i < mTracks.size(); ++i) {
6768 sp<Track> track = mTracks[i];
6769 if (session == track->sessionId()) {
6770 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006771 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006772 }
6773 }
Eric Laurentde070132010-07-13 04:45:46 -07006774 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006775 }
6776 }
6777 return mEffectChains.size();
6778}
6779
Eric Laurentde070132010-07-13 04:45:46 -07006780status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6781 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006782{
6783 Mutex::Autolock _l(mLock);
6784 return attachAuxEffect_l(track, EffectId);
6785}
6786
Eric Laurentde070132010-07-13 04:45:46 -07006787status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6788 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006789{
6790 status_t status = NO_ERROR;
6791
6792 if (EffectId == 0) {
6793 track->setAuxBuffer(0, NULL);
6794 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006795 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6796 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006797 if (effect != 0) {
6798 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6799 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6800 } else {
6801 status = INVALID_OPERATION;
6802 }
6803 } else {
6804 status = BAD_VALUE;
6805 }
6806 }
6807 return status;
6808}
6809
6810void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6811{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006812 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006813 sp<Track> track = mTracks[i];
6814 if (track->auxEffectId() == effectId) {
6815 attachAuxEffect_l(track, 0);
6816 }
6817 }
6818}
6819
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006820status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6821{
6822 // only one chain per input thread
6823 if (mEffectChains.size() != 0) {
6824 return INVALID_OPERATION;
6825 }
Steve Block3856b092011-10-20 11:56:00 +01006826 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006827
6828 chain->setInBuffer(NULL);
6829 chain->setOutBuffer(NULL);
6830
Eric Laurent59255e42011-07-27 19:49:51 -07006831 checkSuspendOnAddEffectChain_l(chain);
6832
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006833 mEffectChains.add(chain);
6834
6835 return NO_ERROR;
6836}
6837
6838size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6839{
Steve Block3856b092011-10-20 11:56:00 +01006840 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006841 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006842 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6843 chain.get(), mEffectChains.size(), this);
6844 if (mEffectChains.size() == 1) {
6845 mEffectChains.removeAt(0);
6846 }
6847 return 0;
6848}
6849
Mathias Agopian65ab4712010-07-14 17:59:35 -07006850// ----------------------------------------------------------------------------
6851// EffectModule implementation
6852// ----------------------------------------------------------------------------
6853
6854#undef LOG_TAG
6855#define LOG_TAG "AudioFlinger::EffectModule"
6856
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006857AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006858 const wp<AudioFlinger::EffectChain>& chain,
6859 effect_descriptor_t *desc,
6860 int id,
6861 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006862 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006863 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006864{
Steve Block3856b092011-10-20 11:56:00 +01006865 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006866 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006867 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006868 return;
6869 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006870
6871 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6872
6873 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006874 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006875
6876 if (mStatus != NO_ERROR) {
6877 return;
6878 }
6879 lStatus = init();
6880 if (lStatus < 0) {
6881 mStatus = lStatus;
6882 goto Error;
6883 }
6884
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006885 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6886 mPinned = true;
6887 }
Steve Block3856b092011-10-20 11:56:00 +01006888 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006889 return;
6890Error:
6891 EffectRelease(mEffectInterface);
6892 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006893 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006894}
6895
6896AudioFlinger::EffectModule::~EffectModule()
6897{
Steve Block3856b092011-10-20 11:56:00 +01006898 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006899 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006900 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6901 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6902 sp<ThreadBase> thread = mThread.promote();
6903 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006904 audio_stream_t *stream = thread->stream();
6905 if (stream != NULL) {
6906 stream->remove_audio_effect(stream, mEffectInterface);
6907 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006908 }
6909 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006910 // release effect engine
6911 EffectRelease(mEffectInterface);
6912 }
6913}
6914
Glenn Kasten435dbe62012-01-30 10:15:48 -08006915status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006916{
6917 status_t status;
6918
6919 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006920 int priority = handle->priority();
6921 size_t size = mHandles.size();
6922 sp<EffectHandle> h;
6923 size_t i;
6924 for (i = 0; i < size; i++) {
6925 h = mHandles[i].promote();
6926 if (h == 0) continue;
6927 if (h->priority() <= priority) break;
6928 }
6929 // if inserted in first place, move effect control from previous owner to this handle
6930 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006931 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006932 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006933 enabled = h->enabled();
6934 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006935 }
Eric Laurent59255e42011-07-27 19:49:51 -07006936 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006937 status = NO_ERROR;
6938 } else {
6939 status = ALREADY_EXISTS;
6940 }
Steve Block3856b092011-10-20 11:56:00 +01006941 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006942 mHandles.insertAt(handle, i);
6943 return status;
6944}
6945
6946size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6947{
6948 Mutex::Autolock _l(mLock);
6949 size_t size = mHandles.size();
6950 size_t i;
6951 for (i = 0; i < size; i++) {
6952 if (mHandles[i] == handle) break;
6953 }
6954 if (i == size) {
6955 return size;
6956 }
Steve Block3856b092011-10-20 11:56:00 +01006957 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006958
6959 bool enabled = false;
6960 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006961 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006962 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006963 enabled = hdl->enabled();
6964 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006965 mHandles.removeAt(i);
6966 size = mHandles.size();
6967 // if removed from first place, move effect control from this handle to next in line
6968 if (i == 0 && size != 0) {
6969 sp<EffectHandle> h = mHandles[0].promote();
6970 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006971 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006972 }
6973 }
6974
Eric Laurentec437d82011-07-26 20:54:46 -07006975 // Prevent calls to process() and other functions on effect interface from now on.
6976 // The effect engine will be released by the destructor when the last strong reference on
6977 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006978 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006979 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006980 }
6981
Mathias Agopian65ab4712010-07-14 17:59:35 -07006982 return size;
6983}
6984
Eric Laurent59255e42011-07-27 19:49:51 -07006985sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6986{
6987 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08006988 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07006989}
6990
Glenn Kasten58123c32012-02-03 10:32:24 -08006991void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006992{
Glenn Kasten90bebef2012-01-27 15:24:38 -08006993 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006994 // keep a strong reference on this EffectModule to avoid calling the
6995 // destructor before we exit
6996 sp<EffectModule> keep(this);
6997 {
6998 sp<ThreadBase> thread = mThread.promote();
6999 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007000 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007001 }
7002 }
7003}
7004
7005void AudioFlinger::EffectModule::updateState() {
7006 Mutex::Autolock _l(mLock);
7007
7008 switch (mState) {
7009 case RESTART:
7010 reset_l();
7011 // FALL THROUGH
7012
7013 case STARTING:
7014 // clear auxiliary effect input buffer for next accumulation
7015 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7016 memset(mConfig.inputCfg.buffer.raw,
7017 0,
7018 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
7019 }
7020 start_l();
7021 mState = ACTIVE;
7022 break;
7023 case STOPPING:
7024 stop_l();
7025 mDisableWaitCnt = mMaxDisableWaitCnt;
7026 mState = STOPPED;
7027 break;
7028 case STOPPED:
7029 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
7030 // turn off sequence.
7031 if (--mDisableWaitCnt == 0) {
7032 reset_l();
7033 mState = IDLE;
7034 }
7035 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007036 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07007037 break;
7038 }
7039}
7040
7041void AudioFlinger::EffectModule::process()
7042{
7043 Mutex::Autolock _l(mLock);
7044
Eric Laurentec437d82011-07-26 20:54:46 -07007045 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007046 mConfig.inputCfg.buffer.raw == NULL ||
7047 mConfig.outputCfg.buffer.raw == NULL) {
7048 return;
7049 }
7050
Eric Laurent8f45bd72010-08-31 13:50:07 -07007051 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007052 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
7053 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08007054 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007055 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07007056 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007057 }
7058
7059 // do the actual processing in the effect engine
7060 int ret = (*mEffectInterface)->process(mEffectInterface,
7061 &mConfig.inputCfg.buffer,
7062 &mConfig.outputCfg.buffer);
7063
7064 // force transition to IDLE state when engine is ready
7065 if (mState == STOPPED && ret == -ENODATA) {
7066 mDisableWaitCnt = 1;
7067 }
7068
7069 // clear auxiliary effect input buffer for next accumulation
7070 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08007071 memset(mConfig.inputCfg.buffer.raw, 0,
7072 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007073 }
7074 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08007075 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7076 // If an insert effect is idle and input buffer is different from output buffer,
7077 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07007078 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07007079 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08007080 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
7081 int16_t *in = mConfig.inputCfg.buffer.s16;
7082 int16_t *out = mConfig.outputCfg.buffer.s16;
7083 for (size_t i = 0; i < frameCnt; i++) {
7084 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007085 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007086 }
7087 }
7088}
7089
7090void AudioFlinger::EffectModule::reset_l()
7091{
7092 if (mEffectInterface == NULL) {
7093 return;
7094 }
7095 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
7096}
7097
7098status_t AudioFlinger::EffectModule::configure()
7099{
7100 uint32_t channels;
7101 if (mEffectInterface == NULL) {
7102 return NO_INIT;
7103 }
7104
7105 sp<ThreadBase> thread = mThread.promote();
7106 if (thread == 0) {
7107 return DEAD_OBJECT;
7108 }
7109
7110 // TODO: handle configuration of effects replacing track process
7111 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007112 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007113 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07007114 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007115 }
7116
7117 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007118 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007119 } else {
7120 mConfig.inputCfg.channels = channels;
7121 }
7122 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07007123 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
7124 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007125 mConfig.inputCfg.samplingRate = thread->sampleRate();
7126 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
7127 mConfig.inputCfg.bufferProvider.cookie = NULL;
7128 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
7129 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
7130 mConfig.outputCfg.bufferProvider.cookie = NULL;
7131 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
7132 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
7133 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
7134 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07007135 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07007136 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07007137 // - in other sessions:
7138 // last effect in the chain accumulates in output buffer: input buffer != output buffer
7139 // other effect: overwrites output buffer: input buffer == output buffer
7140 // Auxiliary effect:
7141 // accumulates in output buffer: input buffer != output buffer
7142 // Therefore: accumulate <=> input buffer != output buffer
7143 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7144 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
7145 } else {
7146 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
7147 }
7148 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
7149 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
7150 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
7151 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
7152
Steve Block3856b092011-10-20 11:56:00 +01007153 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07007154 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
7155
Mathias Agopian65ab4712010-07-14 17:59:35 -07007156 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007157 uint32_t size = sizeof(int);
7158 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08007159 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07007160 sizeof(effect_config_t),
7161 &mConfig,
7162 &size,
7163 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007164 if (status == 0) {
7165 status = cmdStatus;
7166 }
7167
7168 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
7169 (1000 * mConfig.outputCfg.buffer.frameCount);
7170
7171 return status;
7172}
7173
7174status_t AudioFlinger::EffectModule::init()
7175{
7176 Mutex::Autolock _l(mLock);
7177 if (mEffectInterface == NULL) {
7178 return NO_INIT;
7179 }
7180 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007181 uint32_t size = sizeof(status_t);
7182 status_t status = (*mEffectInterface)->command(mEffectInterface,
7183 EFFECT_CMD_INIT,
7184 0,
7185 NULL,
7186 &size,
7187 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007188 if (status == 0) {
7189 status = cmdStatus;
7190 }
7191 return status;
7192}
7193
Eric Laurentec35a142011-10-05 17:42:25 -07007194status_t AudioFlinger::EffectModule::start()
7195{
7196 Mutex::Autolock _l(mLock);
7197 return start_l();
7198}
7199
Mathias Agopian65ab4712010-07-14 17:59:35 -07007200status_t AudioFlinger::EffectModule::start_l()
7201{
7202 if (mEffectInterface == NULL) {
7203 return NO_INIT;
7204 }
7205 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007206 uint32_t size = sizeof(status_t);
7207 status_t status = (*mEffectInterface)->command(mEffectInterface,
7208 EFFECT_CMD_ENABLE,
7209 0,
7210 NULL,
7211 &size,
7212 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007213 if (status == 0) {
7214 status = cmdStatus;
7215 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007216 if (status == 0 &&
7217 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7218 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7219 sp<ThreadBase> thread = mThread.promote();
7220 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007221 audio_stream_t *stream = thread->stream();
7222 if (stream != NULL) {
7223 stream->add_audio_effect(stream, mEffectInterface);
7224 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007225 }
7226 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007227 return status;
7228}
7229
Eric Laurentec437d82011-07-26 20:54:46 -07007230status_t AudioFlinger::EffectModule::stop()
7231{
7232 Mutex::Autolock _l(mLock);
7233 return stop_l();
7234}
7235
Mathias Agopian65ab4712010-07-14 17:59:35 -07007236status_t AudioFlinger::EffectModule::stop_l()
7237{
7238 if (mEffectInterface == NULL) {
7239 return NO_INIT;
7240 }
7241 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007242 uint32_t size = sizeof(status_t);
7243 status_t status = (*mEffectInterface)->command(mEffectInterface,
7244 EFFECT_CMD_DISABLE,
7245 0,
7246 NULL,
7247 &size,
7248 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007249 if (status == 0) {
7250 status = cmdStatus;
7251 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007252 if (status == 0 &&
7253 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7254 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7255 sp<ThreadBase> thread = mThread.promote();
7256 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007257 audio_stream_t *stream = thread->stream();
7258 if (stream != NULL) {
7259 stream->remove_audio_effect(stream, mEffectInterface);
7260 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007261 }
7262 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007263 return status;
7264}
7265
Eric Laurent25f43952010-07-28 05:40:18 -07007266status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
7267 uint32_t cmdSize,
7268 void *pCmdData,
7269 uint32_t *replySize,
7270 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007271{
7272 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007273// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007274
Eric Laurentec437d82011-07-26 20:54:46 -07007275 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007276 return NO_INIT;
7277 }
Eric Laurent25f43952010-07-28 05:40:18 -07007278 status_t status = (*mEffectInterface)->command(mEffectInterface,
7279 cmdCode,
7280 cmdSize,
7281 pCmdData,
7282 replySize,
7283 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007284 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07007285 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007286 for (size_t i = 1; i < mHandles.size(); i++) {
7287 sp<EffectHandle> h = mHandles[i].promote();
7288 if (h != 0) {
7289 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
7290 }
7291 }
7292 }
7293 return status;
7294}
7295
7296status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
7297{
Eric Laurentdb7c0792011-08-10 10:37:50 -07007298
Mathias Agopian65ab4712010-07-14 17:59:35 -07007299 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007300 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007301
7302 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007303 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
7304 if (enabled && status != NO_ERROR) {
7305 return status;
7306 }
7307
Mathias Agopian65ab4712010-07-14 17:59:35 -07007308 switch (mState) {
7309 // going from disabled to enabled
7310 case IDLE:
7311 mState = STARTING;
7312 break;
7313 case STOPPED:
7314 mState = RESTART;
7315 break;
7316 case STOPPING:
7317 mState = ACTIVE;
7318 break;
7319
7320 // going from enabled to disabled
7321 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007322 mState = STOPPED;
7323 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007324 case STARTING:
7325 mState = IDLE;
7326 break;
7327 case ACTIVE:
7328 mState = STOPPING;
7329 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007330 case DESTROYED:
7331 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007332 }
7333 for (size_t i = 1; i < mHandles.size(); i++) {
7334 sp<EffectHandle> h = mHandles[i].promote();
7335 if (h != 0) {
7336 h->setEnabled(enabled);
7337 }
7338 }
7339 }
7340 return NO_ERROR;
7341}
7342
Glenn Kastenc59c0042012-02-02 14:06:11 -08007343bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007344{
7345 switch (mState) {
7346 case RESTART:
7347 case STARTING:
7348 case ACTIVE:
7349 return true;
7350 case IDLE:
7351 case STOPPING:
7352 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07007353 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07007354 default:
7355 return false;
7356 }
7357}
7358
Glenn Kastenc59c0042012-02-02 14:06:11 -08007359bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07007360{
7361 switch (mState) {
7362 case RESTART:
7363 case ACTIVE:
7364 case STOPPING:
7365 case STOPPED:
7366 return true;
7367 case IDLE:
7368 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07007369 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007370 default:
7371 return false;
7372 }
7373}
7374
Mathias Agopian65ab4712010-07-14 17:59:35 -07007375status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7376{
7377 Mutex::Autolock _l(mLock);
7378 status_t status = NO_ERROR;
7379
7380 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7381 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07007382 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07007383 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7384 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007385 status_t cmdStatus;
7386 uint32_t volume[2];
7387 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07007388 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007389 volume[0] = *left;
7390 volume[1] = *right;
7391 if (controller) {
7392 pVolume = volume;
7393 }
Eric Laurent25f43952010-07-28 05:40:18 -07007394 status = (*mEffectInterface)->command(mEffectInterface,
7395 EFFECT_CMD_SET_VOLUME,
7396 size,
7397 volume,
7398 &size,
7399 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007400 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7401 *left = volume[0];
7402 *right = volume[1];
7403 }
7404 }
7405 return status;
7406}
7407
7408status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7409{
7410 Mutex::Autolock _l(mLock);
7411 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007412 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7413 // audio pre processing modules on RecordThread can receive both output and
7414 // input device indication in the same call
7415 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7416 if (dev) {
7417 status_t cmdStatus;
7418 uint32_t size = sizeof(status_t);
7419
7420 status = (*mEffectInterface)->command(mEffectInterface,
7421 EFFECT_CMD_SET_DEVICE,
7422 sizeof(uint32_t),
7423 &dev,
7424 &size,
7425 &cmdStatus);
7426 if (status == NO_ERROR) {
7427 status = cmdStatus;
7428 }
7429 }
7430 dev = device & AUDIO_DEVICE_IN_ALL;
7431 if (dev) {
7432 status_t cmdStatus;
7433 uint32_t size = sizeof(status_t);
7434
7435 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7436 EFFECT_CMD_SET_INPUT_DEVICE,
7437 sizeof(uint32_t),
7438 &dev,
7439 &size,
7440 &cmdStatus);
7441 if (status2 == NO_ERROR) {
7442 status2 = cmdStatus;
7443 }
7444 if (status == NO_ERROR) {
7445 status = status2;
7446 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007447 }
7448 }
7449 return status;
7450}
7451
Glenn Kastenf78aee72012-01-04 11:00:47 -08007452status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007453{
7454 Mutex::Autolock _l(mLock);
7455 status_t status = NO_ERROR;
7456 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007457 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007458 uint32_t size = sizeof(status_t);
7459 status = (*mEffectInterface)->command(mEffectInterface,
7460 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08007461 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07007462 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07007463 &size,
7464 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007465 if (status == NO_ERROR) {
7466 status = cmdStatus;
7467 }
7468 }
7469 return status;
7470}
7471
Eric Laurent59255e42011-07-27 19:49:51 -07007472void AudioFlinger::EffectModule::setSuspended(bool suspended)
7473{
7474 Mutex::Autolock _l(mLock);
7475 mSuspended = suspended;
7476}
Glenn Kastena3a85482012-01-04 11:01:11 -08007477
7478bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07007479{
7480 Mutex::Autolock _l(mLock);
7481 return mSuspended;
7482}
7483
Mathias Agopian65ab4712010-07-14 17:59:35 -07007484status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7485{
7486 const size_t SIZE = 256;
7487 char buffer[SIZE];
7488 String8 result;
7489
7490 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7491 result.append(buffer);
7492
7493 bool locked = tryLock(mLock);
7494 // failed to lock - AudioFlinger is probably deadlocked
7495 if (!locked) {
7496 result.append("\t\tCould not lock Fx mutex:\n");
7497 }
7498
7499 result.append("\t\tSession Status State Engine:\n");
7500 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7501 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7502 result.append(buffer);
7503
7504 result.append("\t\tDescriptor:\n");
7505 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7506 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7507 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7508 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7509 result.append(buffer);
7510 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7511 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7512 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7513 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7514 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07007515 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007516 mDescriptor.apiVersion,
7517 mDescriptor.flags);
7518 result.append(buffer);
7519 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7520 mDescriptor.name);
7521 result.append(buffer);
7522 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7523 mDescriptor.implementor);
7524 result.append(buffer);
7525
7526 result.append("\t\t- Input configuration:\n");
7527 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7528 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7529 (uint32_t)mConfig.inputCfg.buffer.raw,
7530 mConfig.inputCfg.buffer.frameCount,
7531 mConfig.inputCfg.samplingRate,
7532 mConfig.inputCfg.channels,
7533 mConfig.inputCfg.format);
7534 result.append(buffer);
7535
7536 result.append("\t\t- Output configuration:\n");
7537 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7538 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7539 (uint32_t)mConfig.outputCfg.buffer.raw,
7540 mConfig.outputCfg.buffer.frameCount,
7541 mConfig.outputCfg.samplingRate,
7542 mConfig.outputCfg.channels,
7543 mConfig.outputCfg.format);
7544 result.append(buffer);
7545
7546 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7547 result.append(buffer);
7548 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7549 for (size_t i = 0; i < mHandles.size(); ++i) {
7550 sp<EffectHandle> handle = mHandles[i].promote();
7551 if (handle != 0) {
7552 handle->dump(buffer, SIZE);
7553 result.append(buffer);
7554 }
7555 }
7556
7557 result.append("\n");
7558
7559 write(fd, result.string(), result.length());
7560
7561 if (locked) {
7562 mLock.unlock();
7563 }
7564
7565 return NO_ERROR;
7566}
7567
7568// ----------------------------------------------------------------------------
7569// EffectHandle implementation
7570// ----------------------------------------------------------------------------
7571
7572#undef LOG_TAG
7573#define LOG_TAG "AudioFlinger::EffectHandle"
7574
7575AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7576 const sp<AudioFlinger::Client>& client,
7577 const sp<IEffectClient>& effectClient,
7578 int32_t priority)
7579 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007580 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007581 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007582{
Steve Block3856b092011-10-20 11:56:00 +01007583 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007584
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007585 if (client == 0) {
7586 return;
7587 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007588 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7589 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7590 if (mCblkMemory != 0) {
7591 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7592
Glenn Kastena0d68332012-01-27 16:47:15 -08007593 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007594 new(mCblk) effect_param_cblk_t();
7595 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007596 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007597 } else {
Steve Block29357bc2012-01-06 19:20:56 +00007598 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007599 return;
7600 }
7601}
7602
7603AudioFlinger::EffectHandle::~EffectHandle()
7604{
Steve Block3856b092011-10-20 11:56:00 +01007605 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007606 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01007607 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007608}
7609
7610status_t AudioFlinger::EffectHandle::enable()
7611{
Steve Block3856b092011-10-20 11:56:00 +01007612 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007613 if (!mHasControl) return INVALID_OPERATION;
7614 if (mEffect == 0) return DEAD_OBJECT;
7615
Eric Laurentdb7c0792011-08-10 10:37:50 -07007616 if (mEnabled) {
7617 return NO_ERROR;
7618 }
7619
Eric Laurent59255e42011-07-27 19:49:51 -07007620 mEnabled = true;
7621
7622 sp<ThreadBase> thread = mEffect->thread().promote();
7623 if (thread != 0) {
7624 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7625 }
7626
7627 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7628 if (mEffect->suspended()) {
7629 return NO_ERROR;
7630 }
7631
Eric Laurentdb7c0792011-08-10 10:37:50 -07007632 status_t status = mEffect->setEnabled(true);
7633 if (status != NO_ERROR) {
7634 if (thread != 0) {
7635 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7636 }
7637 mEnabled = false;
7638 }
7639 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007640}
7641
7642status_t AudioFlinger::EffectHandle::disable()
7643{
Steve Block3856b092011-10-20 11:56:00 +01007644 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007645 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07007646 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007647
Eric Laurentdb7c0792011-08-10 10:37:50 -07007648 if (!mEnabled) {
7649 return NO_ERROR;
7650 }
Eric Laurent59255e42011-07-27 19:49:51 -07007651 mEnabled = false;
7652
7653 if (mEffect->suspended()) {
7654 return NO_ERROR;
7655 }
7656
7657 status_t status = mEffect->setEnabled(false);
7658
7659 sp<ThreadBase> thread = mEffect->thread().promote();
7660 if (thread != 0) {
7661 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7662 }
7663
7664 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007665}
7666
7667void AudioFlinger::EffectHandle::disconnect()
7668{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007669 disconnect(true);
7670}
7671
Glenn Kasten58123c32012-02-03 10:32:24 -08007672void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007673{
Glenn Kasten58123c32012-02-03 10:32:24 -08007674 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007675 if (mEffect == 0) {
7676 return;
7677 }
Glenn Kasten58123c32012-02-03 10:32:24 -08007678 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07007679
Eric Laurenta85a74a2011-10-19 11:44:54 -07007680 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007681 sp<ThreadBase> thread = mEffect->thread().promote();
7682 if (thread != 0) {
7683 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7684 }
Eric Laurent59255e42011-07-27 19:49:51 -07007685 }
7686
Mathias Agopian65ab4712010-07-14 17:59:35 -07007687 // release sp on module => module destructor can be called now
7688 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007689 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08007690 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08007691 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007692 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7693 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08007694 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007695 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07007696 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7697 mClient.clear();
7698 }
7699}
7700
Eric Laurent25f43952010-07-28 05:40:18 -07007701status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7702 uint32_t cmdSize,
7703 void *pCmdData,
7704 uint32_t *replySize,
7705 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007706{
Steve Block3856b092011-10-20 11:56:00 +01007707// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07007708// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007709
7710 // only get parameter command is permitted for applications not controlling the effect
7711 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7712 return INVALID_OPERATION;
7713 }
7714 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007715 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007716
7717 // handle commands that are not forwarded transparently to effect engine
7718 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7719 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7720 // no risk to block the whole media server process or mixer threads is we are stuck here
7721 Mutex::Autolock _l(mCblk->lock);
7722 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7723 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7724 mCblk->serverIndex = 0;
7725 mCblk->clientIndex = 0;
7726 return BAD_VALUE;
7727 }
7728 status_t status = NO_ERROR;
7729 while (mCblk->serverIndex < mCblk->clientIndex) {
7730 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007731 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007732 int *p = (int *)(mBuffer + mCblk->serverIndex);
7733 int size = *p++;
7734 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007735 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007736 break;
7737 }
7738 effect_param_t *param = (effect_param_t *)p;
7739 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007740 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007741 mCblk->serverIndex += size;
7742 continue;
7743 }
Eric Laurent25f43952010-07-28 05:40:18 -07007744 uint32_t psize = sizeof(effect_param_t) +
7745 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7746 param->vsize;
7747 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7748 psize,
7749 p,
7750 &rsize,
7751 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007752 // stop at first error encountered
7753 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007754 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007755 *(int *)pReplyData = reply;
7756 break;
7757 } else if (reply != NO_ERROR) {
7758 *(int *)pReplyData = reply;
7759 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007760 }
7761 mCblk->serverIndex += size;
7762 }
7763 mCblk->serverIndex = 0;
7764 mCblk->clientIndex = 0;
7765 return status;
7766 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007767 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007768 return enable();
7769 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007770 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007771 return disable();
7772 }
7773
7774 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7775}
7776
Eric Laurent59255e42011-07-27 19:49:51 -07007777void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007778{
Steve Block3856b092011-10-20 11:56:00 +01007779 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007780
7781 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007782 mEnabled = enabled;
7783
Mathias Agopian65ab4712010-07-14 17:59:35 -07007784 if (signal && mEffectClient != 0) {
7785 mEffectClient->controlStatusChanged(hasControl);
7786 }
7787}
7788
Eric Laurent25f43952010-07-28 05:40:18 -07007789void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7790 uint32_t cmdSize,
7791 void *pCmdData,
7792 uint32_t replySize,
7793 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007794{
7795 if (mEffectClient != 0) {
7796 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7797 }
7798}
7799
7800
7801
7802void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7803{
7804 if (mEffectClient != 0) {
7805 mEffectClient->enableStatusChanged(enabled);
7806 }
7807}
7808
7809status_t AudioFlinger::EffectHandle::onTransact(
7810 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7811{
7812 return BnEffect::onTransact(code, data, reply, flags);
7813}
7814
7815
7816void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7817{
Glenn Kastena0d68332012-01-27 16:47:15 -08007818 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007819
7820 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08007821 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007822 mPriority,
7823 mHasControl,
7824 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007825 mCblk ? mCblk->clientIndex : 0,
7826 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007827 );
7828
7829 if (locked) {
7830 mCblk->lock.unlock();
7831 }
7832}
7833
7834#undef LOG_TAG
7835#define LOG_TAG "AudioFlinger::EffectChain"
7836
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007837AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007838 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007839 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007840 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7841 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007842{
Dima Zavinfce7a472011-04-19 22:30:36 -07007843 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007844 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007845 return;
7846 }
7847 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7848 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007849}
7850
7851AudioFlinger::EffectChain::~EffectChain()
7852{
7853 if (mOwnInBuffer) {
7854 delete mInBuffer;
7855 }
7856
7857}
7858
Eric Laurent59255e42011-07-27 19:49:51 -07007859// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007860sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007861{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007862 size_t size = mEffects.size();
7863
7864 for (size_t i = 0; i < size; i++) {
7865 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007866 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007867 }
7868 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007869 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007870}
7871
Eric Laurent59255e42011-07-27 19:49:51 -07007872// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007873sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007874{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007875 size_t size = mEffects.size();
7876
7877 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007878 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7879 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007880 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007881 }
7882 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007883 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007884}
7885
Eric Laurent59255e42011-07-27 19:49:51 -07007886// getEffectFromType_l() must be called with ThreadBase::mLock held
7887sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7888 const effect_uuid_t *type)
7889{
Eric Laurent59255e42011-07-27 19:49:51 -07007890 size_t size = mEffects.size();
7891
7892 for (size_t i = 0; i < size; i++) {
7893 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007894 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007895 }
7896 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007897 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007898}
7899
Mathias Agopian65ab4712010-07-14 17:59:35 -07007900// Must be called with EffectChain::mLock locked
7901void AudioFlinger::EffectChain::process_l()
7902{
Eric Laurentdac69112010-09-28 14:09:57 -07007903 sp<ThreadBase> thread = mThread.promote();
7904 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007905 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007906 return;
7907 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007908 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7909 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007910 // always process effects unless no more tracks are on the session and the effect tail
7911 // has been rendered
7912 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007913 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007914 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007915
Eric Laurent544fe9b2011-11-11 15:42:52 -08007916 if (!tracksOnSession && mTailBufferCount == 0) {
7917 doProcess = false;
7918 }
7919
7920 if (activeTrackCnt() == 0) {
7921 // if no track is active and the effect tail has not been rendered,
7922 // the input buffer must be cleared here as the mixer process will not do it
7923 if (tracksOnSession || mTailBufferCount > 0) {
7924 size_t numSamples = thread->frameCount() * thread->channelCount();
7925 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7926 if (mTailBufferCount > 0) {
7927 mTailBufferCount--;
7928 }
7929 }
7930 }
Eric Laurentdac69112010-09-28 14:09:57 -07007931 }
7932
Mathias Agopian65ab4712010-07-14 17:59:35 -07007933 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007934 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007935 for (size_t i = 0; i < size; i++) {
7936 mEffects[i]->process();
7937 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007938 }
7939 for (size_t i = 0; i < size; i++) {
7940 mEffects[i]->updateState();
7941 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007942}
7943
Eric Laurentcab11242010-07-15 12:50:15 -07007944// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007945status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007946{
7947 effect_descriptor_t desc = effect->desc();
7948 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7949
7950 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007951 effect->setChain(this);
7952 sp<ThreadBase> thread = mThread.promote();
7953 if (thread == 0) {
7954 return NO_INIT;
7955 }
7956 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007957
7958 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7959 // Auxiliary effects are inserted at the beginning of mEffects vector as
7960 // they are processed first and accumulated in chain input buffer
7961 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007962
Mathias Agopian65ab4712010-07-14 17:59:35 -07007963 // the input buffer for auxiliary effect contains mono samples in
7964 // 32 bit format. This is to avoid saturation in AudoMixer
7965 // accumulation stage. Saturation is done in EffectModule::process() before
7966 // calling the process in effect engine
7967 size_t numSamples = thread->frameCount();
7968 int32_t *buffer = new int32_t[numSamples];
7969 memset(buffer, 0, numSamples * sizeof(int32_t));
7970 effect->setInBuffer((int16_t *)buffer);
7971 // auxiliary effects output samples to chain input buffer for further processing
7972 // by insert effects
7973 effect->setOutBuffer(mInBuffer);
7974 } else {
7975 // Insert effects are inserted at the end of mEffects vector as they are processed
7976 // after track and auxiliary effects.
7977 // Insert effect order as a function of indicated preference:
7978 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7979 // another effect is present
7980 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7981 // last effect claiming first position
7982 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7983 // first effect claiming last position
7984 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7985 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7986 // already present
7987
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007988 size_t size = mEffects.size();
7989 size_t idx_insert = size;
7990 ssize_t idx_insert_first = -1;
7991 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007992
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007993 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007994 effect_descriptor_t d = mEffects[i]->desc();
7995 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7996 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7997 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7998 // check invalid effect chaining combinations
7999 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
8000 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008001 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008002 return INVALID_OPERATION;
8003 }
8004 // remember position of first insert effect and by default
8005 // select this as insert position for new effect
8006 if (idx_insert == size) {
8007 idx_insert = i;
8008 }
8009 // remember position of last insert effect claiming
8010 // first position
8011 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
8012 idx_insert_first = i;
8013 }
8014 // remember position of first insert effect claiming
8015 // last position
8016 if (iPref == EFFECT_FLAG_INSERT_LAST &&
8017 idx_insert_last == -1) {
8018 idx_insert_last = i;
8019 }
8020 }
8021 }
8022
8023 // modify idx_insert from first position if needed
8024 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
8025 if (idx_insert_last != -1) {
8026 idx_insert = idx_insert_last;
8027 } else {
8028 idx_insert = size;
8029 }
8030 } else {
8031 if (idx_insert_first != -1) {
8032 idx_insert = idx_insert_first + 1;
8033 }
8034 }
8035
8036 // always read samples from chain input buffer
8037 effect->setInBuffer(mInBuffer);
8038
8039 // if last effect in the chain, output samples to chain
8040 // output buffer, otherwise to chain input buffer
8041 if (idx_insert == size) {
8042 if (idx_insert != 0) {
8043 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
8044 mEffects[idx_insert-1]->configure();
8045 }
8046 effect->setOutBuffer(mOutBuffer);
8047 } else {
8048 effect->setOutBuffer(mInBuffer);
8049 }
8050 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008051
Steve Block3856b092011-10-20 11:56:00 +01008052 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008053 }
8054 effect->configure();
8055 return NO_ERROR;
8056}
8057
Eric Laurentcab11242010-07-15 12:50:15 -07008058// removeEffect_l() must be called with PlaybackThread::mLock held
8059size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008060{
8061 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008062 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008063 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
8064
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008065 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008066 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07008067 // calling stop here will remove pre-processing effect from the audio HAL.
8068 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
8069 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07008070 if (mEffects[i]->state() == EffectModule::ACTIVE ||
8071 mEffects[i]->state() == EffectModule::STOPPING) {
8072 mEffects[i]->stop();
8073 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008074 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
8075 delete[] effect->inBuffer();
8076 } else {
8077 if (i == size - 1 && i != 0) {
8078 mEffects[i - 1]->setOutBuffer(mOutBuffer);
8079 mEffects[i - 1]->configure();
8080 }
8081 }
8082 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01008083 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008084 break;
8085 }
8086 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008087
8088 return mEffects.size();
8089}
8090
Eric Laurentcab11242010-07-15 12:50:15 -07008091// setDevice_l() must be called with PlaybackThread::mLock held
8092void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008093{
8094 size_t size = mEffects.size();
8095 for (size_t i = 0; i < size; i++) {
8096 mEffects[i]->setDevice(device);
8097 }
8098}
8099
Eric Laurentcab11242010-07-15 12:50:15 -07008100// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08008101void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008102{
8103 size_t size = mEffects.size();
8104 for (size_t i = 0; i < size; i++) {
8105 mEffects[i]->setMode(mode);
8106 }
8107}
8108
Eric Laurentcab11242010-07-15 12:50:15 -07008109// setVolume_l() must be called with PlaybackThread::mLock held
8110bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008111{
8112 uint32_t newLeft = *left;
8113 uint32_t newRight = *right;
8114 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07008115 int ctrlIdx = -1;
8116 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008117
Eric Laurentcab11242010-07-15 12:50:15 -07008118 // first update volume controller
8119 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07008120 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07008121 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
8122 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07008123 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07008124 break;
8125 }
8126 }
8127
8128 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07008129 if (hasControl) {
8130 *left = mNewLeftVolume;
8131 *right = mNewRightVolume;
8132 }
8133 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07008134 }
8135
8136 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07008137 mLeftVolume = newLeft;
8138 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008139
8140 // second get volume update from volume controller
8141 if (ctrlIdx >= 0) {
8142 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07008143 mNewLeftVolume = newLeft;
8144 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008145 }
8146 // then indicate volume to all other effects in chain.
8147 // Pass altered volume to effects before volume controller
8148 // and requested volume to effects after controller
8149 uint32_t lVol = newLeft;
8150 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008151
Mathias Agopian65ab4712010-07-14 17:59:35 -07008152 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07008153 if ((int)i == ctrlIdx) continue;
8154 // this also works for ctrlIdx == -1 when there is no volume controller
8155 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008156 lVol = *left;
8157 rVol = *right;
8158 }
8159 mEffects[i]->setVolume(&lVol, &rVol, false);
8160 }
8161 *left = newLeft;
8162 *right = newRight;
8163
8164 return hasControl;
8165}
8166
Mathias Agopian65ab4712010-07-14 17:59:35 -07008167status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
8168{
8169 const size_t SIZE = 256;
8170 char buffer[SIZE];
8171 String8 result;
8172
8173 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
8174 result.append(buffer);
8175
8176 bool locked = tryLock(mLock);
8177 // failed to lock - AudioFlinger is probably deadlocked
8178 if (!locked) {
8179 result.append("\tCould not lock mutex:\n");
8180 }
8181
Eric Laurentcab11242010-07-15 12:50:15 -07008182 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
8183 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008184 mEffects.size(),
8185 (uint32_t)mInBuffer,
8186 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008187 mActiveTrackCnt);
8188 result.append(buffer);
8189 write(fd, result.string(), result.size());
8190
8191 for (size_t i = 0; i < mEffects.size(); ++i) {
8192 sp<EffectModule> effect = mEffects[i];
8193 if (effect != 0) {
8194 effect->dump(fd, args);
8195 }
8196 }
8197
8198 if (locked) {
8199 mLock.unlock();
8200 }
8201
8202 return NO_ERROR;
8203}
8204
Eric Laurent59255e42011-07-27 19:49:51 -07008205// must be called with ThreadBase::mLock held
8206void AudioFlinger::EffectChain::setEffectSuspended_l(
8207 const effect_uuid_t *type, bool suspend)
8208{
8209 sp<SuspendedEffectDesc> desc;
8210 // use effect type UUID timelow as key as there is no real risk of identical
8211 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008212 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008213 if (suspend) {
8214 if (index >= 0) {
8215 desc = mSuspendedEffects.valueAt(index);
8216 } else {
8217 desc = new SuspendedEffectDesc();
8218 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
8219 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01008220 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008221 }
8222 if (desc->mRefCount++ == 0) {
8223 sp<EffectModule> effect = getEffectIfEnabled(type);
8224 if (effect != 0) {
8225 desc->mEffect = effect;
8226 effect->setSuspended(true);
8227 effect->setEnabled(false);
8228 }
8229 }
8230 } else {
8231 if (index < 0) {
8232 return;
8233 }
8234 desc = mSuspendedEffects.valueAt(index);
8235 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008236 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008237 desc->mRefCount = 1;
8238 }
8239 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01008240 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008241 if (desc->mEffect != 0) {
8242 sp<EffectModule> effect = desc->mEffect.promote();
8243 if (effect != 0) {
8244 effect->setSuspended(false);
8245 sp<EffectHandle> handle = effect->controlHandle();
8246 if (handle != 0) {
8247 effect->setEnabled(handle->enabled());
8248 }
8249 }
8250 desc->mEffect.clear();
8251 }
8252 mSuspendedEffects.removeItemsAt(index);
8253 }
8254 }
8255}
8256
8257// must be called with ThreadBase::mLock held
8258void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
8259{
8260 sp<SuspendedEffectDesc> desc;
8261
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008262 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07008263 if (suspend) {
8264 if (index >= 0) {
8265 desc = mSuspendedEffects.valueAt(index);
8266 } else {
8267 desc = new SuspendedEffectDesc();
8268 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01008269 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07008270 }
8271 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08008272 Vector< sp<EffectModule> > effects;
8273 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07008274 for (size_t i = 0; i < effects.size(); i++) {
8275 setEffectSuspended_l(&effects[i]->desc().type, true);
8276 }
8277 }
8278 } else {
8279 if (index < 0) {
8280 return;
8281 }
8282 desc = mSuspendedEffects.valueAt(index);
8283 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008284 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008285 desc->mRefCount = 1;
8286 }
8287 if (--desc->mRefCount == 0) {
8288 Vector<const effect_uuid_t *> types;
8289 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
8290 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
8291 continue;
8292 }
8293 types.add(&mSuspendedEffects.valueAt(i)->mType);
8294 }
8295 for (size_t i = 0; i < types.size(); i++) {
8296 setEffectSuspended_l(types[i], false);
8297 }
Steve Block3856b092011-10-20 11:56:00 +01008298 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008299 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
8300 }
8301 }
8302}
8303
Eric Laurent6bffdb82011-09-23 08:40:41 -07008304
8305// The volume effect is used for automated tests only
8306#ifndef OPENSL_ES_H_
8307static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
8308 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
8309const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
8310#endif //OPENSL_ES_H_
8311
Eric Laurentdb7c0792011-08-10 10:37:50 -07008312bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
8313{
8314 // auxiliary effects and visualizer are never suspended on output mix
8315 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8316 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07008317 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8318 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008319 return false;
8320 }
8321 return true;
8322}
8323
Glenn Kastend0539712012-01-30 12:56:03 -08008324void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07008325{
Glenn Kastend0539712012-01-30 12:56:03 -08008326 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07008327 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08008328 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8329 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07008330 }
Eric Laurent59255e42011-07-27 19:49:51 -07008331 }
Eric Laurent59255e42011-07-27 19:49:51 -07008332}
8333
8334sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8335 const effect_uuid_t *type)
8336{
Glenn Kasten090f0192012-01-30 13:00:02 -08008337 sp<EffectModule> effect = getEffectFromType_l(type);
8338 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008339}
8340
8341void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8342 bool enabled)
8343{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008344 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008345 if (enabled) {
8346 if (index < 0) {
8347 // if the effect is not suspend check if all effects are suspended
8348 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8349 if (index < 0) {
8350 return;
8351 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07008352 if (!isEffectEligibleForSuspend(effect->desc())) {
8353 return;
8354 }
Eric Laurent59255e42011-07-27 19:49:51 -07008355 setEffectSuspended_l(&effect->desc().type, enabled);
8356 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07008357 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008358 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07008359 return;
8360 }
Eric Laurent59255e42011-07-27 19:49:51 -07008361 }
Steve Block3856b092011-10-20 11:56:00 +01008362 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008363 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008364 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8365 // if effect is requested to suspended but was not yet enabled, supend it now.
8366 if (desc->mEffect == 0) {
8367 desc->mEffect = effect;
8368 effect->setEnabled(false);
8369 effect->setSuspended(true);
8370 }
8371 } else {
8372 if (index < 0) {
8373 return;
8374 }
Steve Block3856b092011-10-20 11:56:00 +01008375 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008376 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008377 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8378 desc->mEffect.clear();
8379 effect->setSuspended(false);
8380 }
8381}
8382
Mathias Agopian65ab4712010-07-14 17:59:35 -07008383#undef LOG_TAG
8384#define LOG_TAG "AudioFlinger"
8385
8386// ----------------------------------------------------------------------------
8387
8388status_t AudioFlinger::onTransact(
8389 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8390{
8391 return BnAudioFlinger::onTransact(code, data, reply, flags);
8392}
8393
Mathias Agopian65ab4712010-07-14 17:59:35 -07008394}; // namespace android