blob: ad386f6fc1aceb21b164ccc9d57f5a14e24333a2 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070034#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035
Dima Zavinfce7a472011-04-19 22:30:36 -070036#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080038#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039
Glenn Kastend3cee2f2012-03-13 17:55:35 -070040#undef ADD_BATTERY_DATA
41
42#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080043#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080044#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070045#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070046
47#include <private/media/AudioTrackShared.h>
48#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070049
Dima Zavin64760242011-05-11 14:15:23 -070050#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070051#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
53#include "AudioMixer.h"
54#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080055#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Mathias Agopian65ab4712010-07-14 17:59:35 -070057#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070058#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070059#include <audio_effects/effect_ns.h>
60#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061
Glenn Kasten3b21c502011-12-15 09:52:39 -080062#include <audio_utils/primitives.h>
63
Eric Laurentfeb0db62011-07-22 09:04:31 -070064#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080065
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070066// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080067#ifdef DEBUG_CPU_USAGE
68#include <cpustats/CentralTendencyStatistics.h>
69#include <cpustats/ThreadCpuUsage.h>
70#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070071
John Grossman4ff14ba2012-02-08 16:37:41 -080072#include <common_time/cc_helper.h>
73#include <common_time/local_clock.h>
74
Mathias Agopian65ab4712010-07-14 17:59:35 -070075// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070076
Eric Laurentde070132010-07-13 04:45:46 -070077
Mathias Agopian65ab4712010-07-14 17:59:35 -070078namespace android {
79
Glenn Kastenec1d6b52011-12-12 09:04:45 -080080static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
81static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070082
Mathias Agopian65ab4712010-07-14 17:59:35 -070083static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -080084static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070085
86// retry counts for buffer fill timeout
87// 50 * ~20msecs = 1 second
88static const int8_t kMaxTrackRetries = 50;
89static const int8_t kMaxTrackStartupRetries = 50;
90// allow less retry attempts on direct output thread.
91// direct outputs can be a scarce resource in audio hardware and should
92// be released as quickly as possible.
93static const int8_t kMaxTrackRetriesDirect = 2;
94
95static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -080096static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070097
Glenn Kasten7dede872011-12-13 11:04:14 -080098// don't warn about blocked writes or record buffer overflows more often than this
99static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700100
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700101// RecordThread loop sleep time upon application overrun or audio HAL read error
102static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103
Glenn Kasten7dede872011-12-13 11:04:14 -0800104// maximum time to wait for setParameters to complete
105static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700106
Eric Laurent7cafbb32011-11-22 18:50:29 -0800107// minimum sleep time for the mixer thread loop when tracks are active but in underrun
108static const uint32_t kMinThreadSleepTimeUs = 5000;
109// maximum divider applied to the active sleep time in the mixer thread loop
110static const uint32_t kMaxThreadSleepTimeShift = 2;
111
John Grossman4ff14ba2012-02-08 16:37:41 -0800112nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800113
Mathias Agopian65ab4712010-07-14 17:59:35 -0700114// ----------------------------------------------------------------------------
115
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700116#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800117// To collect the amplifier usage
118static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800119 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
120 if (service == NULL) {
121 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800122 return;
123 }
124
125 service->addBatteryData(params);
126}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700127#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800128
Dima Zavin799a70e2011-04-18 16:57:27 -0700129static int load_audio_interface(const char *if_name, const hw_module_t **mod,
130 audio_hw_device_t **dev)
131{
132 int rc;
133
134 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
135 if (rc)
136 goto out;
137
138 rc = audio_hw_device_open(*mod, dev);
Steve Block29357bc2012-01-06 19:20:56 +0000139 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin799a70e2011-04-18 16:57:27 -0700140 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
141 if (rc)
142 goto out;
143
144 return 0;
145
146out:
147 *mod = NULL;
148 *dev = NULL;
149 return rc;
150}
151
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800152static const char * const audio_interfaces[] = {
Dima Zavin799a70e2011-04-18 16:57:27 -0700153 "primary",
154 "a2dp",
155 "usb",
156};
157#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
158
Mathias Agopian65ab4712010-07-14 17:59:35 -0700159// ----------------------------------------------------------------------------
160
161AudioFlinger::AudioFlinger()
162 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800163 mPrimaryHardwareDev(NULL),
164 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
165 mMasterVolume(1.0f),
166 mMasterVolumeSupportLvl(MVS_NONE),
167 mMasterMute(false),
168 mNextUniqueId(1),
169 mMode(AUDIO_MODE_INVALID),
170 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700171{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700172}
173
174void AudioFlinger::onFirstRef()
175{
Dima Zavin799a70e2011-04-18 16:57:27 -0700176 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700177
Eric Laurent93575202011-01-18 18:39:02 -0800178 Mutex::Autolock _l(mLock);
179
Dima Zavin799a70e2011-04-18 16:57:27 -0700180 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800181 char val_str[PROPERTY_VALUE_MAX] = { 0 };
182 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
183 uint32_t int_val;
184 if (1 == sscanf(val_str, "%u", &int_val)) {
185 mStandbyTimeInNsecs = milliseconds(int_val);
186 ALOGI("Using %u mSec as standby time.", int_val);
187 } else {
188 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
189 ALOGI("Using default %u mSec as standby time.",
190 (uint32_t)(mStandbyTimeInNsecs / 1000000));
191 }
192 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700193
Dima Zavin799a70e2011-04-18 16:57:27 -0700194 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
195 const hw_module_t *mod;
196 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700197
Dima Zavin799a70e2011-04-18 16:57:27 -0700198 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
199 if (rc)
200 continue;
201
Steve Blockdf64d152012-01-04 20:05:49 +0000202 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700203 mod->name, mod->id);
Dima Zavin799a70e2011-04-18 16:57:27 -0700204 mAudioHwDevs.push(dev);
205
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800206 if (mPrimaryHardwareDev == NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700207 mPrimaryHardwareDev = dev;
Steve Blockdf64d152012-01-04 20:05:49 +0000208 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700209 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700210 }
211 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700212
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800213 if (mPrimaryHardwareDev == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000214 ALOGE("Primary audio interface not found");
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800215 // proceed, all later accesses to mPrimaryHardwareDev verify it's safe with initCheck()
Dima Zavin799a70e2011-04-18 16:57:27 -0700216 }
217
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800218 // Currently (mPrimaryHardwareDev == NULL) == (mAudioHwDevs.size() == 0), but the way the
219 // primary HW dev is selected can change so these conditions might not always be equivalent.
220 // When that happens, re-visit all the code that assumes this.
221
222 AutoMutex lock(mHardwareLock);
223
John Grossman4ff14ba2012-02-08 16:37:41 -0800224 // Determine the level of master volume support the primary audio HAL has,
225 // and set the initial master volume at the same time.
226 float initialVolume = 1.0;
227 mMasterVolumeSupportLvl = MVS_NONE;
228 if (0 == mPrimaryHardwareDev->init_check(mPrimaryHardwareDev)) {
229 audio_hw_device_t *dev = mPrimaryHardwareDev;
230
231 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
232 if ((NULL != dev->get_master_volume) &&
233 (NO_ERROR == dev->get_master_volume(dev, &initialVolume))) {
234 mMasterVolumeSupportLvl = MVS_FULL;
235 } else {
236 mMasterVolumeSupportLvl = MVS_SETONLY;
237 initialVolume = 1.0;
238 }
239
240 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
241 if ((NULL == dev->set_master_volume) ||
242 (NO_ERROR != dev->set_master_volume(dev, initialVolume))) {
243 mMasterVolumeSupportLvl = MVS_NONE;
244 }
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800245 mHardwareStatus = AUDIO_HW_IDLE;
John Grossman4ff14ba2012-02-08 16:37:41 -0800246 }
247
248 // Set the mode for each audio HAL, and try to set the initial volume (if
249 // supported) for all of the non-primary audio HALs.
Dima Zavin799a70e2011-04-18 16:57:27 -0700250 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
251 audio_hw_device_t *dev = mAudioHwDevs[i];
252
253 mHardwareStatus = AUDIO_HW_INIT;
254 rc = dev->init_check(dev);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800255 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700256 if (rc == 0) {
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800257 mMode = AUDIO_MODE_NORMAL; // assigned multiple times with same value
Dima Zavin799a70e2011-04-18 16:57:27 -0700258 mHardwareStatus = AUDIO_HW_SET_MODE;
259 dev->set_mode(dev, mMode);
John Grossman4ff14ba2012-02-08 16:37:41 -0800260
261 if ((dev != mPrimaryHardwareDev) &&
262 (NULL != dev->set_master_volume)) {
263 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
264 dev->set_master_volume(dev, initialVolume);
265 }
266
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800267 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700268 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700269 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800270
271 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
272 ? initialVolume
273 : 1.0;
274 mMasterVolume = initialVolume;
275 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700276}
277
278AudioFlinger::~AudioFlinger()
279{
Dima Zavin799a70e2011-04-18 16:57:27 -0700280
Mathias Agopian65ab4712010-07-14 17:59:35 -0700281 while (!mRecordThreads.isEmpty()) {
282 // closeInput() will remove first entry from mRecordThreads
283 closeInput(mRecordThreads.keyAt(0));
284 }
285 while (!mPlaybackThreads.isEmpty()) {
286 // closeOutput() will remove first entry from mPlaybackThreads
287 closeOutput(mPlaybackThreads.keyAt(0));
288 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700289
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800290 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
291 // no mHardwareLock needed, as there are no other references to this
292 audio_hw_device_close(mAudioHwDevs[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700293 }
294}
295
Dima Zavin799a70e2011-04-18 16:57:27 -0700296audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
297{
298 /* first matching HW device is returned */
299 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
300 audio_hw_device_t *dev = mAudioHwDevs[i];
301 if ((dev->get_supported_devices(dev) & devices) == devices)
302 return dev;
303 }
304 return NULL;
305}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700306
307status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
308{
309 const size_t SIZE = 256;
310 char buffer[SIZE];
311 String8 result;
312
313 result.append("Clients:\n");
314 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800315 sp<Client> client = mClients.valueAt(i).promote();
316 if (client != 0) {
317 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
318 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700319 }
320 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700321
322 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800323 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700324 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
325 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800326 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700327 result.append(buffer);
328 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700329 write(fd, result.string(), result.size());
330 return NO_ERROR;
331}
332
333
334status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
335{
336 const size_t SIZE = 256;
337 char buffer[SIZE];
338 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800339 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700340
John Grossman4ff14ba2012-02-08 16:37:41 -0800341 snprintf(buffer, SIZE, "Hardware status: %d\n"
342 "Standby Time mSec: %u\n",
343 hardwareStatus,
344 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700345 result.append(buffer);
346 write(fd, result.string(), result.size());
347 return NO_ERROR;
348}
349
350status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
351{
352 const size_t SIZE = 256;
353 char buffer[SIZE];
354 String8 result;
355 snprintf(buffer, SIZE, "Permission Denial: "
356 "can't dump AudioFlinger from pid=%d, uid=%d\n",
357 IPCThreadState::self()->getCallingPid(),
358 IPCThreadState::self()->getCallingUid());
359 result.append(buffer);
360 write(fd, result.string(), result.size());
361 return NO_ERROR;
362}
363
364static bool tryLock(Mutex& mutex)
365{
366 bool locked = false;
367 for (int i = 0; i < kDumpLockRetries; ++i) {
368 if (mutex.tryLock() == NO_ERROR) {
369 locked = true;
370 break;
371 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800372 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700373 }
374 return locked;
375}
376
377status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
378{
Glenn Kasten44deb052012-02-05 18:09:08 -0800379 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700380 dumpPermissionDenial(fd, args);
381 } else {
382 // get state of hardware lock
383 bool hardwareLocked = tryLock(mHardwareLock);
384 if (!hardwareLocked) {
385 String8 result(kHardwareLockedString);
386 write(fd, result.string(), result.size());
387 } else {
388 mHardwareLock.unlock();
389 }
390
391 bool locked = tryLock(mLock);
392
393 // failed to lock - AudioFlinger is probably deadlocked
394 if (!locked) {
395 String8 result(kDeadlockedString);
396 write(fd, result.string(), result.size());
397 }
398
399 dumpClients(fd, args);
400 dumpInternals(fd, args);
401
402 // dump playback threads
403 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
404 mPlaybackThreads.valueAt(i)->dump(fd, args);
405 }
406
407 // dump record threads
408 for (size_t i = 0; i < mRecordThreads.size(); i++) {
409 mRecordThreads.valueAt(i)->dump(fd, args);
410 }
411
Dima Zavin799a70e2011-04-18 16:57:27 -0700412 // dump all hardware devs
413 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
414 audio_hw_device_t *dev = mAudioHwDevs[i];
415 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700416 }
417 if (locked) mLock.unlock();
418 }
419 return NO_ERROR;
420}
421
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800422sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
423{
424 // If pid is already in the mClients wp<> map, then use that entry
425 // (for which promote() is always != 0), otherwise create a new entry and Client.
426 sp<Client> client = mClients.valueFor(pid).promote();
427 if (client == 0) {
428 client = new Client(this, pid);
429 mClients.add(pid, client);
430 }
431
432 return client;
433}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700434
435// IAudioFlinger interface
436
437
438sp<IAudioTrack> AudioFlinger::createTrack(
439 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800440 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700441 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800442 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700443 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800445 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700446 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800447 audio_io_handle_t output,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700448 int *sessionId,
449 status_t *status)
450{
451 sp<PlaybackThread::Track> track;
452 sp<TrackHandle> trackHandle;
453 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700454 status_t lStatus;
455 int lSessionId;
456
Glenn Kasten263709e2012-01-06 08:40:01 -0800457 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
458 // but if someone uses binder directly they could bypass that and cause us to crash
459 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000460 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700461 lStatus = BAD_VALUE;
462 goto Exit;
463 }
464
465 {
466 Mutex::Autolock _l(mLock);
467 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700468 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700469 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000470 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700471 lStatus = BAD_VALUE;
472 goto Exit;
473 }
474
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800475 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700476
Steve Block3856b092011-10-20 11:56:00 +0100477 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700478 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700479 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700480 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
481 if (mPlaybackThreads.keyAt(i) != output) {
482 // prevent same audio session on different output threads
483 uint32_t sessions = t->hasAudioSession(*sessionId);
484 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000485 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700486 lStatus = BAD_VALUE;
487 goto Exit;
488 }
489 // check if an effect with same session ID is waiting for a track to be created
490 if (sessions & PlaybackThread::EFFECT_SESSION) {
491 effectThread = t.get();
492 }
Eric Laurentde070132010-07-13 04:45:46 -0700493 }
494 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700495 lSessionId = *sessionId;
496 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700497 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700498 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700499 if (sessionId != NULL) {
500 *sessionId = lSessionId;
501 }
502 }
Steve Block3856b092011-10-20 11:56:00 +0100503 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700504
Glenn Kastena075db42012-03-06 11:22:44 -0800505 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700506 track = thread->createTrack_l(client, streamType, sampleRate, format,
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);
Glenn Kasten263709e2012-01-06 08:40:01 -08001506 // initialized by stream_type_t default constructor
1507 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001508 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001509 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1510 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001511}
1512
1513AudioFlinger::PlaybackThread::~PlaybackThread()
1514{
1515 delete [] mMixBuffer;
1516}
1517
1518status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1519{
1520 dumpInternals(fd, args);
1521 dumpTracks(fd, args);
1522 dumpEffectChains(fd, args);
1523 return NO_ERROR;
1524}
1525
1526status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1527{
1528 const size_t SIZE = 256;
1529 char buffer[SIZE];
1530 String8 result;
1531
1532 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1533 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001534 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001535 for (size_t i = 0; i < mTracks.size(); ++i) {
1536 sp<Track> track = mTracks[i];
1537 if (track != 0) {
1538 track->dump(buffer, SIZE);
1539 result.append(buffer);
1540 }
1541 }
1542
1543 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1544 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001545 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 -07001546 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001547 sp<Track> track = mActiveTracks[i].promote();
1548 if (track != 0) {
1549 track->dump(buffer, SIZE);
1550 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001551 }
1552 }
1553 write(fd, result.string(), result.size());
1554 return NO_ERROR;
1555}
1556
Mathias Agopian65ab4712010-07-14 17:59:35 -07001557status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1558{
1559 const size_t SIZE = 256;
1560 char buffer[SIZE];
1561 String8 result;
1562
1563 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1564 result.append(buffer);
1565 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1566 result.append(buffer);
1567 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1568 result.append(buffer);
1569 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1570 result.append(buffer);
1571 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1572 result.append(buffer);
1573 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1574 result.append(buffer);
1575 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1576 result.append(buffer);
1577 write(fd, result.string(), result.size());
1578
1579 dumpBase(fd, args);
1580
1581 return NO_ERROR;
1582}
1583
1584// Thread virtuals
1585status_t AudioFlinger::PlaybackThread::readyToRun()
1586{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001587 status_t status = initCheck();
1588 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001589 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001590 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001591 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001592 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001593 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001594}
1595
1596void AudioFlinger::PlaybackThread::onFirstRef()
1597{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001598 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001599}
1600
1601// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001602sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001603 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001604 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001605 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001606 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001607 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001608 int frameCount,
1609 const sp<IMemory>& sharedBuffer,
1610 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001611 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001612 status_t *status)
1613{
1614 sp<Track> track;
1615 status_t lStatus;
1616
Glenn Kasten73d22752012-03-19 13:38:30 -07001617 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1618
1619 // client expresses a preference for FAST, but we get the final say
1620 if ((flags & IAudioFlinger::TRACK_FAST) &&
1621 !(
1622 // not timed
1623 (!isTimed) &&
1624 // either of these use cases:
1625 (
1626 // use case 1: shared buffer with any frame count
1627 (
1628 (sharedBuffer != 0)
1629 ) ||
1630 // use case 2: callback handler and small power-of-2 frame count
1631 (
1632 // unfortunately we can't verify that there's a callback until start()
1633 // FIXME supported frame counts should not be hard-coded
1634 (
1635 (frameCount == 128) ||
1636 (frameCount == 256) ||
1637 (frameCount == 512)
1638 )
1639 )
1640 ) &&
1641 // PCM data
1642 audio_is_linear_pcm(format) &&
1643 // mono or stereo
1644 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1645 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1646 // hardware sample rate
1647 (sampleRate == mSampleRate)
1648 // FIXME test that MixerThread for this fast track has a capable output HAL
1649 // FIXME add a permission test also?
1650 ) ) {
1651 ALOGW("AUDIO_POLICY_OUTPUT_FLAG_FAST denied");
1652 flags &= ~IAudioFlinger::TRACK_FAST;
1653 }
1654
Mathias Agopian65ab4712010-07-14 17:59:35 -07001655 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001656 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1657 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001658 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001659 "for output %p with format %d",
1660 sampleRate, format, channelMask, mOutput, mFormat);
1661 lStatus = BAD_VALUE;
1662 goto Exit;
1663 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001664 }
1665 } else {
1666 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1667 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001668 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001669 lStatus = BAD_VALUE;
1670 goto Exit;
1671 }
1672 }
1673
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001674 lStatus = initCheck();
1675 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001676 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001677 goto Exit;
1678 }
1679
1680 { // scope for mLock
1681 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001682
1683 // all tracks in same audio session must share the same routing strategy otherwise
1684 // conflicts will happen when tracks are moved from one output to another by audio policy
1685 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001686 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001687 for (size_t i = 0; i < mTracks.size(); ++i) {
1688 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001689 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001690 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001691 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001692 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001693 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001694 lStatus = BAD_VALUE;
1695 goto Exit;
1696 }
1697 }
1698 }
1699
John Grossman4ff14ba2012-02-08 16:37:41 -08001700 if (!isTimed) {
1701 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001702 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001703 } else {
1704 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1705 channelMask, frameCount, sharedBuffer, sessionId);
1706 }
1707 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001708 lStatus = NO_MEMORY;
1709 goto Exit;
1710 }
1711 mTracks.add(track);
1712
1713 sp<EffectChain> chain = getEffectChain_l(sessionId);
1714 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001715 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001716 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001717 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001718 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001719 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001720
1721 // invalidate track immediately if the stream type was moved to another thread since
1722 // createTrack() was called by the client process.
1723 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001724 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001725 this, streamType);
Eric Laurent9f6530f2011-08-30 10:18:54 -07001726 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1727 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001728 }
1729 lStatus = NO_ERROR;
1730
1731Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001732 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001733 *status = lStatus;
1734 }
1735 return track;
1736}
1737
1738uint32_t AudioFlinger::PlaybackThread::latency() const
1739{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001740 Mutex::Autolock _l(mLock);
1741 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001742 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001743 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001744 return 0;
1745 }
1746}
1747
Glenn Kasten6637baa2012-01-09 09:40:36 -08001748void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001749{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001750 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001751 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001752}
1753
Glenn Kasten6637baa2012-01-09 09:40:36 -08001754void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001755{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001756 Mutex::Autolock _l(mLock);
1757 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001758}
1759
Glenn Kasten6637baa2012-01-09 09:40:36 -08001760void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001761{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001762 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001763 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001764}
1765
Glenn Kasten6637baa2012-01-09 09:40:36 -08001766void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001767{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001768 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001769 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001770}
1771
Glenn Kastenfff6d712012-01-12 16:38:12 -08001772float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001773{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001774 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001775 return mStreamTypes[stream].volume;
1776}
1777
Mathias Agopian65ab4712010-07-14 17:59:35 -07001778// addTrack_l() must be called with ThreadBase::mLock held
1779status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1780{
1781 status_t status = ALREADY_EXISTS;
1782
1783 // set retry count for buffer fill
1784 track->mRetryCount = kMaxTrackStartupRetries;
1785 if (mActiveTracks.indexOf(track) < 0) {
1786 // the track is newly added, make sure it fills up all its
1787 // buffers before playing. This is to ensure the client will
1788 // effectively get the latency it requested.
1789 track->mFillingUpStatus = Track::FS_FILLING;
1790 track->mResetDone = false;
1791 mActiveTracks.add(track);
1792 if (track->mainBuffer() != mMixBuffer) {
1793 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1794 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001795 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001796 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001797 }
1798 }
1799
1800 status = NO_ERROR;
1801 }
1802
Steve Block3856b092011-10-20 11:56:00 +01001803 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001804 mWaitWorkCV.broadcast();
1805
1806 return status;
1807}
1808
1809// destroyTrack_l() must be called with ThreadBase::mLock held
1810void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1811{
1812 track->mState = TrackBase::TERMINATED;
1813 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001814 removeTrack_l(track);
1815 }
1816}
1817
1818void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1819{
1820 mTracks.remove(track);
1821 deleteTrackName_l(track->name());
1822 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1823 if (chain != 0) {
1824 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001825 }
1826}
1827
1828String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1829{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001830 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001831 char *s;
1832
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001833 Mutex::Autolock _l(mLock);
1834 if (initCheck() != NO_ERROR) {
1835 return out_s8;
1836 }
1837
Dima Zavin799a70e2011-04-18 16:57:27 -07001838 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001839 out_s8 = String8(s);
1840 free(s);
1841 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001842}
1843
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001844// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001845void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1846 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001847 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001848
Steve Block3856b092011-10-20 11:56:00 +01001849 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001850
1851 switch (event) {
1852 case AudioSystem::OUTPUT_OPENED:
1853 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001854 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001855 desc.samplingRate = mSampleRate;
1856 desc.format = mFormat;
1857 desc.frameCount = mFrameCount;
1858 desc.latency = latency();
1859 param2 = &desc;
1860 break;
1861
1862 case AudioSystem::STREAM_CONFIG_CHANGED:
1863 param2 = &param;
1864 case AudioSystem::OUTPUT_CLOSED:
1865 default:
1866 break;
1867 }
1868 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1869}
1870
1871void AudioFlinger::PlaybackThread::readOutputParameters()
1872{
Dima Zavin799a70e2011-04-18 16:57:27 -07001873 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001874 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1875 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001876 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001877 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001878 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001879
1880 // FIXME - Current mixer implementation only supports stereo output: Always
1881 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001882 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001883 mMixBuffer = new int16_t[mFrameCount * 2];
1884 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1885
Eric Laurentde070132010-07-13 04:45:46 -07001886 // force reconfiguration of effect chains and engines to take new buffer size and audio
1887 // parameters into account
1888 // Note that mLock is not held when readOutputParameters() is called from the constructor
1889 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1890 // matter.
1891 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1892 Vector< sp<EffectChain> > effectChains = mEffectChains;
1893 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001894 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001895 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001896}
1897
1898status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1899{
Glenn Kastena0d68332012-01-27 16:47:15 -08001900 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001901 return BAD_VALUE;
1902 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001903 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001904 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001905 return INVALID_OPERATION;
1906 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001907 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001908
Dima Zavin799a70e2011-04-18 16:57:27 -07001909 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001910}
1911
Eric Laurent39e94f82010-07-28 01:32:47 -07001912uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001913{
1914 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001915 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001916 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001917 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001918 }
1919
1920 for (size_t i = 0; i < mTracks.size(); ++i) {
1921 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001922 if (sessionId == track->sessionId() &&
1923 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001924 result |= TRACK_SESSION;
1925 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001926 }
1927 }
1928
Eric Laurent39e94f82010-07-28 01:32:47 -07001929 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001930}
1931
Eric Laurentde070132010-07-13 04:45:46 -07001932uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1933{
Dima Zavinfce7a472011-04-19 22:30:36 -07001934 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001935 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001936 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1937 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001938 }
1939 for (size_t i = 0; i < mTracks.size(); i++) {
1940 sp<Track> track = mTracks[i];
1941 if (sessionId == track->sessionId() &&
1942 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001943 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07001944 }
1945 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001946 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001947}
1948
Mathias Agopian65ab4712010-07-14 17:59:35 -07001949
Glenn Kastenaed850d2012-01-26 09:46:34 -08001950AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001951{
1952 Mutex::Autolock _l(mLock);
1953 return mOutput;
1954}
1955
1956AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1957{
1958 Mutex::Autolock _l(mLock);
1959 AudioStreamOut *output = mOutput;
1960 mOutput = NULL;
1961 return output;
1962}
1963
1964// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08001965audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001966{
1967 if (mOutput == NULL) {
1968 return NULL;
1969 }
1970 return &mOutput->stream->common;
1971}
1972
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08001973uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08001974{
1975 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1976 // decoding and transfer time. So sleeping for half of the latency would likely cause
1977 // underruns
1978 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1979 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1980 } else {
1981 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1982 }
1983}
1984
Eric Laurenta011e352012-03-29 15:51:43 -07001985status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1986{
1987 if (!isValidSyncEvent(event)) {
1988 return BAD_VALUE;
1989 }
1990
1991 Mutex::Autolock _l(mLock);
1992
1993 for (size_t i = 0; i < mTracks.size(); ++i) {
1994 sp<Track> track = mTracks[i];
1995 if (event->triggerSession() == track->sessionId()) {
1996 track->setSyncEvent(event);
1997 return NO_ERROR;
1998 }
1999 }
2000
2001 return NAME_NOT_FOUND;
2002}
2003
2004bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2005{
2006 switch (event->type()) {
2007 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2008 return true;
2009 default:
2010 break;
2011 }
2012 return false;
2013}
2014
Mathias Agopian65ab4712010-07-14 17:59:35 -07002015// ----------------------------------------------------------------------------
2016
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002017AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002018 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten000f0e32012-03-01 17:10:56 -08002019 : PlaybackThread(audioFlinger, output, id, device, type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002020{
Glenn Kasten000f0e32012-03-01 17:10:56 -08002021 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002022 // FIXME - Current mixer implementation only supports stereo output
2023 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002024 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002025 }
2026}
2027
2028AudioFlinger::MixerThread::~MixerThread()
2029{
2030 delete mAudioMixer;
2031}
2032
Glenn Kasten83efdd02012-02-24 07:21:32 -08002033class CpuStats {
2034public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002035 CpuStats();
2036 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002037#ifdef DEBUG_CPU_USAGE
2038private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002039 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2040 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2041
2042 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2043
2044 int mCpuNum; // thread's current CPU number
2045 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002046#endif
2047};
2048
Glenn Kasten190a46f2012-03-06 11:27:10 -08002049CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002050#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002051 : mCpuNum(-1), mCpukHz(-1)
2052#endif
2053{
2054}
2055
2056void CpuStats::sample(const String8 &title) {
2057#ifdef DEBUG_CPU_USAGE
2058 // get current thread's delta CPU time in wall clock ns
2059 double wcNs;
2060 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2061
2062 // record sample for wall clock statistics
2063 if (valid) {
2064 mWcStats.sample(wcNs);
2065 }
2066
2067 // get the current CPU number
2068 int cpuNum = sched_getcpu();
2069
2070 // get the current CPU frequency in kHz
2071 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2072
2073 // check if either CPU number or frequency changed
2074 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2075 mCpuNum = cpuNum;
2076 mCpukHz = cpukHz;
2077 // ignore sample for purposes of cycles
2078 valid = false;
2079 }
2080
2081 // if no change in CPU number or frequency, then record sample for cycle statistics
2082 if (valid && mCpukHz > 0) {
2083 double cycles = wcNs * cpukHz * 0.000001;
2084 mHzStats.sample(cycles);
2085 }
2086
2087 unsigned n = mWcStats.n();
2088 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002089 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002090 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002091 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2092 double perLoop = elapsed / (double) n;
2093 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002094 double perLoop1k = perLoop * 0.001;
2095 double mean = mWcStats.mean();
2096 double stddev = mWcStats.stddev();
2097 double minimum = mWcStats.minimum();
2098 double maximum = mWcStats.maximum();
2099 double meanCycles = mHzStats.mean();
2100 double stddevCycles = mHzStats.stddev();
2101 double minCycles = mHzStats.minimum();
2102 double maxCycles = mHzStats.maximum();
2103 mCpuUsage.resetElapsed();
2104 mWcStats.reset();
2105 mHzStats.reset();
2106 ALOGD("CPU usage for %s over past %.1f secs\n"
2107 " (%u mixer loops at %.1f mean ms per loop):\n"
2108 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2109 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2110 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2111 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002112 elapsed * .000000001, n, perLoop * .000001,
2113 mean * .001,
2114 stddev * .001,
2115 minimum * .001,
2116 maximum * .001,
2117 mean / perLoop100,
2118 stddev / perLoop100,
2119 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002120 maximum / perLoop100,
2121 meanCycles / perLoop1k,
2122 stddevCycles / perLoop1k,
2123 minCycles / perLoop1k,
2124 maxCycles / perLoop1k);
2125
Glenn Kasten83efdd02012-02-24 07:21:32 -08002126 }
2127 }
2128#endif
2129};
2130
Glenn Kasten37d825e2012-02-24 07:21:48 -08002131void AudioFlinger::PlaybackThread::checkSilentMode_l()
2132{
2133 if (!mMasterMute) {
2134 char value[PROPERTY_VALUE_MAX];
2135 if (property_get("ro.audio.silent", value, "0") > 0) {
2136 char *endptr;
2137 unsigned long ul = strtoul(value, &endptr, 0);
2138 if (*endptr == '\0' && ul != 0) {
2139 ALOGD("Silence is golden");
2140 // The setprop command will not allow a property to be changed after
2141 // the first time it is set, so we don't have to worry about un-muting.
2142 setMasterMute_l(true);
2143 }
2144 }
2145 }
2146}
2147
Glenn Kasten000f0e32012-03-01 17:10:56 -08002148bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002149{
2150 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002151
Glenn Kasten000f0e32012-03-01 17:10:56 -08002152 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002153
2154 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002155 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002156if (mType == MIXER) {
2157 longStandbyExit = false;
2158}
Glenn Kasten688a6402012-02-29 07:57:06 -08002159
Glenn Kasten000f0e32012-03-01 17:10:56 -08002160 // DUPLICATING
2161 // FIXME could this be made local to while loop?
2162 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002163
Glenn Kasten66fcab92012-02-24 14:59:21 -08002164 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002165 sleepTime = idleSleepTime;
2166
2167if (mType == MIXER) {
2168 sleepTimeShift = 0;
2169}
2170
Glenn Kasten83efdd02012-02-24 07:21:32 -08002171 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002172 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002173
Eric Laurentfeb0db62011-07-22 09:04:31 -07002174 acquireWakeLock();
2175
Mathias Agopian65ab4712010-07-14 17:59:35 -07002176 while (!exitPending())
2177 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002178 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002179
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002180 Vector< sp<EffectChain> > effectChains;
2181
Mathias Agopian65ab4712010-07-14 17:59:35 -07002182 processConfigEvents();
2183
Mathias Agopian65ab4712010-07-14 17:59:35 -07002184 { // scope for mLock
2185
2186 Mutex::Autolock _l(mLock);
2187
2188 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002189 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002190 }
2191
Glenn Kastenfa26a852012-03-06 11:28:04 -08002192 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002193
Mathias Agopian65ab4712010-07-14 17:59:35 -07002194 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002195 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002196 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002197 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002198
2199 threadLoop_standby();
2200
Mathias Agopian65ab4712010-07-14 17:59:35 -07002201 mStandby = true;
2202 mBytesWritten = 0;
2203 }
2204
Glenn Kasten3e074702012-02-28 18:40:35 -08002205 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002206 // we're about to wait, flush the binder command buffer
2207 IPCThreadState::self()->flushCommands();
2208
Glenn Kastenfa26a852012-03-06 11:28:04 -08002209 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002210
Mathias Agopian65ab4712010-07-14 17:59:35 -07002211 if (exitPending()) break;
2212
Eric Laurentfeb0db62011-07-22 09:04:31 -07002213 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002214 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002215 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002216 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002217 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002218 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002219
Eric Laurent27741442012-01-17 19:20:12 -08002220 mPrevMixerStatus = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002221
Glenn Kasten37d825e2012-02-24 07:21:48 -08002222 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002223
Glenn Kasten000f0e32012-03-01 17:10:56 -08002224 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002225 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002226 if (mType == MIXER) {
2227 sleepTimeShift = 0;
2228 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002229
Mathias Agopian65ab4712010-07-14 17:59:35 -07002230 continue;
2231 }
2232 }
2233
Glenn Kastenfec279f2012-03-08 07:47:15 -08002234 mixer_state newMixerStatus = prepareTracks_l(&tracksToRemove);
2235 // Shift in the new status; this could be a queue if it's
2236 // useful to filter the mixer status over several cycles.
2237 mPrevMixerStatus = mMixerStatus;
2238 mMixerStatus = newMixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002239
2240 // prevent any changes in effect chain list and in each effect chain
2241 // during mixing and effect process as the audio buffers could be deleted
2242 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002243 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002244 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002245
Glenn Kastenfec279f2012-03-08 07:47:15 -08002246 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002247 threadLoop_mix();
2248 } else {
2249 threadLoop_sleepTime();
2250 }
2251
2252 if (mSuspended > 0) {
2253 sleepTime = suspendSleepTimeUs();
2254 }
2255
2256 // only process effects if we're going to write
2257 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002258 for (size_t i = 0; i < effectChains.size(); i ++) {
2259 effectChains[i]->process_l();
2260 }
2261 }
2262
2263 // enable changes in effect chain
2264 unlockEffectChains(effectChains);
2265
2266 // sleepTime == 0 means we must write to audio hardware
2267 if (sleepTime == 0) {
2268
2269 threadLoop_write();
2270
2271if (mType == MIXER) {
2272 // write blocked detection
2273 nsecs_t now = systemTime();
2274 nsecs_t delta = now - mLastWriteTime;
2275 if (!mStandby && delta > maxPeriod) {
2276 mNumDelayedWrites++;
2277 if ((now - lastWarning) > kWarningThrottleNs) {
2278 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2279 ns2ms(delta), mNumDelayedWrites, this);
2280 lastWarning = now;
2281 }
2282 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2283 // a different threshold. Or completely removed for what it is worth anyway...
2284 if (mStandby) {
2285 longStandbyExit = true;
2286 }
2287 }
2288}
2289
2290 mStandby = false;
2291 } else {
2292 usleep(sleepTime);
2293 }
2294
2295 // finally let go of removed track(s), without the lock held
2296 // since we can't guarantee the destructors won't acquire that
2297 // same lock.
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002298 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002299
Glenn Kastenfa26a852012-03-06 11:28:04 -08002300 // FIXME I don't understand the need for this here;
2301 // it was in the original code but maybe the
2302 // assignment in saveOutputTracks() makes this unnecessary?
2303 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002304
2305 // Effect chains will be actually deleted here if they were removed from
2306 // mEffectChains list during mixing or effects processing
2307 effectChains.clear();
2308
2309 // FIXME Note that the above .clear() is no longer necessary since effectChains
2310 // is now local to this block, but will keep it for now (at least until merge done).
2311 }
2312
2313if (mType == MIXER || mType == DIRECT) {
2314 // put output stream into standby mode
2315 if (!mStandby) {
2316 mOutput->stream->common.standby(&mOutput->stream->common);
2317 }
2318}
2319if (mType == DUPLICATING) {
2320 // for DuplicatingThread, standby mode is handled by the outputTracks
2321}
2322
2323 releaseWakeLock();
2324
2325 ALOGV("Thread %p type %d exiting", this, mType);
2326 return false;
2327}
2328
2329// shared by MIXER and DIRECT, overridden by DUPLICATING
2330void AudioFlinger::PlaybackThread::threadLoop_write()
2331{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002332 // FIXME rewrite to reduce number of system calls
2333 mLastWriteTime = systemTime();
2334 mInWrite = true;
2335 mBytesWritten += mixBufferSize;
2336 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2337 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2338 mNumWrites++;
2339 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002340}
2341
2342// shared by MIXER and DIRECT, overridden by DUPLICATING
2343void AudioFlinger::PlaybackThread::threadLoop_standby()
2344{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002345 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2346 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002347}
2348
2349void AudioFlinger::MixerThread::threadLoop_mix()
2350{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002351 // obtain the presentation timestamp of the next output buffer
2352 int64_t pts;
2353 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002354
Glenn Kasten952eeb22012-03-06 11:30:57 -08002355 if (NULL != mOutput->stream->get_next_write_timestamp) {
2356 status = mOutput->stream->get_next_write_timestamp(
2357 mOutput->stream, &pts);
2358 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002359
Glenn Kasten952eeb22012-03-06 11:30:57 -08002360 if (status != NO_ERROR) {
2361 pts = AudioBufferProvider::kInvalidPTS;
2362 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002363
Glenn Kasten952eeb22012-03-06 11:30:57 -08002364 // mix buffers...
2365 mAudioMixer->process(pts);
2366 // increase sleep time progressively when application underrun condition clears.
2367 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2368 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2369 // such that we would underrun the audio HAL.
2370 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2371 sleepTimeShift--;
2372 }
2373 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002374 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002375 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002376}
2377
2378void AudioFlinger::MixerThread::threadLoop_sleepTime()
2379{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002380 // If no tracks are ready, sleep once for the duration of an output
2381 // buffer size, then write 0s to the output
2382 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002383 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002384 sleepTime = activeSleepTime >> sleepTimeShift;
2385 if (sleepTime < kMinThreadSleepTimeUs) {
2386 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002387 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002388 // reduce sleep time in case of consecutive application underruns to avoid
2389 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2390 // duration we would end up writing less data than needed by the audio HAL if
2391 // the condition persists.
2392 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2393 sleepTimeShift++;
2394 }
2395 } else {
2396 sleepTime = idleSleepTime;
2397 }
2398 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002399 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002400 memset (mMixBuffer, 0, mixBufferSize);
2401 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002402 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002403 }
2404 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002405}
2406
2407// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002408AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002409 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002410{
2411
Glenn Kasten29c23c32012-01-26 13:37:52 -08002412 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002413 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002414 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002415 size_t mixedTracks = 0;
2416 size_t tracksWithEffect = 0;
2417
2418 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002419 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002420
Eric Laurent571d49c2010-08-11 05:20:11 -07002421 if (masterMute) {
2422 masterVolume = 0;
2423 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002424 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002425 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002426 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002427 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002428 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002429 masterVolume = (float)((v + (1 << 23)) >> 24);
2430 chain.clear();
2431 }
2432
2433 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002434 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002435 if (t == 0) continue;
2436
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002437 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002438 Track* const track = t.get();
2439 audio_track_cblk_t* cblk = track->cblk();
2440
2441 // The first time a track is added we wait
2442 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002443 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002444 // make sure that we have enough frames to mix one full buffer.
2445 // enforce this condition only once to enable draining the buffer in case the client
2446 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002447 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002448 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002449 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002450 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002451 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002452 if (t->sampleRate() == (int)mSampleRate) {
2453 minFrames = mFrameCount;
2454 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002455 // +1 for rounding and +1 for additional sample needed for interpolation
2456 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2457 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07002458 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08002459 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2460 // the minimum track buffer size is normally twice the number of frames necessary
2461 // to fill one buffer and the resampler should not leave more than one buffer worth
2462 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002463 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002464 }
2465 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002466 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002467 !track->isPaused() && !track->isTerminated())
2468 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002469 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002470
2471 mixedTracks++;
2472
2473 // track->mainBuffer() != mMixBuffer means there is an effect chain
2474 // connected to the track
2475 chain.clear();
2476 if (track->mainBuffer() != mMixBuffer) {
2477 chain = getEffectChain_l(track->sessionId());
2478 // Delegate volume control to effect in track effect chain if needed
2479 if (chain != 0) {
2480 tracksWithEffect++;
2481 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002482 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002483 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002484 }
2485 }
2486
2487
2488 int param = AudioMixer::VOLUME;
2489 if (track->mFillingUpStatus == Track::FS_FILLED) {
2490 // no ramp for the first volume setting
2491 track->mFillingUpStatus = Track::FS_ACTIVE;
2492 if (track->mState == TrackBase::RESUMING) {
2493 track->mState = TrackBase::ACTIVE;
2494 param = AudioMixer::RAMP_VOLUME;
2495 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002496 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002497 } else if (cblk->server != 0) {
2498 // If the track is stopped before the first frame was mixed,
2499 // do not apply ramp
2500 param = AudioMixer::RAMP_VOLUME;
2501 }
2502
2503 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002504 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002505 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002506 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002507 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002508 if (track->isPausing()) {
2509 track->setPaused();
2510 }
2511 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002512
Mathias Agopian65ab4712010-07-14 17:59:35 -07002513 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002514 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002515 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002516 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002517 vl = vlr & 0xFFFF;
2518 vr = vlr >> 16;
2519 // track volumes come from shared memory, so can't be trusted and must be clamped
2520 if (vl > MAX_GAIN_INT) {
2521 ALOGV("Track left volume out of range: %04X", vl);
2522 vl = MAX_GAIN_INT;
2523 }
2524 if (vr > MAX_GAIN_INT) {
2525 ALOGV("Track right volume out of range: %04X", vr);
2526 vr = MAX_GAIN_INT;
2527 }
2528 // now apply the master volume and stream type volume
2529 vl = (uint32_t)(v * vl) << 12;
2530 vr = (uint32_t)(v * vr) << 12;
2531 // assuming master volume and stream type volume each go up to 1.0,
2532 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002533
Glenn Kasten05632a52012-01-03 14:22:33 -08002534 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2535 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002536 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002537 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002538 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002539 }
2540 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002541 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002542 // Delegate volume control to effect in track effect chain if needed
2543 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2544 // Do not ramp volume if volume is controlled by effect
2545 param = AudioMixer::VOLUME;
2546 track->mHasVolumeController = true;
2547 } else {
2548 // force no volume ramp when volume controller was just disabled or removed
2549 // from effect chain to avoid volume spike
2550 if (track->mHasVolumeController) {
2551 param = AudioMixer::VOLUME;
2552 }
2553 track->mHasVolumeController = false;
2554 }
2555
2556 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002557 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002558 vl = (vl + (1 << 11)) >> 12;
2559 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2560 vr = (vr + (1 << 11)) >> 12;
2561 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002562
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002563 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 -07002564
Mathias Agopian65ab4712010-07-14 17:59:35 -07002565 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002566 mAudioMixer->setBufferProvider(name, track);
2567 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002568
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002569 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2570 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2571 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002572 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002573 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002574 AudioMixer::TRACK,
2575 AudioMixer::FORMAT, (void *)track->format());
2576 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002577 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002578 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002579 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002580 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002581 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002582 AudioMixer::RESAMPLE,
2583 AudioMixer::SAMPLE_RATE,
2584 (void *)(cblk->sampleRate));
2585 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002586 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002587 AudioMixer::TRACK,
2588 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2589 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002590 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002591 AudioMixer::TRACK,
2592 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2593
2594 // reset retry count
2595 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002596
Eric Laurent27741442012-01-17 19:20:12 -08002597 // If one track is ready, set the mixer ready if:
2598 // - the mixer was not ready during previous round OR
2599 // - no other track is not ready
2600 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2601 mixerStatus != MIXER_TRACKS_ENABLED) {
2602 mixerStatus = MIXER_TRACKS_READY;
2603 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002604 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002605 //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 -07002606 if (track->isStopped()) {
2607 track->reset();
2608 }
2609 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2610 // We have consumed all the buffers of this track.
2611 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07002612 // TODO: use actual buffer filling status instead of latency when available from
2613 // audio HAL
2614 size_t audioHALFrames =
2615 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2616 size_t framesWritten =
2617 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2618 if (track->presentationComplete(framesWritten, audioHALFrames)) {
2619 tracksToRemove->add(track);
2620 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002621 } else {
2622 // No buffers for this track. Give it a few chances to
2623 // fill a buffer, then remove it from active list.
2624 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002625 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002626 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002627 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002628 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002629 // If one track is not ready, mark the mixer also not ready if:
2630 // - the mixer was ready during previous round OR
2631 // - no other track is ready
2632 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2633 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002634 mixerStatus = MIXER_TRACKS_ENABLED;
2635 }
2636 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002637 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002638 }
2639 }
2640
2641 // remove all the tracks that need to be...
2642 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002643 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002644 for (size_t i=0 ; i<count ; i++) {
2645 const sp<Track>& track = tracksToRemove->itemAt(i);
2646 mActiveTracks.remove(track);
2647 if (track->mainBuffer() != mMixBuffer) {
2648 chain = getEffectChain_l(track->sessionId());
2649 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002650 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002651 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002652 }
2653 }
2654 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002655 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002656 }
2657 }
2658 }
2659
2660 // mix buffer must be cleared if all tracks are connected to an
2661 // effect chain as in this case the mixer will not write to
2662 // mix buffer and track effects will accumulate into it
2663 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2664 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2665 }
2666
2667 return mixerStatus;
2668}
2669
Glenn Kasten66fcab92012-02-24 14:59:21 -08002670/*
2671The derived values that are cached:
2672 - mixBufferSize from frame count * frame size
2673 - activeSleepTime from activeSleepTimeUs()
2674 - idleSleepTime from idleSleepTimeUs()
2675 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2676 - maxPeriod from frame count and sample rate (MIXER only)
2677
2678The parameters that affect these derived values are:
2679 - frame count
2680 - frame size
2681 - sample rate
2682 - device type: A2DP or not
2683 - device latency
2684 - format: PCM or not
2685 - active sleep time
2686 - idle sleep time
2687*/
2688
2689void AudioFlinger::PlaybackThread::cacheParameters_l()
2690{
2691 mixBufferSize = mFrameCount * mFrameSize;
2692 activeSleepTime = activeSleepTimeUs();
2693 idleSleepTime = idleSleepTimeUs();
2694}
2695
Glenn Kastenfff6d712012-01-12 16:38:12 -08002696void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002697{
Steve Block3856b092011-10-20 11:56:00 +01002698 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002699 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002700 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002701
Mathias Agopian65ab4712010-07-14 17:59:35 -07002702 size_t size = mTracks.size();
2703 for (size_t i = 0; i < size; i++) {
2704 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08002705 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002706 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002707 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002708 }
2709 }
2710}
2711
Glenn Kastenfff6d712012-01-12 16:38:12 -08002712void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002713{
Steve Block3856b092011-10-20 11:56:00 +01002714 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002715 this, streamType, valid);
2716 Mutex::Autolock _l(mLock);
2717
2718 mStreamTypes[streamType].valid = valid;
2719}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002720
2721// getTrackName_l() must be called with ThreadBase::mLock held
2722int AudioFlinger::MixerThread::getTrackName_l()
2723{
2724 return mAudioMixer->getTrackName();
2725}
2726
2727// deleteTrackName_l() must be called with ThreadBase::mLock held
2728void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2729{
Steve Block3856b092011-10-20 11:56:00 +01002730 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002731 mAudioMixer->deleteTrackName(name);
2732}
2733
2734// checkForNewParameters_l() must be called with ThreadBase::mLock held
2735bool AudioFlinger::MixerThread::checkForNewParameters_l()
2736{
2737 bool reconfig = false;
2738
2739 while (!mNewParameters.isEmpty()) {
2740 status_t status = NO_ERROR;
2741 String8 keyValuePair = mNewParameters[0];
2742 AudioParameter param = AudioParameter(keyValuePair);
2743 int value;
2744
2745 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2746 reconfig = true;
2747 }
2748 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002749 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002750 status = BAD_VALUE;
2751 } else {
2752 reconfig = true;
2753 }
2754 }
2755 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002756 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002757 status = BAD_VALUE;
2758 } else {
2759 reconfig = true;
2760 }
2761 }
2762 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2763 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002764 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002765 // if frame count is changed after track creation
2766 if (!mTracks.isEmpty()) {
2767 status = INVALID_OPERATION;
2768 } else {
2769 reconfig = true;
2770 }
2771 }
2772 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07002773#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08002774 // when changing the audio output device, call addBatteryData to notify
2775 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002776 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002777 uint32_t params = 0;
2778 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002779 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002780 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2781 }
2782
2783 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002784 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002785 // check if any other device (except speaker) is on
2786 if (value & deviceWithoutSpeaker ) {
2787 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2788 }
2789
2790 if (params != 0) {
2791 addBatteryData(params);
2792 }
2793 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07002794#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08002795
Mathias Agopian65ab4712010-07-14 17:59:35 -07002796 // forward device change to effects that have requested to be
2797 // aware of attached audio device.
2798 mDevice = (uint32_t)value;
2799 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002800 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002801 }
2802 }
2803
2804 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002805 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002806 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002807 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002808 mOutput->stream->common.standby(&mOutput->stream->common);
2809 mStandby = true;
2810 mBytesWritten = 0;
2811 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002812 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002813 }
2814 if (status == NO_ERROR && reconfig) {
2815 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002816 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2817 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002818 readOutputParameters();
2819 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2820 for (size_t i = 0; i < mTracks.size() ; i++) {
2821 int name = getTrackName_l();
2822 if (name < 0) break;
2823 mTracks[i]->mName = name;
2824 // limit track sample rate to 2 x new output sample rate
2825 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2826 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2827 }
2828 }
2829 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2830 }
2831 }
2832
2833 mNewParameters.removeAt(0);
2834
2835 mParamStatus = status;
2836 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002837 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2838 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002839 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002840 }
2841 return reconfig;
2842}
2843
2844status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2845{
2846 const size_t SIZE = 256;
2847 char buffer[SIZE];
2848 String8 result;
2849
2850 PlaybackThread::dumpInternals(fd, args);
2851
2852 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2853 result.append(buffer);
2854 write(fd, result.string(), result.size());
2855 return NO_ERROR;
2856}
2857
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002858uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002859{
Eric Laurent60e18242010-07-29 06:50:24 -07002860 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002861}
2862
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002863uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002864{
2865 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2866}
2867
Glenn Kasten66fcab92012-02-24 14:59:21 -08002868void AudioFlinger::MixerThread::cacheParameters_l()
2869{
2870 PlaybackThread::cacheParameters_l();
2871
2872 // FIXME: Relaxed timing because of a certain device that can't meet latency
2873 // Should be reduced to 2x after the vendor fixes the driver issue
2874 // increase threshold again due to low power audio mode. The way this warning
2875 // threshold is calculated and its usefulness should be reconsidered anyway.
2876 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
2877}
2878
Mathias Agopian65ab4712010-07-14 17:59:35 -07002879// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002880AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2881 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002882 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002883 // mLeftVolFloat, mRightVolFloat
2884 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002885{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002886}
2887
2888AudioFlinger::DirectOutputThread::~DirectOutputThread()
2889{
2890}
2891
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002892AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
2893 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08002894)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002895{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002896 sp<Track> trackToRemove;
2897
Glenn Kastenfec279f2012-03-08 07:47:15 -08002898 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002899
Glenn Kasten952eeb22012-03-06 11:30:57 -08002900 // find out which tracks need to be processed
2901 if (mActiveTracks.size() != 0) {
2902 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08002903 // The track died recently
2904 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002905
Glenn Kasten952eeb22012-03-06 11:30:57 -08002906 Track* const track = t.get();
2907 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002908
Glenn Kasten952eeb22012-03-06 11:30:57 -08002909 // The first time a track is added we wait
2910 // for all its buffers to be filled before processing it
2911 if (cblk->framesReady() && track->isReady() &&
2912 !track->isPaused() && !track->isTerminated())
2913 {
2914 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002915
Glenn Kasten952eeb22012-03-06 11:30:57 -08002916 if (track->mFillingUpStatus == Track::FS_FILLED) {
2917 track->mFillingUpStatus = Track::FS_ACTIVE;
2918 mLeftVolFloat = mRightVolFloat = 0;
2919 mLeftVolShort = mRightVolShort = 0;
2920 if (track->mState == TrackBase::RESUMING) {
2921 track->mState = TrackBase::ACTIVE;
2922 rampVolume = true;
2923 }
2924 } else if (cblk->server != 0) {
2925 // If the track is stopped before the first frame was mixed,
2926 // do not apply ramp
2927 rampVolume = true;
2928 }
2929 // compute volume for this track
2930 float left, right;
2931 if (track->isMuted() || mMasterMute || track->isPausing() ||
2932 mStreamTypes[track->streamType()].mute) {
2933 left = right = 0;
2934 if (track->isPausing()) {
2935 track->setPaused();
2936 }
2937 } else {
2938 float typeVolume = mStreamTypes[track->streamType()].volume;
2939 float v = mMasterVolume * typeVolume;
2940 uint32_t vlr = cblk->getVolumeLR();
2941 float v_clamped = v * (vlr & 0xFFFF);
2942 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2943 left = v_clamped/MAX_GAIN;
2944 v_clamped = v * (vlr >> 16);
2945 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2946 right = v_clamped/MAX_GAIN;
2947 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002948
Glenn Kasten952eeb22012-03-06 11:30:57 -08002949 if (left != mLeftVolFloat || right != mRightVolFloat) {
2950 mLeftVolFloat = left;
2951 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002952
Glenn Kasten952eeb22012-03-06 11:30:57 -08002953 // If audio HAL implements volume control,
2954 // force software volume to nominal value
2955 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
2956 left = 1.0f;
2957 right = 1.0f;
2958 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002959
Glenn Kasten952eeb22012-03-06 11:30:57 -08002960 // Convert volumes from float to 8.24
2961 uint32_t vl = (uint32_t)(left * (1 << 24));
2962 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002963
Glenn Kasten952eeb22012-03-06 11:30:57 -08002964 // Delegate volume control to effect in track effect chain if needed
2965 // only one effect chain can be present on DirectOutputThread, so if
2966 // there is one, the track is connected to it
2967 if (!mEffectChains.isEmpty()) {
2968 // Do not ramp volume if volume is controlled by effect
2969 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002970 rampVolume = false;
2971 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002972 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002973
Glenn Kasten952eeb22012-03-06 11:30:57 -08002974 // Convert volumes from 8.24 to 4.12 format
2975 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2976 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2977 leftVol = (uint16_t)v_clamped;
2978 v_clamped = (vr + (1 << 11)) >> 12;
2979 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2980 rightVol = (uint16_t)v_clamped;
2981 } else {
2982 leftVol = mLeftVolShort;
2983 rightVol = mRightVolShort;
2984 rampVolume = false;
2985 }
2986
2987 // reset retry count
2988 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002989 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002990 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002991 } else {
2992 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2993 if (track->isStopped()) {
2994 track->reset();
2995 }
2996 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2997 // We have consumed all the buffers of this track.
2998 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07002999 // TODO: implement behavior for compressed audio
3000 size_t audioHALFrames =
3001 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3002 size_t framesWritten =
3003 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3004 if (track->presentationComplete(framesWritten, audioHALFrames)) {
3005 trackToRemove = track;
3006 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003007 } else {
3008 // No buffers for this track. Give it a few chances to
3009 // fill a buffer, then remove it from active list.
3010 if (--(track->mRetryCount) <= 0) {
3011 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3012 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003013 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003014 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003015 }
3016 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003017 }
3018 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003019
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003020 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003021 // remove all the tracks that need to be...
3022 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003023 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003024 mActiveTracks.remove(trackToRemove);
3025 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003026 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003027 trackToRemove->sessionId());
3028 mEffectChains[0]->decActiveTrackCnt();
3029 }
3030 if (trackToRemove->isTerminated()) {
3031 removeTrack_l(trackToRemove);
3032 }
3033 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003034
Glenn Kastenfec279f2012-03-08 07:47:15 -08003035 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003036}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003037
Glenn Kasten000f0e32012-03-01 17:10:56 -08003038void AudioFlinger::DirectOutputThread::threadLoop_mix()
3039{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003040 AudioBufferProvider::Buffer buffer;
3041 size_t frameCount = mFrameCount;
3042 int8_t *curBuf = (int8_t *)mMixBuffer;
3043 // output audio to hardware
3044 while (frameCount) {
3045 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003046 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003047 if (CC_UNLIKELY(buffer.raw == NULL)) {
3048 memset(curBuf, 0, frameCount * mFrameSize);
3049 break;
3050 }
3051 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3052 frameCount -= buffer.frameCount;
3053 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003054 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003055 }
3056 sleepTime = 0;
3057 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003058 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003059
3060 // apply volume
3061
3062 // Do not apply volume on compressed audio
3063 if (!audio_is_linear_pcm(mFormat)) {
3064 return;
3065 }
3066
3067 // convert to signed 16 bit before volume calculation
3068 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3069 size_t count = mFrameCount * mChannelCount;
3070 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
3071 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003072 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003073 *dst-- = (int16_t)(*src--^0x80) << 8;
3074 }
3075 }
3076
3077 frameCount = mFrameCount;
3078 int16_t *out = mMixBuffer;
3079 if (rampVolume) {
3080 if (mChannelCount == 1) {
3081 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3082 int32_t vlInc = d / (int32_t)frameCount;
3083 int32_t vl = ((int32_t)mLeftVolShort << 16);
3084 do {
3085 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3086 out++;
3087 vl += vlInc;
3088 } while (--frameCount);
3089
3090 } else {
3091 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3092 int32_t vlInc = d / (int32_t)frameCount;
3093 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
3094 int32_t vrInc = d / (int32_t)frameCount;
3095 int32_t vl = ((int32_t)mLeftVolShort << 16);
3096 int32_t vr = ((int32_t)mRightVolShort << 16);
3097 do {
3098 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3099 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3100 out += 2;
3101 vl += vlInc;
3102 vr += vrInc;
3103 } while (--frameCount);
3104 }
3105 } else {
3106 if (mChannelCount == 1) {
3107 do {
3108 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3109 out++;
3110 } while (--frameCount);
3111 } else {
3112 do {
3113 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3114 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3115 out += 2;
3116 } while (--frameCount);
3117 }
3118 }
3119
3120 // convert back to unsigned 8 bit after volume calculation
3121 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3122 size_t count = mFrameCount * mChannelCount;
3123 int16_t *src = mMixBuffer;
3124 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003125 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003126 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3127 }
3128 }
3129
3130 mLeftVolShort = leftVol;
3131 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003132}
3133
3134void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3135{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003136 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003137 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003138 sleepTime = activeSleepTime;
3139 } else {
3140 sleepTime = idleSleepTime;
3141 }
3142 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3143 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
3144 sleepTime = 0;
3145 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003146}
3147
3148// getTrackName_l() must be called with ThreadBase::mLock held
3149int AudioFlinger::DirectOutputThread::getTrackName_l()
3150{
3151 return 0;
3152}
3153
3154// deleteTrackName_l() must be called with ThreadBase::mLock held
3155void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3156{
3157}
3158
3159// checkForNewParameters_l() must be called with ThreadBase::mLock held
3160bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3161{
3162 bool reconfig = false;
3163
3164 while (!mNewParameters.isEmpty()) {
3165 status_t status = NO_ERROR;
3166 String8 keyValuePair = mNewParameters[0];
3167 AudioParameter param = AudioParameter(keyValuePair);
3168 int value;
3169
3170 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3171 // do not accept frame count changes if tracks are open as the track buffer
3172 // size depends on frame count and correct behavior would not be garantied
3173 // if frame count is changed after track creation
3174 if (!mTracks.isEmpty()) {
3175 status = INVALID_OPERATION;
3176 } else {
3177 reconfig = true;
3178 }
3179 }
3180 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003181 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003182 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003183 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003184 mOutput->stream->common.standby(&mOutput->stream->common);
3185 mStandby = true;
3186 mBytesWritten = 0;
3187 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003188 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003189 }
3190 if (status == NO_ERROR && reconfig) {
3191 readOutputParameters();
3192 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3193 }
3194 }
3195
3196 mNewParameters.removeAt(0);
3197
3198 mParamStatus = status;
3199 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003200 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3201 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003202 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003203 }
3204 return reconfig;
3205}
3206
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003207uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003208{
3209 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003210 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003211 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003212 } else {
3213 time = 10000;
3214 }
3215 return time;
3216}
3217
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003218uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003219{
3220 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003221 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003222 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003223 } else {
3224 time = 10000;
3225 }
3226 return time;
3227}
3228
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003229uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003230{
3231 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003232 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003233 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3234 } else {
3235 time = 10000;
3236 }
3237 return time;
3238}
3239
Glenn Kasten66fcab92012-02-24 14:59:21 -08003240void AudioFlinger::DirectOutputThread::cacheParameters_l()
3241{
3242 PlaybackThread::cacheParameters_l();
3243
3244 // use shorter standby delay as on normal output to release
3245 // hardware resources as soon as possible
3246 standbyDelay = microseconds(activeSleepTime*2);
3247}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003248
Mathias Agopian65ab4712010-07-14 17:59:35 -07003249// ----------------------------------------------------------------------------
3250
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003251AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003252 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003253 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3254 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003255{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003256 addOutputTrack(mainThread);
3257}
3258
3259AudioFlinger::DuplicatingThread::~DuplicatingThread()
3260{
3261 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3262 mOutputTracks[i]->destroy();
3263 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003264}
3265
Glenn Kasten000f0e32012-03-01 17:10:56 -08003266void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003267{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003268 // mix buffers...
3269 if (outputsReady(outputTracks)) {
3270 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3271 } else {
3272 memset(mMixBuffer, 0, mixBufferSize);
3273 }
3274 sleepTime = 0;
3275 writeFrames = mFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003276}
3277
3278void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3279{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003280 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003281 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003282 sleepTime = activeSleepTime;
3283 } else {
3284 sleepTime = idleSleepTime;
3285 }
3286 } else if (mBytesWritten != 0) {
3287 // flush remaining overflow buffers in output tracks
3288 for (size_t i = 0; i < outputTracks.size(); i++) {
3289 if (outputTracks[i]->isActive()) {
3290 sleepTime = 0;
3291 writeFrames = 0;
3292 memset(mMixBuffer, 0, mixBufferSize);
3293 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003294 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003295 }
3296 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003297}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003298
Glenn Kasten000f0e32012-03-01 17:10:56 -08003299void AudioFlinger::DuplicatingThread::threadLoop_write()
3300{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003301 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003302 for (size_t i = 0; i < outputTracks.size(); i++) {
3303 outputTracks[i]->write(mMixBuffer, writeFrames);
3304 }
3305 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003306}
Glenn Kasten688a6402012-02-29 07:57:06 -08003307
Glenn Kasten000f0e32012-03-01 17:10:56 -08003308void AudioFlinger::DuplicatingThread::threadLoop_standby()
3309{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003310 // DuplicatingThread implements standby by stopping all tracks
3311 for (size_t i = 0; i < outputTracks.size(); i++) {
3312 outputTracks[i]->stop();
3313 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003314}
3315
Glenn Kastenfa26a852012-03-06 11:28:04 -08003316void AudioFlinger::DuplicatingThread::saveOutputTracks()
3317{
3318 outputTracks = mOutputTracks;
3319}
3320
3321void AudioFlinger::DuplicatingThread::clearOutputTracks()
3322{
3323 outputTracks.clear();
3324}
3325
Mathias Agopian65ab4712010-07-14 17:59:35 -07003326void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3327{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003328 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003329 // FIXME explain this formula
Mathias Agopian65ab4712010-07-14 17:59:35 -07003330 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003331 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003332 this,
3333 mSampleRate,
3334 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003335 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003336 frameCount);
3337 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003338 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003339 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003340 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003341 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003342 }
3343}
3344
3345void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3346{
3347 Mutex::Autolock _l(mLock);
3348 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003349 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003350 mOutputTracks[i]->destroy();
3351 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003352 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003353 return;
3354 }
3355 }
Steve Block3856b092011-10-20 11:56:00 +01003356 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003357}
3358
Glenn Kasten438b0362012-03-06 11:24:48 -08003359// caller must hold mLock
3360void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003361{
3362 mWaitTimeMs = UINT_MAX;
3363 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3364 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003365 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003366 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3367 if (waitTimeMs < mWaitTimeMs) {
3368 mWaitTimeMs = waitTimeMs;
3369 }
3370 }
3371 }
3372}
3373
3374
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003375bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003376{
3377 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003378 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003379 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003380 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003381 return false;
3382 }
3383 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3384 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003385 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003386 return false;
3387 }
3388 }
3389 return true;
3390}
3391
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003392uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003393{
3394 return (mWaitTimeMs * 1000) / 2;
3395}
3396
Glenn Kasten66fcab92012-02-24 14:59:21 -08003397void AudioFlinger::DuplicatingThread::cacheParameters_l()
3398{
3399 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3400 updateWaitTime_l();
3401
3402 MixerThread::cacheParameters_l();
3403}
3404
Mathias Agopian65ab4712010-07-14 17:59:35 -07003405// ----------------------------------------------------------------------------
3406
3407// TrackBase constructor must be called with AudioFlinger::mLock held
3408AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003409 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003410 const sp<Client>& client,
3411 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003412 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003413 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003414 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003415 const sp<IMemory>& sharedBuffer,
3416 int sessionId)
3417 : RefBase(),
3418 mThread(thread),
3419 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003420 mCblk(NULL),
3421 // mBuffer
3422 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003423 mFrameCount(0),
3424 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003425 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003426 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003427 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003428 // mChannelCount
3429 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003430{
Steve Block3856b092011-10-20 11:56:00 +01003431 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003432
Steve Blockb8a80522011-12-20 16:23:08 +00003433 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003434 size_t size = sizeof(audio_track_cblk_t);
3435 uint8_t channelCount = popcount(channelMask);
3436 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3437 if (sharedBuffer == 0) {
3438 size += bufferSize;
3439 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003440
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003441 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003442 mCblkMemory = client->heap()->allocate(size);
3443 if (mCblkMemory != 0) {
3444 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003445 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003446 new(mCblk) audio_track_cblk_t();
3447 // clear all buffers
3448 mCblk->frameCount = frameCount;
3449 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003450// uncomment the following lines to quickly test 32-bit wraparound
3451// mCblk->user = 0xffff0000;
3452// mCblk->server = 0xffff0000;
3453// mCblk->userBase = 0xffff0000;
3454// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003455 mChannelCount = channelCount;
3456 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003457 if (sharedBuffer == 0) {
3458 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3459 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3460 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003461 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003462 mCblk->flags = CBLK_UNDERRUN_ON;
3463 } else {
3464 mBuffer = sharedBuffer->pointer();
3465 }
3466 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3467 }
3468 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003469 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003470 client->heap()->dump("AudioTrack");
3471 return;
3472 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003473 } else {
3474 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07003475 // construct the shared structure in-place.
3476 new(mCblk) audio_track_cblk_t();
3477 // clear all buffers
3478 mCblk->frameCount = frameCount;
3479 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003480// uncomment the following lines to quickly test 32-bit wraparound
3481// mCblk->user = 0xffff0000;
3482// mCblk->server = 0xffff0000;
3483// mCblk->userBase = 0xffff0000;
3484// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003485 mChannelCount = channelCount;
3486 mChannelMask = channelMask;
3487 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3488 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3489 // Force underrun condition to avoid false underrun callback until first data is
3490 // written to buffer (other flags are cleared)
3491 mCblk->flags = CBLK_UNDERRUN_ON;
3492 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003493 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003494}
3495
3496AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3497{
Glenn Kastena0d68332012-01-27 16:47:15 -08003498 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003499 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003500 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003501 } else {
3502 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003503 }
3504 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003505 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003506 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003507 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003508 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003509 // If the client's reference count drops to zero, the associated destructor
3510 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3511 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003512 mClient.clear();
3513 }
3514}
3515
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003516// AudioBufferProvider interface
3517// getNextBuffer() = 0;
3518// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07003519void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3520{
Glenn Kastene0feee32011-12-13 11:53:26 -08003521 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003522 mFrameCount = buffer->frameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003523 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003524 buffer->frameCount = 0;
3525}
3526
3527bool AudioFlinger::ThreadBase::TrackBase::step() {
3528 bool result;
3529 audio_track_cblk_t* cblk = this->cblk();
3530
3531 result = cblk->stepServer(mFrameCount);
3532 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003533 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003534 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003535 }
3536 return result;
3537}
3538
3539void AudioFlinger::ThreadBase::TrackBase::reset() {
3540 audio_track_cblk_t* cblk = this->cblk();
3541
3542 cblk->user = 0;
3543 cblk->server = 0;
3544 cblk->userBase = 0;
3545 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003546 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01003547 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003548}
3549
Mathias Agopian65ab4712010-07-14 17:59:35 -07003550int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3551 return (int)mCblk->sampleRate;
3552}
3553
Mathias Agopian65ab4712010-07-14 17:59:35 -07003554void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3555 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003556 size_t frameSize = cblk->frameSize;
3557 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3558 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003559
3560 // Check validity of returned pointer in case the track control block would have been corrupted.
3561 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003562 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003563 ALOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Marco Nelissena1472d92012-03-30 14:36:54 -07003564 server %u, serverBase %u, user %u, userBase %u",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003565 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003566 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003567 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003568 }
3569
3570 return bufferStart;
3571}
3572
Eric Laurenta011e352012-03-29 15:51:43 -07003573status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
3574{
3575 mSyncEvents.add(event);
3576 return NO_ERROR;
3577}
3578
Mathias Agopian65ab4712010-07-14 17:59:35 -07003579// ----------------------------------------------------------------------------
3580
3581// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3582AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003583 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003584 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003585 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003586 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003587 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003588 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003589 int frameCount,
3590 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07003591 int sessionId,
3592 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003593 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07003594 mMute(false),
3595 // mFillingUpStatus ?
3596 // mRetryCount initialized later when needed
3597 mSharedBuffer(sharedBuffer),
3598 mStreamType(streamType),
3599 mName(-1), // see note below
3600 mMainBuffer(thread->mixBuffer()),
3601 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07003602 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07003603 mPresentationCompleteFrames(0),
3604 mFlags(flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003605{
3606 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003607 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3608 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003609 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kastenf9959012012-03-19 11:14:37 -07003610 // to avoid leaking a track name, do not allocate one unless there is an mCblk
3611 mName = thread->getTrackName_l();
3612 if (mName < 0) {
3613 ALOGE("no more track names available");
3614 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003615 }
Glenn Kastenf9959012012-03-19 11:14:37 -07003616 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003617}
3618
3619AudioFlinger::PlaybackThread::Track::~Track()
3620{
Steve Block3856b092011-10-20 11:56:00 +01003621 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003622 sp<ThreadBase> thread = mThread.promote();
3623 if (thread != 0) {
3624 Mutex::Autolock _l(thread->mLock);
3625 mState = TERMINATED;
3626 }
3627}
3628
3629void AudioFlinger::PlaybackThread::Track::destroy()
3630{
3631 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3632 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08003633 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003634 // we must acquire a strong reference on this Track before locking mLock
3635 // here so that the destructor is called only when exiting this function.
3636 // On the other hand, as long as Track::destroy() is only called by
3637 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3638 // this Track with its member mTrack.
3639 sp<Track> keep(this);
3640 { // scope for mLock
3641 sp<ThreadBase> thread = mThread.promote();
3642 if (thread != 0) {
3643 if (!isOutputTrack()) {
3644 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08003645 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003646
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003647#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003648 // to track the speaker usage
3649 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003650#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003651 }
3652 AudioSystem::releaseOutput(thread->id());
3653 }
3654 Mutex::Autolock _l(thread->mLock);
3655 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3656 playbackThread->destroyTrack_l(this);
3657 }
3658 }
3659}
3660
3661void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3662{
Glenn Kasten83d86532012-01-17 14:39:34 -08003663 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003664 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 -07003665 mName - AudioMixer::TRACK0,
Glenn Kasten44deb052012-02-05 18:09:08 -08003666 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003667 mStreamType,
3668 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003669 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003670 mSessionId,
3671 mFrameCount,
3672 mState,
3673 mMute,
3674 mFillingUpStatus,
3675 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003676 vlr & 0xFFFF,
3677 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003678 mCblk->server,
3679 mCblk->user,
3680 (int)mMainBuffer,
3681 (int)mAuxBuffer);
3682}
3683
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003684// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08003685status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003686 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003687{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003688 audio_track_cblk_t* cblk = this->cblk();
3689 uint32_t framesReady;
3690 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003691
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003692 // Check if last stepServer failed, try to step now
3693 if (mStepServerFailed) {
3694 if (!step()) goto getNextBuffer_exit;
3695 ALOGV("stepServer recovered");
3696 mStepServerFailed = false;
3697 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003698
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003699 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003700
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003701 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003702 uint32_t s = cblk->server;
3703 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3704
3705 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3706 if (framesReq > framesReady) {
3707 framesReq = framesReady;
3708 }
Marco Nelissena1472d92012-03-30 14:36:54 -07003709 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003710 framesReq = bufferEnd - s;
3711 }
3712
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003713 buffer->raw = getBuffer(s, framesReq);
3714 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003715
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003716 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003717 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003718 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003719
3720getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003721 buffer->raw = NULL;
3722 buffer->frameCount = 0;
3723 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3724 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003725}
3726
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003727uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08003728 return mCblk->framesReady();
3729}
3730
Mathias Agopian65ab4712010-07-14 17:59:35 -07003731bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003732 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003733
John Grossman4ff14ba2012-02-08 16:37:41 -08003734 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003735 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3736 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003737 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003738 return true;
3739 }
3740 return false;
3741}
3742
Eric Laurenta011e352012-03-29 15:51:43 -07003743status_t AudioFlinger::PlaybackThread::Track::start(pid_t tid,
3744 AudioSystem::sync_event_t event,
3745 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003746{
3747 status_t status = NO_ERROR;
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003748 ALOGV("start(%d), calling pid %d session %d tid %d",
3749 mName, IPCThreadState::self()->getCallingPid(), mSessionId, tid);
Glenn Kasten73d22752012-03-19 13:38:30 -07003750 // check for use case 2 with missing callback
3751 if (isFastTrack() && (mSharedBuffer == 0) && (tid == 0)) {
3752 ALOGW("AUDIO_POLICY_OUTPUT_FLAG_FAST denied");
3753 mFlags &= ~IAudioFlinger::TRACK_FAST;
3754 // FIXME the track must be invalidated and moved to another thread or
3755 // attached directly to the normal mixer now
3756 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003757 sp<ThreadBase> thread = mThread.promote();
3758 if (thread != 0) {
3759 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003760 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003761 // here the track could be either new, or restarted
3762 // in both cases "unstop" the track
3763 if (mState == PAUSED) {
3764 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003765 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003766 } else {
3767 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003768 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003769 }
3770
3771 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3772 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003773 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003774 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003775
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003776#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003777 // to track the speaker usage
3778 if (status == NO_ERROR) {
3779 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3780 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003781#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003782 }
3783 if (status == NO_ERROR) {
3784 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3785 playbackThread->addTrack_l(this);
3786 } else {
3787 mState = state;
3788 }
3789 } else {
3790 status = BAD_VALUE;
3791 }
3792 return status;
3793}
3794
3795void AudioFlinger::PlaybackThread::Track::stop()
3796{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003797 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003798 sp<ThreadBase> thread = mThread.promote();
3799 if (thread != 0) {
3800 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003801 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003802 if (mState > STOPPED) {
3803 mState = STOPPED;
3804 // If the track is not active (PAUSED and buffers full), flush buffers
3805 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3806 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3807 reset();
3808 }
Steve Block3856b092011-10-20 11:56:00 +01003809 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003810 }
3811 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3812 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003813 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003814 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003815
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003816#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003817 // to track the speaker usage
3818 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003819#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003820 }
3821 }
3822}
3823
3824void AudioFlinger::PlaybackThread::Track::pause()
3825{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003826 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003827 sp<ThreadBase> thread = mThread.promote();
3828 if (thread != 0) {
3829 Mutex::Autolock _l(thread->mLock);
3830 if (mState == ACTIVE || mState == RESUMING) {
3831 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003832 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003833 if (!isOutputTrack()) {
3834 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003835 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003836 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003837
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003838#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003839 // to track the speaker usage
3840 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003841#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003842 }
3843 }
3844 }
3845}
3846
3847void AudioFlinger::PlaybackThread::Track::flush()
3848{
Steve Block3856b092011-10-20 11:56:00 +01003849 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003850 sp<ThreadBase> thread = mThread.promote();
3851 if (thread != 0) {
3852 Mutex::Autolock _l(thread->mLock);
3853 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3854 return;
3855 }
3856 // No point remaining in PAUSED state after a flush => go to
3857 // STOPPED state
3858 mState = STOPPED;
3859
Eric Laurent38ccae22011-03-28 18:37:07 -07003860 // do not reset the track if it is still in the process of being stopped or paused.
3861 // this will be done by prepareTracks_l() when the track is stopped.
3862 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3863 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3864 reset();
3865 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003866 }
3867}
3868
3869void AudioFlinger::PlaybackThread::Track::reset()
3870{
3871 // Do not reset twice to avoid discarding data written just after a flush and before
3872 // the audioflinger thread detects the track is stopped.
3873 if (!mResetDone) {
3874 TrackBase::reset();
3875 // Force underrun condition to avoid false underrun callback until first data is
3876 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003877 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3878 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003879 mFillingUpStatus = FS_FILLING;
3880 mResetDone = true;
Eric Laurenta011e352012-03-29 15:51:43 -07003881 mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003882 }
3883}
3884
3885void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3886{
3887 mMute = muted;
3888}
3889
Mathias Agopian65ab4712010-07-14 17:59:35 -07003890status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3891{
3892 status_t status = DEAD_OBJECT;
3893 sp<ThreadBase> thread = mThread.promote();
3894 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003895 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3896 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003897 }
3898 return status;
3899}
3900
3901void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3902{
3903 mAuxEffectId = EffectId;
3904 mAuxBuffer = buffer;
3905}
3906
Eric Laurenta011e352012-03-29 15:51:43 -07003907bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
3908 size_t audioHalFrames)
3909{
3910 // a track is considered presented when the total number of frames written to audio HAL
3911 // corresponds to the number of frames written when presentationComplete() is called for the
3912 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
3913 if (mPresentationCompleteFrames == 0) {
3914 mPresentationCompleteFrames = framesWritten + audioHalFrames;
3915 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
3916 mPresentationCompleteFrames, audioHalFrames);
3917 }
3918 if (framesWritten >= mPresentationCompleteFrames) {
3919 ALOGV("presentationComplete() session %d complete: framesWritten %d",
3920 mSessionId, framesWritten);
3921 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
3922 mPresentationCompleteFrames = 0;
3923 return true;
3924 }
3925 return false;
3926}
3927
3928void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
3929{
3930 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
3931 if (mSyncEvents[i]->type() == type) {
3932 mSyncEvents[i]->trigger();
3933 mSyncEvents.removeAt(i);
3934 i--;
3935 }
3936 }
3937}
3938
3939
John Grossman4ff14ba2012-02-08 16:37:41 -08003940// timed audio tracks
3941
3942sp<AudioFlinger::PlaybackThread::TimedTrack>
3943AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003944 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003945 const sp<Client>& client,
3946 audio_stream_type_t streamType,
3947 uint32_t sampleRate,
3948 audio_format_t format,
3949 uint32_t channelMask,
3950 int frameCount,
3951 const sp<IMemory>& sharedBuffer,
3952 int sessionId) {
3953 if (!client->reserveTimedTrack())
3954 return NULL;
3955
Glenn Kastena0356762012-03-19 10:38:51 -07003956 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08003957 thread, client, streamType, sampleRate, format, channelMask, frameCount,
3958 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08003959}
3960
3961AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003962 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003963 const sp<Client>& client,
3964 audio_stream_type_t streamType,
3965 uint32_t sampleRate,
3966 audio_format_t format,
3967 uint32_t channelMask,
3968 int frameCount,
3969 const sp<IMemory>& sharedBuffer,
3970 int sessionId)
3971 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07003972 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman4ff14ba2012-02-08 16:37:41 -08003973 mTimedSilenceBuffer(NULL),
3974 mTimedSilenceBufferSize(0),
3975 mTimedAudioOutputOnTime(false),
3976 mMediaTimeTransformValid(false)
3977{
3978 LocalClock lc;
3979 mLocalTimeFreq = lc.getLocalFreq();
3980
3981 mLocalTimeToSampleTransform.a_zero = 0;
3982 mLocalTimeToSampleTransform.b_zero = 0;
3983 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3984 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3985 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3986 &mLocalTimeToSampleTransform.a_to_b_denom);
3987}
3988
3989AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3990 mClient->releaseTimedTrack();
3991 delete [] mTimedSilenceBuffer;
3992}
3993
3994status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3995 size_t size, sp<IMemory>* buffer) {
3996
3997 Mutex::Autolock _l(mTimedBufferQueueLock);
3998
3999 trimTimedBufferQueue_l();
4000
4001 // lazily initialize the shared memory heap for timed buffers
4002 if (mTimedMemoryDealer == NULL) {
4003 const int kTimedBufferHeapSize = 512 << 10;
4004
4005 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4006 "AudioFlingerTimed");
4007 if (mTimedMemoryDealer == NULL)
4008 return NO_MEMORY;
4009 }
4010
4011 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4012 if (newBuffer == NULL) {
4013 newBuffer = mTimedMemoryDealer->allocate(size);
4014 if (newBuffer == NULL)
4015 return NO_MEMORY;
4016 }
4017
4018 *buffer = newBuffer;
4019 return NO_ERROR;
4020}
4021
4022// caller must hold mTimedBufferQueueLock
4023void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4024 int64_t mediaTimeNow;
4025 {
4026 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4027 if (!mMediaTimeTransformValid)
4028 return;
4029
4030 int64_t targetTimeNow;
4031 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4032 ? mCCHelper.getCommonTime(&targetTimeNow)
4033 : mCCHelper.getLocalTime(&targetTimeNow);
4034
4035 if (OK != res)
4036 return;
4037
4038 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4039 &mediaTimeNow)) {
4040 return;
4041 }
4042 }
4043
4044 size_t trimIndex;
4045 for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
4046 if (mTimedBufferQueue[trimIndex].pts() > mediaTimeNow)
4047 break;
4048 }
4049
4050 if (trimIndex) {
4051 mTimedBufferQueue.removeItemsAt(0, trimIndex);
4052 }
4053}
4054
4055status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4056 const sp<IMemory>& buffer, int64_t pts) {
4057
4058 {
4059 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4060 if (!mMediaTimeTransformValid)
4061 return INVALID_OPERATION;
4062 }
4063
4064 Mutex::Autolock _l(mTimedBufferQueueLock);
4065
4066 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4067
4068 return NO_ERROR;
4069}
4070
4071status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4072 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4073
4074 ALOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
4075 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4076 target);
4077
4078 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4079 target == TimedAudioTrack::COMMON_TIME)) {
4080 return BAD_VALUE;
4081 }
4082
4083 Mutex::Autolock lock(mMediaTimeTransformLock);
4084 mMediaTimeTransform = xform;
4085 mMediaTimeTransformTarget = target;
4086 mMediaTimeTransformValid = true;
4087
4088 return NO_ERROR;
4089}
4090
4091#define min(a, b) ((a) < (b) ? (a) : (b))
4092
4093// implementation of getNextBuffer for tracks whose buffers have timestamps
4094status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4095 AudioBufferProvider::Buffer* buffer, int64_t pts)
4096{
4097 if (pts == AudioBufferProvider::kInvalidPTS) {
4098 buffer->raw = 0;
4099 buffer->frameCount = 0;
4100 return INVALID_OPERATION;
4101 }
4102
John Grossman4ff14ba2012-02-08 16:37:41 -08004103 Mutex::Autolock _l(mTimedBufferQueueLock);
4104
4105 while (true) {
4106
4107 // if we have no timed buffers, then fail
4108 if (mTimedBufferQueue.isEmpty()) {
4109 buffer->raw = 0;
4110 buffer->frameCount = 0;
4111 return NOT_ENOUGH_DATA;
4112 }
4113
4114 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4115
4116 // calculate the PTS of the head of the timed buffer queue expressed in
4117 // local time
4118 int64_t headLocalPTS;
4119 {
4120 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4121
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004122 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08004123
4124 if (mMediaTimeTransform.a_to_b_denom == 0) {
4125 // the transform represents a pause, so yield silence
4126 timedYieldSilence(buffer->frameCount, buffer);
4127 return NO_ERROR;
4128 }
4129
4130 int64_t transformedPTS;
4131 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4132 &transformedPTS)) {
4133 // the transform failed. this shouldn't happen, but if it does
4134 // then just drop this buffer
4135 ALOGW("timedGetNextBuffer transform failed");
4136 buffer->raw = 0;
4137 buffer->frameCount = 0;
4138 mTimedBufferQueue.removeAt(0);
4139 return NO_ERROR;
4140 }
4141
4142 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
4143 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
4144 &headLocalPTS)) {
4145 buffer->raw = 0;
4146 buffer->frameCount = 0;
4147 return INVALID_OPERATION;
4148 }
4149 } else {
4150 headLocalPTS = transformedPTS;
4151 }
4152 }
4153
4154 // adjust the head buffer's PTS to reflect the portion of the head buffer
4155 // that has already been consumed
4156 int64_t effectivePTS = headLocalPTS +
4157 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4158
4159 // Calculate the delta in samples between the head of the input buffer
4160 // queue and the start of the next output buffer that will be written.
4161 // If the transformation fails because of over or underflow, it means
4162 // that the sample's position in the output stream is so far out of
4163 // whack that it should just be dropped.
4164 int64_t sampleDelta;
4165 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4166 ALOGV("*** head buffer is too far from PTS: dropped buffer");
4167 mTimedBufferQueue.removeAt(0);
4168 continue;
4169 }
4170 if (!mLocalTimeToSampleTransform.doForwardTransform(
4171 (effectivePTS - pts) << 32, &sampleDelta)) {
4172 ALOGV("*** too late during sample rate transform: dropped buffer");
4173 mTimedBufferQueue.removeAt(0);
4174 continue;
4175 }
4176
4177 ALOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
4178 __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
4179 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
4180 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
4181
4182 // if the delta between the ideal placement for the next input sample and
4183 // the current output position is within this threshold, then we will
4184 // concatenate the next input samples to the previous output
4185 const int64_t kSampleContinuityThreshold =
4186 (static_cast<int64_t>(sampleRate()) << 32) / 10;
4187
4188 // if this is the first buffer of audio that we're emitting from this track
4189 // then it should be almost exactly on time.
4190 const int64_t kSampleStartupThreshold = 1LL << 32;
4191
4192 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
4193 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
4194 // the next input is close enough to being on time, so concatenate it
4195 // with the last output
4196 timedYieldSamples(buffer);
4197
4198 ALOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4199 return NO_ERROR;
4200 } else if (sampleDelta > 0) {
4201 // the gap between the current output position and the proper start of
4202 // the next input sample is too big, so fill it with silence
4203 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4204
4205 timedYieldSilence(framesUntilNextInput, buffer);
4206 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4207 return NO_ERROR;
4208 } else {
4209 // the next input sample is late
4210 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4211 size_t onTimeSamplePosition =
4212 head.position() + lateFrames * mCblk->frameSize;
4213
4214 if (onTimeSamplePosition > head.buffer()->size()) {
4215 // all the remaining samples in the head are too late, so
4216 // drop it and move on
4217 ALOGV("*** too late: dropped buffer");
4218 mTimedBufferQueue.removeAt(0);
4219 continue;
4220 } else {
4221 // skip over the late samples
4222 head.setPosition(onTimeSamplePosition);
4223
4224 // yield the available samples
4225 timedYieldSamples(buffer);
4226
4227 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4228 return NO_ERROR;
4229 }
4230 }
4231 }
4232}
4233
4234// Yield samples from the timed buffer queue head up to the given output
4235// buffer's capacity.
4236//
4237// Caller must hold mTimedBufferQueueLock
4238void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples(
4239 AudioBufferProvider::Buffer* buffer) {
4240
4241 const TimedBuffer& head = mTimedBufferQueue[0];
4242
4243 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4244 head.position());
4245
4246 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4247 mCblk->frameSize);
4248 size_t framesRequested = buffer->frameCount;
4249 buffer->frameCount = min(framesLeftInHead, framesRequested);
4250
4251 mTimedAudioOutputOnTime = true;
4252}
4253
4254// Yield samples of silence up to the given output buffer's capacity
4255//
4256// Caller must hold mTimedBufferQueueLock
4257void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence(
4258 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4259
4260 // lazily allocate a buffer filled with silence
4261 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4262 delete [] mTimedSilenceBuffer;
4263 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4264 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4265 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4266 }
4267
4268 buffer->raw = mTimedSilenceBuffer;
4269 size_t framesRequested = buffer->frameCount;
4270 buffer->frameCount = min(numFrames, framesRequested);
4271
4272 mTimedAudioOutputOnTime = false;
4273}
4274
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004275// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004276void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4277 AudioBufferProvider::Buffer* buffer) {
4278
4279 Mutex::Autolock _l(mTimedBufferQueueLock);
4280
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004281 // If the buffer which was just released is part of the buffer at the head
4282 // of the queue, be sure to update the amt of the buffer which has been
4283 // consumed. If the buffer being returned is not part of the head of the
4284 // queue, its either because the buffer is part of the silence buffer, or
4285 // because the head of the timed queue was trimmed after the mixer called
4286 // getNextBuffer but before the mixer called releaseBuffer.
4287 if ((buffer->raw != mTimedSilenceBuffer) && mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004288 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004289
4290 void* start = head.buffer()->pointer();
Glenn Kastenf063b492012-02-17 16:24:10 -08004291 void* end = (char *) head.buffer()->pointer() + head.buffer()->size();
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004292
4293 if ((buffer->raw >= start) && (buffer->raw <= end)) {
4294 head.setPosition(head.position() +
4295 (buffer->frameCount * mCblk->frameSize));
4296 if (static_cast<size_t>(head.position()) >= head.buffer()->size()) {
4297 mTimedBufferQueue.removeAt(0);
4298 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004299 }
4300 }
4301
4302 buffer->raw = 0;
4303 buffer->frameCount = 0;
4304}
4305
4306uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4307 Mutex::Autolock _l(mTimedBufferQueueLock);
4308
4309 uint32_t frames = 0;
4310 for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4311 const TimedBuffer& tb = mTimedBufferQueue[i];
4312 frames += (tb.buffer()->size() - tb.position()) / mCblk->frameSize;
4313 }
4314
4315 return frames;
4316}
4317
4318AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4319 : mPTS(0), mPosition(0) {}
4320
4321AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4322 const sp<IMemory>& buffer, int64_t pts)
4323 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4324
Mathias Agopian65ab4712010-07-14 17:59:35 -07004325// ----------------------------------------------------------------------------
4326
4327// RecordTrack constructor must be called with AudioFlinger::mLock held
4328AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004329 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004330 const sp<Client>& client,
4331 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004332 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004333 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004334 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004335 int sessionId)
4336 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004337 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004338 mOverflow(false)
4339{
4340 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004341 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
4342 if (format == AUDIO_FORMAT_PCM_16_BIT) {
4343 mCblk->frameSize = mChannelCount * sizeof(int16_t);
4344 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
4345 mCblk->frameSize = mChannelCount * sizeof(int8_t);
4346 } else {
4347 mCblk->frameSize = sizeof(int8_t);
4348 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004349 }
4350}
4351
4352AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4353{
4354 sp<ThreadBase> thread = mThread.promote();
4355 if (thread != 0) {
4356 AudioSystem::releaseInput(thread->id());
4357 }
4358}
4359
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004360// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004361status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004362{
4363 audio_track_cblk_t* cblk = this->cblk();
4364 uint32_t framesAvail;
4365 uint32_t framesReq = buffer->frameCount;
4366
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004367 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004368 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004369 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004370 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004371 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004372 }
4373
4374 framesAvail = cblk->framesAvailable_l();
4375
Glenn Kastenf6b16782011-12-15 09:51:17 -08004376 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004377 uint32_t s = cblk->server;
4378 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4379
4380 if (framesReq > framesAvail) {
4381 framesReq = framesAvail;
4382 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004383 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004384 framesReq = bufferEnd - s;
4385 }
4386
4387 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004388 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004389
4390 buffer->frameCount = framesReq;
4391 return NO_ERROR;
4392 }
4393
4394getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004395 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004396 buffer->frameCount = 0;
4397 return NOT_ENOUGH_DATA;
4398}
4399
Eric Laurenta011e352012-03-29 15:51:43 -07004400status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid,
4401 AudioSystem::sync_event_t event,
4402 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004403{
4404 sp<ThreadBase> thread = mThread.promote();
4405 if (thread != 0) {
4406 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurenta011e352012-03-29 15:51:43 -07004407 return recordThread->start(this, tid, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004408 } else {
4409 return BAD_VALUE;
4410 }
4411}
4412
4413void AudioFlinger::RecordThread::RecordTrack::stop()
4414{
4415 sp<ThreadBase> thread = mThread.promote();
4416 if (thread != 0) {
4417 RecordThread *recordThread = (RecordThread *)thread.get();
4418 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004419 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08004420 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07004421 // read from buffer
4422 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004423 }
4424}
4425
4426void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4427{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004428 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004429 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004430 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004431 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004432 mSessionId,
4433 mFrameCount,
4434 mState,
4435 mCblk->sampleRate,
4436 mCblk->server,
4437 mCblk->user);
4438}
4439
4440
4441// ----------------------------------------------------------------------------
4442
4443AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004444 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004445 DuplicatingThread *sourceThread,
4446 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004447 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004448 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004449 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07004450 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
4451 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004452 mActive(false), mSourceThread(sourceThread)
4453{
4454
Mathias Agopian65ab4712010-07-14 17:59:35 -07004455 if (mCblk != NULL) {
4456 mCblk->flags |= CBLK_DIRECTION_OUT;
4457 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004458 mOutBuffer.frameCount = 0;
4459 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01004460 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004461 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4462 mCblk, mBuffer, mCblk->buffers,
4463 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004464 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004465 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004466 }
4467}
4468
4469AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4470{
4471 clearBufferQueue();
4472}
4473
Eric Laurenta011e352012-03-29 15:51:43 -07004474status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid,
4475 AudioSystem::sync_event_t event,
4476 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004477{
Eric Laurenta011e352012-03-29 15:51:43 -07004478 status_t status = Track::start(tid, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004479 if (status != NO_ERROR) {
4480 return status;
4481 }
4482
4483 mActive = true;
4484 mRetryCount = 127;
4485 return status;
4486}
4487
4488void AudioFlinger::PlaybackThread::OutputTrack::stop()
4489{
4490 Track::stop();
4491 clearBufferQueue();
4492 mOutBuffer.frameCount = 0;
4493 mActive = false;
4494}
4495
4496bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4497{
4498 Buffer *pInBuffer;
4499 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004500 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004501 bool outputBufferFull = false;
4502 inBuffer.frameCount = frames;
4503 inBuffer.i16 = data;
4504
4505 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4506
4507 if (!mActive && frames != 0) {
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004508 start(0);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004509 sp<ThreadBase> thread = mThread.promote();
4510 if (thread != 0) {
4511 MixerThread *mixerThread = (MixerThread *)thread.get();
4512 if (mCblk->frameCount > frames){
4513 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4514 uint32_t startFrames = (mCblk->frameCount - frames);
4515 pInBuffer = new Buffer;
4516 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4517 pInBuffer->frameCount = startFrames;
4518 pInBuffer->i16 = pInBuffer->mBuffer;
4519 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4520 mBufferQueue.add(pInBuffer);
4521 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004522 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004523 }
4524 }
4525 }
4526 }
4527
4528 while (waitTimeLeftMs) {
4529 // First write pending buffers, then new data
4530 if (mBufferQueue.size()) {
4531 pInBuffer = mBufferQueue.itemAt(0);
4532 } else {
4533 pInBuffer = &inBuffer;
4534 }
4535
4536 if (pInBuffer->frameCount == 0) {
4537 break;
4538 }
4539
4540 if (mOutBuffer.frameCount == 0) {
4541 mOutBuffer.frameCount = pInBuffer->frameCount;
4542 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08004543 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01004544 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004545 outputBufferFull = true;
4546 break;
4547 }
4548 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4549 if (waitTimeLeftMs >= waitTimeMs) {
4550 waitTimeLeftMs -= waitTimeMs;
4551 } else {
4552 waitTimeLeftMs = 0;
4553 }
4554 }
4555
4556 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4557 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4558 mCblk->stepUser(outFrames);
4559 pInBuffer->frameCount -= outFrames;
4560 pInBuffer->i16 += outFrames * channelCount;
4561 mOutBuffer.frameCount -= outFrames;
4562 mOutBuffer.i16 += outFrames * channelCount;
4563
4564 if (pInBuffer->frameCount == 0) {
4565 if (mBufferQueue.size()) {
4566 mBufferQueue.removeAt(0);
4567 delete [] pInBuffer->mBuffer;
4568 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01004569 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004570 } else {
4571 break;
4572 }
4573 }
4574 }
4575
4576 // If we could not write all frames, allocate a buffer and queue it for next time.
4577 if (inBuffer.frameCount) {
4578 sp<ThreadBase> thread = mThread.promote();
4579 if (thread != 0 && !thread->standby()) {
4580 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4581 pInBuffer = new Buffer;
4582 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4583 pInBuffer->frameCount = inBuffer.frameCount;
4584 pInBuffer->i16 = pInBuffer->mBuffer;
4585 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4586 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01004587 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004588 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004589 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004590 }
4591 }
4592 }
4593
4594 // Calling write() with a 0 length buffer, means that no more data will be written:
4595 // If no more buffers are pending, fill output track buffer to make sure it is started
4596 // by output mixer.
4597 if (frames == 0 && mBufferQueue.size() == 0) {
4598 if (mCblk->user < mCblk->frameCount) {
4599 frames = mCblk->frameCount - mCblk->user;
4600 pInBuffer = new Buffer;
4601 pInBuffer->mBuffer = new int16_t[frames * channelCount];
4602 pInBuffer->frameCount = frames;
4603 pInBuffer->i16 = pInBuffer->mBuffer;
4604 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4605 mBufferQueue.add(pInBuffer);
4606 } else if (mActive) {
4607 stop();
4608 }
4609 }
4610
4611 return outputBufferFull;
4612}
4613
4614status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4615{
4616 int active;
4617 status_t result;
4618 audio_track_cblk_t* cblk = mCblk;
4619 uint32_t framesReq = buffer->frameCount;
4620
Steve Block3856b092011-10-20 11:56:00 +01004621// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004622 buffer->frameCount = 0;
4623
4624 uint32_t framesAvail = cblk->framesAvailable();
4625
4626
4627 if (framesAvail == 0) {
4628 Mutex::Autolock _l(cblk->lock);
4629 goto start_loop_here;
4630 while (framesAvail == 0) {
4631 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004632 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004633 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004634 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004635 }
4636 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4637 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004638 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004639 }
4640 // read the server count again
4641 start_loop_here:
4642 framesAvail = cblk->framesAvailable_l();
4643 }
4644 }
4645
4646// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004647// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004648// }
4649
4650 if (framesReq > framesAvail) {
4651 framesReq = framesAvail;
4652 }
4653
4654 uint32_t u = cblk->user;
4655 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4656
Marco Nelissena1472d92012-03-30 14:36:54 -07004657 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004658 framesReq = bufferEnd - u;
4659 }
4660
4661 buffer->frameCount = framesReq;
4662 buffer->raw = (void *)cblk->buffer(u);
4663 return NO_ERROR;
4664}
4665
4666
4667void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4668{
4669 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004670
4671 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004672 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004673 delete [] pBuffer->mBuffer;
4674 delete pBuffer;
4675 }
4676 mBufferQueue.clear();
4677}
4678
4679// ----------------------------------------------------------------------------
4680
4681AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4682 : RefBase(),
4683 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08004684 // 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 -07004685 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08004686 mPid(pid),
4687 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004688{
4689 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4690}
4691
4692// Client destructor must be called with AudioFlinger::mLock held
4693AudioFlinger::Client::~Client()
4694{
4695 mAudioFlinger->removeClient_l(mPid);
4696}
4697
Glenn Kasten435dbe62012-01-30 10:15:48 -08004698sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004699{
4700 return mMemoryDealer;
4701}
4702
John Grossman4ff14ba2012-02-08 16:37:41 -08004703// Reserve one of the limited slots for a timed audio track associated
4704// with this client
4705bool AudioFlinger::Client::reserveTimedTrack()
4706{
4707 const int kMaxTimedTracksPerClient = 4;
4708
4709 Mutex::Autolock _l(mTimedTrackLock);
4710
4711 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4712 ALOGW("can not create timed track - pid %d has exceeded the limit",
4713 mPid);
4714 return false;
4715 }
4716
4717 mTimedTrackCount++;
4718 return true;
4719}
4720
4721// Release a slot for a timed audio track
4722void AudioFlinger::Client::releaseTimedTrack()
4723{
4724 Mutex::Autolock _l(mTimedTrackLock);
4725 mTimedTrackCount--;
4726}
4727
Mathias Agopian65ab4712010-07-14 17:59:35 -07004728// ----------------------------------------------------------------------------
4729
4730AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4731 const sp<IAudioFlingerClient>& client,
4732 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004733 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004734{
4735}
4736
4737AudioFlinger::NotificationClient::~NotificationClient()
4738{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004739}
4740
4741void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4742{
4743 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08004744 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004745}
4746
4747// ----------------------------------------------------------------------------
4748
4749AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4750 : BnAudioTrack(),
4751 mTrack(track)
4752{
4753}
4754
4755AudioFlinger::TrackHandle::~TrackHandle() {
4756 // just stop the track on deletion, associated resources
4757 // will be freed from the main thread once all pending buffers have
4758 // been played. Unless it's not in the active track list, in which
4759 // case we free everything now...
4760 mTrack->destroy();
4761}
4762
Glenn Kasten90716c52012-01-26 13:40:12 -08004763sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4764 return mTrack->getCblk();
4765}
4766
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004767status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4768 return mTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004769}
4770
4771void AudioFlinger::TrackHandle::stop() {
4772 mTrack->stop();
4773}
4774
4775void AudioFlinger::TrackHandle::flush() {
4776 mTrack->flush();
4777}
4778
4779void AudioFlinger::TrackHandle::mute(bool e) {
4780 mTrack->mute(e);
4781}
4782
4783void AudioFlinger::TrackHandle::pause() {
4784 mTrack->pause();
4785}
4786
Mathias Agopian65ab4712010-07-14 17:59:35 -07004787status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4788{
4789 return mTrack->attachAuxEffect(EffectId);
4790}
4791
John Grossman4ff14ba2012-02-08 16:37:41 -08004792status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4793 sp<IMemory>* buffer) {
4794 if (!mTrack->isTimedTrack())
4795 return INVALID_OPERATION;
4796
4797 PlaybackThread::TimedTrack* tt =
4798 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4799 return tt->allocateTimedBuffer(size, buffer);
4800}
4801
4802status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4803 int64_t pts) {
4804 if (!mTrack->isTimedTrack())
4805 return INVALID_OPERATION;
4806
4807 PlaybackThread::TimedTrack* tt =
4808 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4809 return tt->queueTimedBuffer(buffer, pts);
4810}
4811
4812status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4813 const LinearTransform& xform, int target) {
4814
4815 if (!mTrack->isTimedTrack())
4816 return INVALID_OPERATION;
4817
4818 PlaybackThread::TimedTrack* tt =
4819 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4820 return tt->setMediaTimeTransform(
4821 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4822}
4823
Mathias Agopian65ab4712010-07-14 17:59:35 -07004824status_t AudioFlinger::TrackHandle::onTransact(
4825 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4826{
4827 return BnAudioTrack::onTransact(code, data, reply, flags);
4828}
4829
4830// ----------------------------------------------------------------------------
4831
4832sp<IAudioRecord> AudioFlinger::openRecord(
4833 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004834 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004835 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004836 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004837 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004838 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08004839 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004840 int *sessionId,
4841 status_t *status)
4842{
4843 sp<RecordThread::RecordTrack> recordTrack;
4844 sp<RecordHandle> recordHandle;
4845 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004846 status_t lStatus;
4847 RecordThread *thread;
4848 size_t inFrameCount;
4849 int lSessionId;
4850
4851 // check calling permissions
4852 if (!recordingAllowed()) {
4853 lStatus = PERMISSION_DENIED;
4854 goto Exit;
4855 }
4856
4857 // add client to list
4858 { // scope for mLock
4859 Mutex::Autolock _l(mLock);
4860 thread = checkRecordThread_l(input);
4861 if (thread == NULL) {
4862 lStatus = BAD_VALUE;
4863 goto Exit;
4864 }
4865
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004866 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004867
4868 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004869 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004870 lSessionId = *sessionId;
4871 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004872 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004873 if (sessionId != NULL) {
4874 *sessionId = lSessionId;
4875 }
4876 }
4877 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004878 recordTrack = thread->createRecordTrack_l(client,
4879 sampleRate,
4880 format,
4881 channelMask,
4882 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004883 lSessionId,
4884 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004885 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004886 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004887 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4888 // destructor is called by the TrackBase destructor with mLock held
4889 client.clear();
4890 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004891 goto Exit;
4892 }
4893
4894 // return to handle to client
4895 recordHandle = new RecordHandle(recordTrack);
4896 lStatus = NO_ERROR;
4897
4898Exit:
4899 if (status) {
4900 *status = lStatus;
4901 }
4902 return recordHandle;
4903}
4904
4905// ----------------------------------------------------------------------------
4906
4907AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4908 : BnAudioRecord(),
4909 mRecordTrack(recordTrack)
4910{
4911}
4912
4913AudioFlinger::RecordHandle::~RecordHandle() {
4914 stop();
4915}
4916
Glenn Kasten90716c52012-01-26 13:40:12 -08004917sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4918 return mRecordTrack->getCblk();
4919}
4920
Eric Laurenta011e352012-03-29 15:51:43 -07004921status_t AudioFlinger::RecordHandle::start(pid_t tid, int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01004922 ALOGV("RecordHandle::start()");
Eric Laurenta011e352012-03-29 15:51:43 -07004923 return mRecordTrack->start(tid, (AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004924}
4925
4926void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004927 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004928 mRecordTrack->stop();
4929}
4930
Mathias Agopian65ab4712010-07-14 17:59:35 -07004931status_t AudioFlinger::RecordHandle::onTransact(
4932 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4933{
4934 return BnAudioRecord::onTransact(code, data, reply, flags);
4935}
4936
4937// ----------------------------------------------------------------------------
4938
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004939AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4940 AudioStreamIn *input,
4941 uint32_t sampleRate,
4942 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004943 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004944 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004945 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004946 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4947 // mRsmpInIndex and mInputBytes set by readInputParameters()
4948 mReqChannelCount(popcount(channels)),
4949 mReqSampleRate(sampleRate)
4950 // mBytesRead is only meaningful while active, and so is cleared in start()
4951 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004952{
Glenn Kasten480b4682012-02-28 12:30:08 -08004953 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07004954
Mathias Agopian65ab4712010-07-14 17:59:35 -07004955 readInputParameters();
4956}
4957
4958
4959AudioFlinger::RecordThread::~RecordThread()
4960{
4961 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004962 delete mResampler;
4963 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004964}
4965
4966void AudioFlinger::RecordThread::onFirstRef()
4967{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004968 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004969}
4970
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004971status_t AudioFlinger::RecordThread::readyToRun()
4972{
4973 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004974 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004975 return status;
4976}
4977
Mathias Agopian65ab4712010-07-14 17:59:35 -07004978bool AudioFlinger::RecordThread::threadLoop()
4979{
4980 AudioBufferProvider::Buffer buffer;
4981 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004982 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004983
Eric Laurent44d98482010-09-30 16:12:31 -07004984 nsecs_t lastWarning = 0;
4985
Eric Laurentfeb0db62011-07-22 09:04:31 -07004986 acquireWakeLock();
4987
Mathias Agopian65ab4712010-07-14 17:59:35 -07004988 // start recording
4989 while (!exitPending()) {
4990
4991 processConfigEvents();
4992
4993 { // scope for mLock
4994 Mutex::Autolock _l(mLock);
4995 checkForNewParameters_l();
4996 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4997 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004998 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004999 mStandby = true;
5000 }
5001
5002 if (exitPending()) break;
5003
Eric Laurentfeb0db62011-07-22 09:04:31 -07005004 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005005 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005006 // go to sleep
5007 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005008 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005009 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005010 continue;
5011 }
5012 if (mActiveTrack != 0) {
5013 if (mActiveTrack->mState == TrackBase::PAUSING) {
5014 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005015 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005016 mStandby = true;
5017 }
5018 mActiveTrack.clear();
5019 mStartStopCond.broadcast();
5020 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5021 if (mReqChannelCount != mActiveTrack->channelCount()) {
5022 mActiveTrack.clear();
5023 mStartStopCond.broadcast();
5024 } else if (mBytesRead != 0) {
5025 // record start succeeds only if first read from audio input
5026 // succeeds
5027 if (mBytesRead > 0) {
5028 mActiveTrack->mState = TrackBase::ACTIVE;
5029 } else {
5030 mActiveTrack.clear();
5031 }
5032 mStartStopCond.broadcast();
5033 }
5034 mStandby = false;
5035 }
5036 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005037 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005038 }
5039
5040 if (mActiveTrack != 0) {
5041 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5042 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005043 unlockEffectChains(effectChains);
5044 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005045 continue;
5046 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005047 for (size_t i = 0; i < effectChains.size(); i ++) {
5048 effectChains[i]->process_l();
5049 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005050
Mathias Agopian65ab4712010-07-14 17:59:35 -07005051 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005052 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005053 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08005054 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005055 // no resampling
5056 while (framesOut) {
5057 size_t framesIn = mFrameCount - mRsmpInIndex;
5058 if (framesIn) {
5059 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
5060 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
5061 if (framesIn > framesOut)
5062 framesIn = framesOut;
5063 mRsmpInIndex += framesIn;
5064 framesOut -= framesIn;
5065 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07005066 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005067 memcpy(dst, src, framesIn * mFrameSize);
5068 } else {
5069 int16_t *src16 = (int16_t *)src;
5070 int16_t *dst16 = (int16_t *)dst;
5071 if (mChannelCount == 1) {
5072 while (framesIn--) {
5073 *dst16++ = *src16;
5074 *dst16++ = *src16++;
5075 }
5076 } else {
5077 while (framesIn--) {
5078 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
5079 src16 += 2;
5080 }
5081 }
5082 }
5083 }
5084 if (framesOut && mFrameCount == mRsmpInIndex) {
5085 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005086 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005087 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005088 framesOut = 0;
5089 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07005090 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005091 mRsmpInIndex = 0;
5092 }
5093 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005094 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005095 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5096 // Force input into standby so that it tries to
5097 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005098 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005099 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005100 }
5101 mRsmpInIndex = mFrameCount;
5102 framesOut = 0;
5103 buffer.frameCount = 0;
5104 }
5105 }
5106 }
5107 } else {
5108 // resampling
5109
5110 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
5111 // alter output frame count as if we were expecting stereo samples
5112 if (mChannelCount == 1 && mReqChannelCount == 1) {
5113 framesOut >>= 1;
5114 }
5115 mResampler->resample(mRsmpOutBuffer, framesOut, this);
5116 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
5117 // are 32 bit aligned which should be always true.
5118 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005119 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005120 // the resampler always outputs stereo samples: do post stereo to mono conversion
5121 int16_t *src = (int16_t *)mRsmpOutBuffer;
5122 int16_t *dst = buffer.i16;
5123 while (framesOut--) {
5124 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
5125 src += 2;
5126 }
5127 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005128 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005129 }
5130
5131 }
Eric Laurenta011e352012-03-29 15:51:43 -07005132 if (mFramestoDrop == 0) {
5133 mActiveTrack->releaseBuffer(&buffer);
5134 } else {
5135 if (mFramestoDrop > 0) {
5136 mFramestoDrop -= buffer.frameCount;
5137 if (mFramestoDrop < 0) {
5138 mFramestoDrop = 0;
5139 }
5140 }
5141 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005142 mActiveTrack->overflow();
5143 }
5144 // client isn't retrieving buffers fast enough
5145 else {
Eric Laurent44d98482010-09-30 16:12:31 -07005146 if (!mActiveTrack->setOverflow()) {
5147 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08005148 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005149 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07005150 lastWarning = now;
5151 }
5152 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005153 // Release the processor for a while before asking for a new buffer.
5154 // This will give the application more chance to read from the buffer and
5155 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005156 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005157 }
5158 }
Eric Laurentec437d82011-07-26 20:54:46 -07005159 // enable changes in effect chain
5160 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005161 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005162 }
5163
5164 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005165 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005166 }
5167 mActiveTrack.clear();
5168
5169 mStartStopCond.broadcast();
5170
Eric Laurentfeb0db62011-07-22 09:04:31 -07005171 releaseWakeLock();
5172
Steve Block3856b092011-10-20 11:56:00 +01005173 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005174 return false;
5175}
5176
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005177
5178sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5179 const sp<AudioFlinger::Client>& client,
5180 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005181 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005182 int channelMask,
5183 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005184 int sessionId,
5185 status_t *status)
5186{
5187 sp<RecordTrack> track;
5188 status_t lStatus;
5189
5190 lStatus = initCheck();
5191 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005192 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005193 goto Exit;
5194 }
5195
5196 { // scope for mLock
5197 Mutex::Autolock _l(mLock);
5198
5199 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005200 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005201
Glenn Kasten7378ca52012-01-20 13:44:40 -08005202 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005203 lStatus = NO_MEMORY;
5204 goto Exit;
5205 }
5206
5207 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005208 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5209 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005210 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005211 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5212 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005213 }
5214 lStatus = NO_ERROR;
5215
5216Exit:
5217 if (status) {
5218 *status = lStatus;
5219 }
5220 return track;
5221}
5222
Eric Laurenta011e352012-03-29 15:51:43 -07005223status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5224 pid_t tid, AudioSystem::sync_event_t event,
5225 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005226{
Eric Laurenta011e352012-03-29 15:51:43 -07005227 ALOGV("RecordThread::start tid=%d, event %d, triggerSession %d", tid, event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005228 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005229 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07005230
5231 if (event == AudioSystem::SYNC_EVENT_NONE) {
5232 mSyncStartEvent.clear();
5233 mFramestoDrop = 0;
5234 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
5235 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
5236 triggerSession,
5237 recordTrack->sessionId(),
5238 syncStartEventCallback,
5239 this);
5240 mFramestoDrop = -1;
5241 }
5242
Mathias Agopian65ab4712010-07-14 17:59:35 -07005243 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005244 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005245 if (mActiveTrack != 0) {
5246 if (recordTrack != mActiveTrack.get()) {
5247 status = -EBUSY;
5248 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5249 mActiveTrack->mState = TrackBase::ACTIVE;
5250 }
5251 return status;
5252 }
5253
5254 recordTrack->mState = TrackBase::IDLE;
5255 mActiveTrack = recordTrack;
5256 mLock.unlock();
5257 status_t status = AudioSystem::startInput(mId);
5258 mLock.lock();
5259 if (status != NO_ERROR) {
5260 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07005261 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005262 return status;
5263 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005264 mRsmpInIndex = mFrameCount;
5265 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005266 if (mResampler != NULL) {
5267 mResampler->reset();
5268 }
5269 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005270 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005271 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005272 mWaitWorkCV.signal();
5273 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005274 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005275 mActiveTrack.clear();
5276 status = INVALID_OPERATION;
5277 goto startError;
5278 }
5279 mStartStopCond.wait(mLock);
5280 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005281 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005282 status = BAD_VALUE;
5283 goto startError;
5284 }
Steve Block3856b092011-10-20 11:56:00 +01005285 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005286 return status;
5287 }
5288startError:
5289 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07005290 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005291 return status;
5292}
5293
Eric Laurenta011e352012-03-29 15:51:43 -07005294void AudioFlinger::RecordThread::clearSyncStartEvent()
5295{
5296 if (mSyncStartEvent != 0) {
5297 mSyncStartEvent->cancel();
5298 }
5299 mSyncStartEvent.clear();
5300}
5301
5302void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5303{
5304 sp<SyncEvent> strongEvent = event.promote();
5305
5306 if (strongEvent != 0) {
5307 RecordThread *me = (RecordThread *)strongEvent->cookie();
5308 me->handleSyncStartEvent(strongEvent);
5309 }
5310}
5311
5312void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
5313{
5314 ALOGV("handleSyncStartEvent() mActiveTrack %p session %d event->listenerSession() %d",
5315 mActiveTrack.get(),
5316 mActiveTrack.get() ? mActiveTrack->sessionId() : 0,
5317 event->listenerSession());
5318
5319 if (mActiveTrack != 0 &&
5320 event == mSyncStartEvent) {
5321 // TODO: use actual buffer filling status instead of 2 buffers when info is available
5322 // from audio HAL
5323 mFramestoDrop = mFrameCount * 2;
5324 mSyncStartEvent.clear();
5325 }
5326}
5327
Mathias Agopian65ab4712010-07-14 17:59:35 -07005328void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005329 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005330 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005331 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005332 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005333 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5334 mActiveTrack->mState = TrackBase::PAUSING;
5335 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005336 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005337 return;
5338 }
5339 mStartStopCond.wait(mLock);
5340 // if we have been restarted, recordTrack == mActiveTrack.get() here
5341 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5342 mLock.unlock();
5343 AudioSystem::stopInput(mId);
5344 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005345 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005346 }
5347 }
5348 }
5349}
5350
Eric Laurenta011e352012-03-29 15:51:43 -07005351bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
5352{
5353 return false;
5354}
5355
5356status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
5357{
5358 if (!isValidSyncEvent(event)) {
5359 return BAD_VALUE;
5360 }
5361
5362 Mutex::Autolock _l(mLock);
5363
5364 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
5365 mTrack->setSyncEvent(event);
5366 return NO_ERROR;
5367 }
5368 return NAME_NOT_FOUND;
5369}
5370
Mathias Agopian65ab4712010-07-14 17:59:35 -07005371status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5372{
5373 const size_t SIZE = 256;
5374 char buffer[SIZE];
5375 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005376
5377 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5378 result.append(buffer);
5379
5380 if (mActiveTrack != 0) {
5381 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005382 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005383 mActiveTrack->dump(buffer, SIZE);
5384 result.append(buffer);
5385
5386 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5387 result.append(buffer);
5388 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5389 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005390 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005391 result.append(buffer);
5392 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5393 result.append(buffer);
5394 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5395 result.append(buffer);
5396
5397
5398 } else {
5399 result.append("No record client\n");
5400 }
5401 write(fd, result.string(), result.size());
5402
5403 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005404 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005405
5406 return NO_ERROR;
5407}
5408
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005409// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005410status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005411{
5412 size_t framesReq = buffer->frameCount;
5413 size_t framesReady = mFrameCount - mRsmpInIndex;
5414 int channelCount;
5415
5416 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005417 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005418 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005419 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005420 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5421 // Force input into standby so that it tries to
5422 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005423 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005424 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005425 }
Glenn Kastene0feee32011-12-13 11:53:26 -08005426 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005427 buffer->frameCount = 0;
5428 return NOT_ENOUGH_DATA;
5429 }
5430 mRsmpInIndex = 0;
5431 framesReady = mFrameCount;
5432 }
5433
5434 if (framesReq > framesReady) {
5435 framesReq = framesReady;
5436 }
5437
5438 if (mChannelCount == 1 && mReqChannelCount == 2) {
5439 channelCount = 1;
5440 } else {
5441 channelCount = 2;
5442 }
5443 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5444 buffer->frameCount = framesReq;
5445 return NO_ERROR;
5446}
5447
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005448// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07005449void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5450{
5451 mRsmpInIndex += buffer->frameCount;
5452 buffer->frameCount = 0;
5453}
5454
5455bool AudioFlinger::RecordThread::checkForNewParameters_l()
5456{
5457 bool reconfig = false;
5458
5459 while (!mNewParameters.isEmpty()) {
5460 status_t status = NO_ERROR;
5461 String8 keyValuePair = mNewParameters[0];
5462 AudioParameter param = AudioParameter(keyValuePair);
5463 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08005464 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005465 int reqSamplingRate = mReqSampleRate;
5466 int reqChannelCount = mReqChannelCount;
5467
5468 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5469 reqSamplingRate = value;
5470 reconfig = true;
5471 }
5472 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08005473 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005474 reconfig = true;
5475 }
5476 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005477 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005478 reconfig = true;
5479 }
5480 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5481 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08005482 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005483 // if frame count is changed after track creation
5484 if (mActiveTrack != 0) {
5485 status = INVALID_OPERATION;
5486 } else {
5487 reconfig = true;
5488 }
5489 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005490 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5491 // forward device change to effects that have requested to be
5492 // aware of attached audio device.
5493 for (size_t i = 0; i < mEffectChains.size(); i++) {
5494 mEffectChains[i]->setDevice_l(value);
5495 }
5496 // store input device and output device but do not forward output device to audio HAL.
5497 // Note that status is ignored by the caller for output device
5498 // (see AudioFlinger::setParameters()
5499 if (value & AUDIO_DEVICE_OUT_ALL) {
5500 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5501 status = BAD_VALUE;
5502 } else {
5503 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07005504 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5505 if (mTrack != NULL) {
5506 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005507 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005508 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5509 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5510 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005511 }
5512 mDevice |= (uint32_t)value;
5513 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005514 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005515 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005516 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005517 mInput->stream->common.standby(&mInput->stream->common);
5518 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5519 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005520 }
5521 if (reconfig) {
5522 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005523 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005524 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005525 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08005526 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
5527 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005528 status = NO_ERROR;
5529 }
5530 if (status == NO_ERROR) {
5531 readInputParameters();
5532 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5533 }
5534 }
5535 }
5536
5537 mNewParameters.removeAt(0);
5538
5539 mParamStatus = status;
5540 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07005541 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5542 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08005543 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005544 }
5545 return reconfig;
5546}
5547
5548String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5549{
Dima Zavinfce7a472011-04-19 22:30:36 -07005550 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005551 String8 out_s8 = String8();
5552
5553 Mutex::Autolock _l(mLock);
5554 if (initCheck() != NO_ERROR) {
5555 return out_s8;
5556 }
Dima Zavinfce7a472011-04-19 22:30:36 -07005557
Dima Zavin799a70e2011-04-18 16:57:27 -07005558 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07005559 out_s8 = String8(s);
5560 free(s);
5561 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005562}
5563
5564void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5565 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08005566 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005567
5568 switch (event) {
5569 case AudioSystem::INPUT_OPENED:
5570 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005571 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005572 desc.samplingRate = mSampleRate;
5573 desc.format = mFormat;
5574 desc.frameCount = mFrameCount;
5575 desc.latency = 0;
5576 param2 = &desc;
5577 break;
5578
5579 case AudioSystem::INPUT_CLOSED:
5580 default:
5581 break;
5582 }
5583 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5584}
5585
5586void AudioFlinger::RecordThread::readInputParameters()
5587{
Glenn Kastene9dd0172012-01-27 18:08:45 -08005588 delete mRsmpInBuffer;
5589 // mRsmpInBuffer is always assigned a new[] below
5590 delete mRsmpOutBuffer;
5591 mRsmpOutBuffer = NULL;
5592 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08005593 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005594
Dima Zavin799a70e2011-04-18 16:57:27 -07005595 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005596 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5597 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07005598 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08005599 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07005600 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005601 mFrameCount = mInputBytes / mFrameSize;
5602 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5603
Glenn Kasten53d76db2012-03-08 12:32:47 -08005604 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005605 {
5606 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005607 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5608 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005609 if (mChannelCount == 1 && mReqChannelCount == 2) {
5610 channelCount = 1;
5611 } else {
5612 channelCount = 2;
5613 }
5614 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5615 mResampler->setSampleRate(mSampleRate);
5616 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5617 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5618
5619 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5620 if (mChannelCount == 1 && mReqChannelCount == 1) {
5621 mFrameCount >>= 1;
5622 }
5623
5624 }
5625 mRsmpInIndex = mFrameCount;
5626}
5627
5628unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5629{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005630 Mutex::Autolock _l(mLock);
5631 if (initCheck() != NO_ERROR) {
5632 return 0;
5633 }
5634
Dima Zavin799a70e2011-04-18 16:57:27 -07005635 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005636}
5637
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005638uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5639{
5640 Mutex::Autolock _l(mLock);
5641 uint32_t result = 0;
5642 if (getEffectChain_l(sessionId) != 0) {
5643 result = EFFECT_SESSION;
5644 }
5645
5646 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5647 result |= TRACK_SESSION;
5648 }
5649
5650 return result;
5651}
5652
Eric Laurent59bd0da2011-08-01 09:52:20 -07005653AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5654{
5655 Mutex::Autolock _l(mLock);
5656 return mTrack;
5657}
5658
Glenn Kastenaed850d2012-01-26 09:46:34 -08005659AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005660{
5661 Mutex::Autolock _l(mLock);
5662 return mInput;
5663}
5664
5665AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5666{
5667 Mutex::Autolock _l(mLock);
5668 AudioStreamIn *input = mInput;
5669 mInput = NULL;
5670 return input;
5671}
5672
5673// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08005674audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005675{
5676 if (mInput == NULL) {
5677 return NULL;
5678 }
5679 return &mInput->stream->common;
5680}
5681
5682
Mathias Agopian65ab4712010-07-14 17:59:35 -07005683// ----------------------------------------------------------------------------
5684
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005685audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005686 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005687 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005688 uint32_t *pChannels,
5689 uint32_t *pLatencyMs,
Glenn Kasten18868c52012-03-07 09:15:37 -08005690 audio_policy_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005691{
5692 status_t status;
5693 PlaybackThread *thread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005694 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005695 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005696 uint32_t channels = pChannels ? *pChannels : 0;
5697 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07005698 audio_stream_out_t *outStream;
5699 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005700
Steve Block3856b092011-10-20 11:56:00 +01005701 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07005702 pDevices ? *pDevices : 0,
5703 samplingRate,
5704 format,
5705 channels,
5706 flags);
5707
5708 if (pDevices == NULL || *pDevices == 0) {
5709 return 0;
5710 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005711
Mathias Agopian65ab4712010-07-14 17:59:35 -07005712 Mutex::Autolock _l(mLock);
5713
Dima Zavin799a70e2011-04-18 16:57:27 -07005714 outHwDev = findSuitableHwDev_l(*pDevices);
5715 if (outHwDev == NULL)
5716 return 0;
5717
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005718 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Glenn Kasten58f30212012-01-12 12:27:51 -08005719 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005720 &channels, &samplingRate, &outStream);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005721 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01005722 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005723 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005724 samplingRate,
5725 format,
5726 channels,
5727 status);
5728
Dima Zavin799a70e2011-04-18 16:57:27 -07005729 if (outStream != NULL) {
5730 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005731 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07005732
Dima Zavinfce7a472011-04-19 22:30:36 -07005733 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5734 (format != AUDIO_FORMAT_PCM_16_BIT) ||
5735 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005736 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005737 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005738 } else {
5739 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005740 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005741 }
5742 mPlaybackThreads.add(id, thread);
5743
Glenn Kastena0d68332012-01-27 16:47:15 -08005744 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5745 if (pFormat != NULL) *pFormat = format;
5746 if (pChannels != NULL) *pChannels = channels;
5747 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005748
5749 // notify client processes of the new output creation
5750 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5751 return id;
5752 }
5753
5754 return 0;
5755}
5756
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005757audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
5758 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005759{
5760 Mutex::Autolock _l(mLock);
5761 MixerThread *thread1 = checkMixerThread_l(output1);
5762 MixerThread *thread2 = checkMixerThread_l(output2);
5763
5764 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005765 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005766 return 0;
5767 }
5768
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005769 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005770 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5771 thread->addOutputTrack(thread2);
5772 mPlaybackThreads.add(id, thread);
5773 // notify client processes of the new output creation
5774 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5775 return id;
5776}
5777
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005778status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005779{
5780 // keep strong reference on the playback thread so that
5781 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005782 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005783 {
5784 Mutex::Autolock _l(mLock);
5785 thread = checkPlaybackThread_l(output);
5786 if (thread == NULL) {
5787 return BAD_VALUE;
5788 }
5789
Steve Block3856b092011-10-20 11:56:00 +01005790 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005791
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005792 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005793 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005794 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005795 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5796 dupThread->removeOutputTrack((MixerThread *)thread.get());
5797 }
5798 }
5799 }
Glenn Kastena1117922012-01-26 10:53:32 -08005800 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005801 mPlaybackThreads.removeItem(output);
5802 }
5803 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005804 // The thread entity (active unit of execution) is no longer running here,
5805 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005806
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005807 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005808 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005809 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005810 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005811 out->hwDev->close_output_stream(out->hwDev, out->stream);
5812 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005813 }
5814 return NO_ERROR;
5815}
5816
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005817status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005818{
5819 Mutex::Autolock _l(mLock);
5820 PlaybackThread *thread = checkPlaybackThread_l(output);
5821
5822 if (thread == NULL) {
5823 return BAD_VALUE;
5824 }
5825
Steve Block3856b092011-10-20 11:56:00 +01005826 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005827 thread->suspend();
5828
5829 return NO_ERROR;
5830}
5831
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005832status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005833{
5834 Mutex::Autolock _l(mLock);
5835 PlaybackThread *thread = checkPlaybackThread_l(output);
5836
5837 if (thread == NULL) {
5838 return BAD_VALUE;
5839 }
5840
Steve Block3856b092011-10-20 11:56:00 +01005841 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005842
5843 thread->restore();
5844
5845 return NO_ERROR;
5846}
5847
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005848audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005849 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005850 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005851 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005852 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005853{
5854 status_t status;
5855 RecordThread *thread = NULL;
5856 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005857 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005858 uint32_t channels = pChannels ? *pChannels : 0;
5859 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005860 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005861 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005862 audio_stream_in_t *inStream;
5863 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005864
5865 if (pDevices == NULL || *pDevices == 0) {
5866 return 0;
5867 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005868
Mathias Agopian65ab4712010-07-14 17:59:35 -07005869 Mutex::Autolock _l(mLock);
5870
Dima Zavin799a70e2011-04-18 16:57:27 -07005871 inHwDev = findSuitableHwDev_l(*pDevices);
5872 if (inHwDev == NULL)
5873 return 0;
5874
Glenn Kasten58f30212012-01-12 12:27:51 -08005875 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005876 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005877 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005878 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005879 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005880 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005881 samplingRate,
5882 format,
5883 channels,
5884 acoustics,
5885 status);
5886
5887 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5888 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5889 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005890 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005891 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005892 (samplingRate <= 2 * reqSamplingRate) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08005893 (popcount(channels) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01005894 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005895 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005896 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005897 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005898 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005899 }
5900
Dima Zavin799a70e2011-04-18 16:57:27 -07005901 if (inStream != NULL) {
5902 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5903
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005904 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005905 // Start record thread
5906 // RecorThread require both input and output device indication to forward to audio
5907 // pre processing modules
5908 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5909 thread = new RecordThread(this,
5910 input,
5911 reqSamplingRate,
5912 reqChannels,
5913 id,
5914 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005915 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005916 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005917 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5918 if (pFormat != NULL) *pFormat = format;
5919 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005920
Dima Zavin799a70e2011-04-18 16:57:27 -07005921 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005922
5923 // notify client processes of the new input creation
5924 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5925 return id;
5926 }
5927
5928 return 0;
5929}
5930
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005931status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005932{
5933 // keep strong reference on the record thread so that
5934 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005935 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005936 {
5937 Mutex::Autolock _l(mLock);
5938 thread = checkRecordThread_l(input);
5939 if (thread == NULL) {
5940 return BAD_VALUE;
5941 }
5942
Steve Block3856b092011-10-20 11:56:00 +01005943 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08005944 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005945 mRecordThreads.removeItem(input);
5946 }
5947 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005948 // The thread entity (active unit of execution) is no longer running here,
5949 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005950
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005951 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005952 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005953 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005954 in->hwDev->close_input_stream(in->hwDev, in->stream);
5955 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005956
5957 return NO_ERROR;
5958}
5959
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005960status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005961{
5962 Mutex::Autolock _l(mLock);
5963 MixerThread *dstThread = checkMixerThread_l(output);
5964 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005965 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005966 return BAD_VALUE;
5967 }
5968
Steve Block3856b092011-10-20 11:56:00 +01005969 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005970 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5971
Eric Laurent9f6530f2011-08-30 10:18:54 -07005972 dstThread->setStreamValid(stream, true);
5973
Mathias Agopian65ab4712010-07-14 17:59:35 -07005974 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5975 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08005976 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005977 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005978 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005979 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005980 }
Eric Laurentde070132010-07-13 04:45:46 -07005981 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005982
5983 return NO_ERROR;
5984}
5985
5986
5987int AudioFlinger::newAudioSessionId()
5988{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005989 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005990}
5991
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005992void AudioFlinger::acquireAudioSessionId(int audioSession)
5993{
5994 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005995 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005996 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005997 size_t num = mAudioSessionRefs.size();
5998 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005999 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006000 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6001 ref->mCnt++;
6002 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006003 return;
6004 }
6005 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006006 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
6007 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006008}
6009
6010void AudioFlinger::releaseAudioSessionId(int audioSession)
6011{
6012 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006013 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006014 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006015 size_t num = mAudioSessionRefs.size();
6016 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006017 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006018 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6019 ref->mCnt--;
6020 ALOGV(" decremented refcount to %d", ref->mCnt);
6021 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006022 mAudioSessionRefs.removeAt(i);
6023 delete ref;
6024 purgeStaleEffects_l();
6025 }
6026 return;
6027 }
6028 }
Steve Block5ff1dd52012-01-05 23:22:43 +00006029 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006030}
6031
6032void AudioFlinger::purgeStaleEffects_l() {
6033
Steve Block3856b092011-10-20 11:56:00 +01006034 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006035
6036 Vector< sp<EffectChain> > chains;
6037
6038 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6039 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
6040 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6041 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07006042 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
6043 chains.push(ec);
6044 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006045 }
6046 }
6047 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6048 sp<RecordThread> t = mRecordThreads.valueAt(i);
6049 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6050 sp<EffectChain> ec = t->mEffectChains[j];
6051 chains.push(ec);
6052 }
6053 }
6054
6055 for (size_t i = 0; i < chains.size(); i++) {
6056 sp<EffectChain> ec = chains[i];
6057 int sessionid = ec->sessionId();
6058 sp<ThreadBase> t = ec->mThread.promote();
6059 if (t == 0) {
6060 continue;
6061 }
6062 size_t numsessionrefs = mAudioSessionRefs.size();
6063 bool found = false;
6064 for (size_t k = 0; k < numsessionrefs; k++) {
6065 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006066 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01006067 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006068 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006069 found = true;
6070 break;
6071 }
6072 }
6073 if (!found) {
6074 // remove all effects from the chain
6075 while (ec->mEffects.size()) {
6076 sp<EffectModule> effect = ec->mEffects[0];
6077 effect->unPin();
6078 Mutex::Autolock _l (t->mLock);
6079 t->removeEffect_l(effect);
6080 for (size_t j = 0; j < effect->mHandles.size(); j++) {
6081 sp<EffectHandle> handle = effect->mHandles[j].promote();
6082 if (handle != 0) {
6083 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07006084 if (handle->mHasControl && handle->mEnabled) {
6085 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
6086 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006087 }
6088 }
6089 AudioSystem::unregisterEffect(effect->id());
6090 }
6091 }
6092 }
6093 return;
6094}
6095
Mathias Agopian65ab4712010-07-14 17:59:35 -07006096// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006097AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006098{
Glenn Kastena1117922012-01-26 10:53:32 -08006099 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006100}
6101
6102// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006103AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006104{
6105 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08006106 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006107}
6108
6109// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006110AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006111{
Glenn Kastena1117922012-01-26 10:53:32 -08006112 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006113}
6114
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006115uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07006116{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006117 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006118}
6119
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006120AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006121{
6122 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6123 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006124 AudioStreamOut *output = thread->getOutput();
6125 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006126 return thread;
6127 }
6128 }
6129 return NULL;
6130}
6131
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006132uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006133{
6134 PlaybackThread *thread = primaryPlaybackThread_l();
6135
6136 if (thread == NULL) {
6137 return 0;
6138 }
6139
6140 return thread->device();
6141}
6142
Eric Laurenta011e352012-03-29 15:51:43 -07006143sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
6144 int triggerSession,
6145 int listenerSession,
6146 sync_event_callback_t callBack,
6147 void *cookie)
6148{
6149 Mutex::Autolock _l(mLock);
6150
6151 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
6152 status_t playStatus = NAME_NOT_FOUND;
6153 status_t recStatus = NAME_NOT_FOUND;
6154 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6155 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
6156 if (playStatus == NO_ERROR) {
6157 return event;
6158 }
6159 }
6160 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6161 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
6162 if (recStatus == NO_ERROR) {
6163 return event;
6164 }
6165 }
6166 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
6167 mPendingSyncEvents.add(event);
6168 } else {
6169 ALOGV("createSyncEvent() invalid event %d", event->type());
6170 event.clear();
6171 }
6172 return event;
6173}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006174
Mathias Agopian65ab4712010-07-14 17:59:35 -07006175// ----------------------------------------------------------------------------
6176// Effect management
6177// ----------------------------------------------------------------------------
6178
6179
Glenn Kastenf587ba52012-01-26 16:25:10 -08006180status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006181{
6182 Mutex::Autolock _l(mLock);
6183 return EffectQueryNumberEffects(numEffects);
6184}
6185
Glenn Kastenf587ba52012-01-26 16:25:10 -08006186status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006187{
6188 Mutex::Autolock _l(mLock);
6189 return EffectQueryEffect(index, descriptor);
6190}
6191
Glenn Kasten5e92a782012-01-30 07:40:52 -08006192status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08006193 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006194{
6195 Mutex::Autolock _l(mLock);
6196 return EffectGetDescriptor(pUuid, descriptor);
6197}
6198
6199
Mathias Agopian65ab4712010-07-14 17:59:35 -07006200sp<IEffect> AudioFlinger::createEffect(pid_t pid,
6201 effect_descriptor_t *pDesc,
6202 const sp<IEffectClient>& effectClient,
6203 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006204 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006205 int sessionId,
6206 status_t *status,
6207 int *id,
6208 int *enabled)
6209{
6210 status_t lStatus = NO_ERROR;
6211 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006212 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006213
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006214 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006215 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006216
6217 if (pDesc == NULL) {
6218 lStatus = BAD_VALUE;
6219 goto Exit;
6220 }
6221
Eric Laurent84e9a102010-09-23 16:10:16 -07006222 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006223 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006224 lStatus = PERMISSION_DENIED;
6225 goto Exit;
6226 }
6227
Dima Zavinfce7a472011-04-19 22:30:36 -07006228 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07006229 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08006230 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006231 lStatus = PERMISSION_DENIED;
6232 goto Exit;
6233 }
6234
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006235 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006236 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006237 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07006238 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07006239 lStatus = BAD_VALUE;
6240 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07006241 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006242 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006243 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07006244 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006245 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07006246 }
6247 }
6248
Mathias Agopian65ab4712010-07-14 17:59:35 -07006249 {
6250 Mutex::Autolock _l(mLock);
6251
Mathias Agopian65ab4712010-07-14 17:59:35 -07006252
6253 if (!EffectIsNullUuid(&pDesc->uuid)) {
6254 // if uuid is specified, request effect descriptor
6255 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
6256 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006257 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006258 goto Exit;
6259 }
6260 } else {
6261 // if uuid is not specified, look for an available implementation
6262 // of the required type in effect factory
6263 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006264 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006265 lStatus = BAD_VALUE;
6266 goto Exit;
6267 }
6268 uint32_t numEffects = 0;
6269 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006270 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07006271 bool found = false;
6272
6273 lStatus = EffectQueryNumberEffects(&numEffects);
6274 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006275 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006276 goto Exit;
6277 }
6278 for (uint32_t i = 0; i < numEffects; i++) {
6279 lStatus = EffectQueryEffect(i, &desc);
6280 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006281 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006282 continue;
6283 }
6284 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
6285 // If matching type found save effect descriptor. If the session is
6286 // 0 and the effect is not auxiliary, continue enumeration in case
6287 // an auxiliary version of this effect type is available
6288 found = true;
6289 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07006290 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006291 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6292 break;
6293 }
6294 }
6295 }
6296 if (!found) {
6297 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00006298 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006299 goto Exit;
6300 }
6301 // For same effect type, chose auxiliary version over insert version if
6302 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07006303 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006304 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
6305 memcpy(&desc, &d, sizeof(effect_descriptor_t));
6306 }
6307 }
6308
6309 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07006310 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006311 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6312 lStatus = INVALID_OPERATION;
6313 goto Exit;
6314 }
6315
Eric Laurent59255e42011-07-27 19:49:51 -07006316 // check recording permission for visualizer
6317 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
6318 !recordingAllowed()) {
6319 lStatus = PERMISSION_DENIED;
6320 goto Exit;
6321 }
6322
Mathias Agopian65ab4712010-07-14 17:59:35 -07006323 // return effect descriptor
6324 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
6325
6326 // If output is not specified try to find a matching audio session ID in one of the
6327 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07006328 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
6329 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006330 // Note: io is never 0 when creating an effect on an input
6331 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006332 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07006333 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6334 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006335 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07006336 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07006337 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006338 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006339 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006340 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6341 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6342 io = mRecordThreads.keyAt(i);
6343 break;
6344 }
6345 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006346 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006347 // If no output thread contains the requested session ID, default to
6348 // first output. The effect chain will be moved to the correct output
6349 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006350 if (io == 0 && mPlaybackThreads.size()) {
6351 io = mPlaybackThreads.keyAt(0);
6352 }
Steve Block3856b092011-10-20 11:56:00 +01006353 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006354 }
6355 ThreadBase *thread = checkRecordThread_l(io);
6356 if (thread == NULL) {
6357 thread = checkPlaybackThread_l(io);
6358 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00006359 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006360 lStatus = BAD_VALUE;
6361 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07006362 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006363 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006364
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006365 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006366
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006367 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07006368 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6369 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006370 if (handle != 0 && id != NULL) {
6371 *id = handle->id();
6372 }
6373 }
6374
6375Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006376 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006377 *status = lStatus;
6378 }
6379 return handle;
6380}
6381
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006382status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
6383 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07006384{
Steve Block3856b092011-10-20 11:56:00 +01006385 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07006386 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006387 Mutex::Autolock _l(mLock);
6388 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006389 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006390 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006391 }
Eric Laurentde070132010-07-13 04:45:46 -07006392 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6393 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006394 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006395 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006396 }
Eric Laurentde070132010-07-13 04:45:46 -07006397 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6398 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006399 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006400 return BAD_VALUE;
6401 }
6402
6403 Mutex::Autolock _dl(dstThread->mLock);
6404 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07006405 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07006406
Mathias Agopian65ab4712010-07-14 17:59:35 -07006407 return NO_ERROR;
6408}
6409
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006410// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07006411status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07006412 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07006413 AudioFlinger::PlaybackThread *dstThread,
6414 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07006415{
Steve Block3856b092011-10-20 11:56:00 +01006416 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006417 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07006418
Eric Laurent59255e42011-07-27 19:49:51 -07006419 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006420 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006421 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006422 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07006423 return INVALID_OPERATION;
6424 }
6425
Eric Laurent39e94f82010-07-28 01:32:47 -07006426 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07006427 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07006428 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07006429 // removed.
6430 srcThread->removeEffectChain_l(chain);
6431
6432 // transfer all effects one by one so that new effect chain is created on new thread with
6433 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006434 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07006435 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006436 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07006437 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6438 while (effect != 0) {
6439 srcThread->removeEffect_l(effect);
6440 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07006441 // removeEffect_l() has stopped the effect if it was active so it must be restarted
6442 if (effect->state() == EffectModule::ACTIVE ||
6443 effect->state() == EffectModule::STOPPING) {
6444 effect->start();
6445 }
Eric Laurent39e94f82010-07-28 01:32:47 -07006446 // if the move request is not received from audio policy manager, the effect must be
6447 // re-registered with the new strategy and output
6448 if (dstChain == 0) {
6449 dstChain = effect->chain().promote();
6450 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006451 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07006452 srcThread->addEffect_l(effect);
6453 return NO_INIT;
6454 }
6455 strategy = dstChain->strategy();
6456 }
6457 if (reRegister) {
6458 AudioSystem::unregisterEffect(effect->id());
6459 AudioSystem::registerEffect(&effect->desc(),
6460 dstOutput,
6461 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07006462 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07006463 effect->id());
6464 }
Eric Laurentde070132010-07-13 04:45:46 -07006465 effect = chain->getEffectFromId_l(0);
6466 }
6467
6468 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006469}
6470
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006471
Mathias Agopian65ab4712010-07-14 17:59:35 -07006472// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006473sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07006474 const sp<AudioFlinger::Client>& client,
6475 const sp<IEffectClient>& effectClient,
6476 int32_t priority,
6477 int sessionId,
6478 effect_descriptor_t *desc,
6479 int *enabled,
6480 status_t *status
6481 )
6482{
6483 sp<EffectModule> effect;
6484 sp<EffectHandle> handle;
6485 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006486 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07006487 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006488 bool effectCreated = false;
6489 bool effectRegistered = false;
6490
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006491 lStatus = initCheck();
6492 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006493 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006494 goto Exit;
6495 }
6496
6497 // Do not allow effects with session ID 0 on direct output or duplicating threads
6498 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07006499 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006500 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07006501 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006502 lStatus = BAD_VALUE;
6503 goto Exit;
6504 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006505 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08006506 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006507 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006508 desc->name, desc->flags, mType);
6509 lStatus = BAD_VALUE;
6510 goto Exit;
6511 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006512
Steve Block3856b092011-10-20 11:56:00 +01006513 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006514
6515 { // scope for mLock
6516 Mutex::Autolock _l(mLock);
6517
6518 // check for existing effect chain with the requested audio session
6519 chain = getEffectChain_l(sessionId);
6520 if (chain == 0) {
6521 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006522 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006523 chain = new EffectChain(this, sessionId);
6524 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07006525 chain->setStrategy(getStrategyForSession_l(sessionId));
6526 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006527 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07006528 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006529 }
6530
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08006531 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006532
6533 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006534 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006535 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07006536 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006537 if (lStatus != NO_ERROR) {
6538 goto Exit;
6539 }
6540 effectRegistered = true;
6541 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07006542 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006543 lStatus = effect->status();
6544 if (lStatus != NO_ERROR) {
6545 goto Exit;
6546 }
Eric Laurentcab11242010-07-15 12:50:15 -07006547 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006548 if (lStatus != NO_ERROR) {
6549 goto Exit;
6550 }
6551 effectCreated = true;
6552
6553 effect->setDevice(mDevice);
6554 effect->setMode(mAudioFlinger->getMode());
6555 }
6556 // create effect handle and connect it to effect module
6557 handle = new EffectHandle(effect, client, effectClient, priority);
6558 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08006559 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006560 *enabled = (int)effect->isEnabled();
6561 }
6562 }
6563
6564Exit:
6565 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07006566 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006567 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07006568 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006569 }
6570 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07006571 AudioSystem::unregisterEffect(effect->id());
6572 }
6573 if (chainCreated) {
6574 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006575 }
6576 handle.clear();
6577 }
6578
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006579 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006580 *status = lStatus;
6581 }
6582 return handle;
6583}
6584
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006585sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6586{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006587 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08006588 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006589}
6590
Eric Laurentde070132010-07-13 04:45:46 -07006591// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6592// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006593status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07006594{
6595 // check for existing effect chain with the requested audio session
6596 int sessionId = effect->sessionId();
6597 sp<EffectChain> chain = getEffectChain_l(sessionId);
6598 bool chainCreated = false;
6599
6600 if (chain == 0) {
6601 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006602 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006603 chain = new EffectChain(this, sessionId);
6604 addEffectChain_l(chain);
6605 chain->setStrategy(getStrategyForSession_l(sessionId));
6606 chainCreated = true;
6607 }
Steve Block3856b092011-10-20 11:56:00 +01006608 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006609
6610 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006611 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07006612 this, effect->desc().name, chain.get());
6613 return BAD_VALUE;
6614 }
6615
6616 status_t status = chain->addEffect_l(effect);
6617 if (status != NO_ERROR) {
6618 if (chainCreated) {
6619 removeEffectChain_l(chain);
6620 }
6621 return status;
6622 }
6623
6624 effect->setDevice(mDevice);
6625 effect->setMode(mAudioFlinger->getMode());
6626 return NO_ERROR;
6627}
6628
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006629void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07006630
Steve Block3856b092011-10-20 11:56:00 +01006631 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006632 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07006633 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6634 detachAuxEffect_l(effect->id());
6635 }
6636
6637 sp<EffectChain> chain = effect->chain().promote();
6638 if (chain != 0) {
6639 // remove effect chain if removing last effect
6640 if (chain->removeEffect_l(effect) == 0) {
6641 removeEffectChain_l(chain);
6642 }
6643 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00006644 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006645 }
6646}
6647
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006648void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006649 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006650{
6651 effectChains = mEffectChains;
6652 for (size_t i = 0; i < mEffectChains.size(); i++) {
6653 mEffectChains[i]->lock();
6654 }
6655}
6656
6657void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006658 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006659{
6660 for (size_t i = 0; i < effectChains.size(); i++) {
6661 effectChains[i]->unlock();
6662 }
6663}
6664
6665sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6666{
6667 Mutex::Autolock _l(mLock);
6668 return getEffectChain_l(sessionId);
6669}
6670
6671sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6672{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006673 size_t size = mEffectChains.size();
6674 for (size_t i = 0; i < size; i++) {
6675 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08006676 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006677 }
6678 }
Glenn Kasten090f0192012-01-30 13:00:02 -08006679 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006680}
6681
Glenn Kastenf78aee72012-01-04 11:00:47 -08006682void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006683{
6684 Mutex::Autolock _l(mLock);
6685 size_t size = mEffectChains.size();
6686 for (size_t i = 0; i < size; i++) {
6687 mEffectChains[i]->setMode_l(mode);
6688 }
6689}
6690
6691void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006692 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08006693 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07006694
Mathias Agopian65ab4712010-07-14 17:59:35 -07006695 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006696 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006697 // delete the effect module if removing last handle on it
6698 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006699 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006700 removeEffect_l(effect);
6701 AudioSystem::unregisterEffect(effect->id());
6702 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006703 }
6704}
6705
6706status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6707{
6708 int session = chain->sessionId();
6709 int16_t *buffer = mMixBuffer;
6710 bool ownsBuffer = false;
6711
Steve Block3856b092011-10-20 11:56:00 +01006712 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006713 if (session > 0) {
6714 // Only one effect chain can be present in direct output thread and it uses
6715 // the mix buffer as input
6716 if (mType != DIRECT) {
6717 size_t numSamples = mFrameCount * mChannelCount;
6718 buffer = new int16_t[numSamples];
6719 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01006720 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006721 ownsBuffer = true;
6722 }
6723
6724 // Attach all tracks with same session ID to this chain.
6725 for (size_t i = 0; i < mTracks.size(); ++i) {
6726 sp<Track> track = mTracks[i];
6727 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006728 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006729 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006730 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006731 }
6732 }
6733
6734 // indicate all active tracks in the chain
6735 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6736 sp<Track> track = mActiveTracks[i].promote();
6737 if (track == 0) continue;
6738 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006739 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07006740 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006741 }
6742 }
6743 }
6744
6745 chain->setInBuffer(buffer, ownsBuffer);
6746 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006747 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006748 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006749 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6750 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006751 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006752 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6753 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006754 // Effect chain for other sessions are inserted at beginning of effect
6755 // chains list to be processed before output mix effects. Relative order between other
6756 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006757 size_t size = mEffectChains.size();
6758 size_t i = 0;
6759 for (i = 0; i < size; i++) {
6760 if (mEffectChains[i]->sessionId() < session) break;
6761 }
6762 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006763 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006764
6765 return NO_ERROR;
6766}
6767
6768size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6769{
6770 int session = chain->sessionId();
6771
Steve Block3856b092011-10-20 11:56:00 +01006772 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006773
6774 for (size_t i = 0; i < mEffectChains.size(); i++) {
6775 if (chain == mEffectChains[i]) {
6776 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006777 // detach all active tracks from the chain
6778 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6779 sp<Track> track = mActiveTracks[i].promote();
6780 if (track == 0) continue;
6781 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006782 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006783 chain.get(), session);
6784 chain->decActiveTrackCnt();
6785 }
6786 }
6787
Mathias Agopian65ab4712010-07-14 17:59:35 -07006788 // detach all tracks with same session ID from this chain
6789 for (size_t i = 0; i < mTracks.size(); ++i) {
6790 sp<Track> track = mTracks[i];
6791 if (session == track->sessionId()) {
6792 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006793 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006794 }
6795 }
Eric Laurentde070132010-07-13 04:45:46 -07006796 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006797 }
6798 }
6799 return mEffectChains.size();
6800}
6801
Eric Laurentde070132010-07-13 04:45:46 -07006802status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6803 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006804{
6805 Mutex::Autolock _l(mLock);
6806 return attachAuxEffect_l(track, EffectId);
6807}
6808
Eric Laurentde070132010-07-13 04:45:46 -07006809status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6810 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006811{
6812 status_t status = NO_ERROR;
6813
6814 if (EffectId == 0) {
6815 track->setAuxBuffer(0, NULL);
6816 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006817 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6818 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006819 if (effect != 0) {
6820 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6821 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6822 } else {
6823 status = INVALID_OPERATION;
6824 }
6825 } else {
6826 status = BAD_VALUE;
6827 }
6828 }
6829 return status;
6830}
6831
6832void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6833{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006834 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006835 sp<Track> track = mTracks[i];
6836 if (track->auxEffectId() == effectId) {
6837 attachAuxEffect_l(track, 0);
6838 }
6839 }
6840}
6841
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006842status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6843{
6844 // only one chain per input thread
6845 if (mEffectChains.size() != 0) {
6846 return INVALID_OPERATION;
6847 }
Steve Block3856b092011-10-20 11:56:00 +01006848 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006849
6850 chain->setInBuffer(NULL);
6851 chain->setOutBuffer(NULL);
6852
Eric Laurent59255e42011-07-27 19:49:51 -07006853 checkSuspendOnAddEffectChain_l(chain);
6854
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006855 mEffectChains.add(chain);
6856
6857 return NO_ERROR;
6858}
6859
6860size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6861{
Steve Block3856b092011-10-20 11:56:00 +01006862 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006863 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006864 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6865 chain.get(), mEffectChains.size(), this);
6866 if (mEffectChains.size() == 1) {
6867 mEffectChains.removeAt(0);
6868 }
6869 return 0;
6870}
6871
Mathias Agopian65ab4712010-07-14 17:59:35 -07006872// ----------------------------------------------------------------------------
6873// EffectModule implementation
6874// ----------------------------------------------------------------------------
6875
6876#undef LOG_TAG
6877#define LOG_TAG "AudioFlinger::EffectModule"
6878
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006879AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006880 const wp<AudioFlinger::EffectChain>& chain,
6881 effect_descriptor_t *desc,
6882 int id,
6883 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006884 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006885 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006886{
Steve Block3856b092011-10-20 11:56:00 +01006887 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006888 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006889 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006890 return;
6891 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006892
6893 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6894
6895 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006896 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006897
6898 if (mStatus != NO_ERROR) {
6899 return;
6900 }
6901 lStatus = init();
6902 if (lStatus < 0) {
6903 mStatus = lStatus;
6904 goto Error;
6905 }
6906
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006907 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6908 mPinned = true;
6909 }
Steve Block3856b092011-10-20 11:56:00 +01006910 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006911 return;
6912Error:
6913 EffectRelease(mEffectInterface);
6914 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006915 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006916}
6917
6918AudioFlinger::EffectModule::~EffectModule()
6919{
Steve Block3856b092011-10-20 11:56:00 +01006920 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006921 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006922 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6923 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6924 sp<ThreadBase> thread = mThread.promote();
6925 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006926 audio_stream_t *stream = thread->stream();
6927 if (stream != NULL) {
6928 stream->remove_audio_effect(stream, mEffectInterface);
6929 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006930 }
6931 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006932 // release effect engine
6933 EffectRelease(mEffectInterface);
6934 }
6935}
6936
Glenn Kasten435dbe62012-01-30 10:15:48 -08006937status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006938{
6939 status_t status;
6940
6941 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006942 int priority = handle->priority();
6943 size_t size = mHandles.size();
6944 sp<EffectHandle> h;
6945 size_t i;
6946 for (i = 0; i < size; i++) {
6947 h = mHandles[i].promote();
6948 if (h == 0) continue;
6949 if (h->priority() <= priority) break;
6950 }
6951 // if inserted in first place, move effect control from previous owner to this handle
6952 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006953 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006954 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006955 enabled = h->enabled();
6956 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006957 }
Eric Laurent59255e42011-07-27 19:49:51 -07006958 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006959 status = NO_ERROR;
6960 } else {
6961 status = ALREADY_EXISTS;
6962 }
Steve Block3856b092011-10-20 11:56:00 +01006963 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006964 mHandles.insertAt(handle, i);
6965 return status;
6966}
6967
6968size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6969{
6970 Mutex::Autolock _l(mLock);
6971 size_t size = mHandles.size();
6972 size_t i;
6973 for (i = 0; i < size; i++) {
6974 if (mHandles[i] == handle) break;
6975 }
6976 if (i == size) {
6977 return size;
6978 }
Steve Block3856b092011-10-20 11:56:00 +01006979 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006980
6981 bool enabled = false;
6982 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006983 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006984 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006985 enabled = hdl->enabled();
6986 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006987 mHandles.removeAt(i);
6988 size = mHandles.size();
6989 // if removed from first place, move effect control from this handle to next in line
6990 if (i == 0 && size != 0) {
6991 sp<EffectHandle> h = mHandles[0].promote();
6992 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006993 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006994 }
6995 }
6996
Eric Laurentec437d82011-07-26 20:54:46 -07006997 // Prevent calls to process() and other functions on effect interface from now on.
6998 // The effect engine will be released by the destructor when the last strong reference on
6999 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007000 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07007001 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07007002 }
7003
Mathias Agopian65ab4712010-07-14 17:59:35 -07007004 return size;
7005}
7006
Eric Laurent59255e42011-07-27 19:49:51 -07007007sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
7008{
7009 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08007010 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007011}
7012
Glenn Kasten58123c32012-02-03 10:32:24 -08007013void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007014{
Glenn Kasten90bebef2012-01-27 15:24:38 -08007015 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007016 // keep a strong reference on this EffectModule to avoid calling the
7017 // destructor before we exit
7018 sp<EffectModule> keep(this);
7019 {
7020 sp<ThreadBase> thread = mThread.promote();
7021 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007022 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007023 }
7024 }
7025}
7026
7027void AudioFlinger::EffectModule::updateState() {
7028 Mutex::Autolock _l(mLock);
7029
7030 switch (mState) {
7031 case RESTART:
7032 reset_l();
7033 // FALL THROUGH
7034
7035 case STARTING:
7036 // clear auxiliary effect input buffer for next accumulation
7037 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7038 memset(mConfig.inputCfg.buffer.raw,
7039 0,
7040 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
7041 }
7042 start_l();
7043 mState = ACTIVE;
7044 break;
7045 case STOPPING:
7046 stop_l();
7047 mDisableWaitCnt = mMaxDisableWaitCnt;
7048 mState = STOPPED;
7049 break;
7050 case STOPPED:
7051 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
7052 // turn off sequence.
7053 if (--mDisableWaitCnt == 0) {
7054 reset_l();
7055 mState = IDLE;
7056 }
7057 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007058 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07007059 break;
7060 }
7061}
7062
7063void AudioFlinger::EffectModule::process()
7064{
7065 Mutex::Autolock _l(mLock);
7066
Eric Laurentec437d82011-07-26 20:54:46 -07007067 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007068 mConfig.inputCfg.buffer.raw == NULL ||
7069 mConfig.outputCfg.buffer.raw == NULL) {
7070 return;
7071 }
7072
Eric Laurent8f45bd72010-08-31 13:50:07 -07007073 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007074 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
7075 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08007076 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007077 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07007078 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007079 }
7080
7081 // do the actual processing in the effect engine
7082 int ret = (*mEffectInterface)->process(mEffectInterface,
7083 &mConfig.inputCfg.buffer,
7084 &mConfig.outputCfg.buffer);
7085
7086 // force transition to IDLE state when engine is ready
7087 if (mState == STOPPED && ret == -ENODATA) {
7088 mDisableWaitCnt = 1;
7089 }
7090
7091 // clear auxiliary effect input buffer for next accumulation
7092 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08007093 memset(mConfig.inputCfg.buffer.raw, 0,
7094 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007095 }
7096 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08007097 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7098 // If an insert effect is idle and input buffer is different from output buffer,
7099 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07007100 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07007101 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08007102 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
7103 int16_t *in = mConfig.inputCfg.buffer.s16;
7104 int16_t *out = mConfig.outputCfg.buffer.s16;
7105 for (size_t i = 0; i < frameCnt; i++) {
7106 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007107 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007108 }
7109 }
7110}
7111
7112void AudioFlinger::EffectModule::reset_l()
7113{
7114 if (mEffectInterface == NULL) {
7115 return;
7116 }
7117 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
7118}
7119
7120status_t AudioFlinger::EffectModule::configure()
7121{
7122 uint32_t channels;
7123 if (mEffectInterface == NULL) {
7124 return NO_INIT;
7125 }
7126
7127 sp<ThreadBase> thread = mThread.promote();
7128 if (thread == 0) {
7129 return DEAD_OBJECT;
7130 }
7131
7132 // TODO: handle configuration of effects replacing track process
7133 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007134 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007135 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07007136 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007137 }
7138
7139 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007140 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007141 } else {
7142 mConfig.inputCfg.channels = channels;
7143 }
7144 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07007145 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
7146 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007147 mConfig.inputCfg.samplingRate = thread->sampleRate();
7148 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
7149 mConfig.inputCfg.bufferProvider.cookie = NULL;
7150 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
7151 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
7152 mConfig.outputCfg.bufferProvider.cookie = NULL;
7153 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
7154 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
7155 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
7156 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07007157 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07007158 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07007159 // - in other sessions:
7160 // last effect in the chain accumulates in output buffer: input buffer != output buffer
7161 // other effect: overwrites output buffer: input buffer == output buffer
7162 // Auxiliary effect:
7163 // accumulates in output buffer: input buffer != output buffer
7164 // Therefore: accumulate <=> input buffer != output buffer
7165 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7166 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
7167 } else {
7168 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
7169 }
7170 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
7171 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
7172 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
7173 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
7174
Steve Block3856b092011-10-20 11:56:00 +01007175 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07007176 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
7177
Mathias Agopian65ab4712010-07-14 17:59:35 -07007178 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007179 uint32_t size = sizeof(int);
7180 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08007181 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07007182 sizeof(effect_config_t),
7183 &mConfig,
7184 &size,
7185 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007186 if (status == 0) {
7187 status = cmdStatus;
7188 }
7189
7190 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
7191 (1000 * mConfig.outputCfg.buffer.frameCount);
7192
7193 return status;
7194}
7195
7196status_t AudioFlinger::EffectModule::init()
7197{
7198 Mutex::Autolock _l(mLock);
7199 if (mEffectInterface == NULL) {
7200 return NO_INIT;
7201 }
7202 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007203 uint32_t size = sizeof(status_t);
7204 status_t status = (*mEffectInterface)->command(mEffectInterface,
7205 EFFECT_CMD_INIT,
7206 0,
7207 NULL,
7208 &size,
7209 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007210 if (status == 0) {
7211 status = cmdStatus;
7212 }
7213 return status;
7214}
7215
Eric Laurentec35a142011-10-05 17:42:25 -07007216status_t AudioFlinger::EffectModule::start()
7217{
7218 Mutex::Autolock _l(mLock);
7219 return start_l();
7220}
7221
Mathias Agopian65ab4712010-07-14 17:59:35 -07007222status_t AudioFlinger::EffectModule::start_l()
7223{
7224 if (mEffectInterface == NULL) {
7225 return NO_INIT;
7226 }
7227 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007228 uint32_t size = sizeof(status_t);
7229 status_t status = (*mEffectInterface)->command(mEffectInterface,
7230 EFFECT_CMD_ENABLE,
7231 0,
7232 NULL,
7233 &size,
7234 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007235 if (status == 0) {
7236 status = cmdStatus;
7237 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007238 if (status == 0 &&
7239 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7240 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7241 sp<ThreadBase> thread = mThread.promote();
7242 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007243 audio_stream_t *stream = thread->stream();
7244 if (stream != NULL) {
7245 stream->add_audio_effect(stream, mEffectInterface);
7246 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007247 }
7248 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007249 return status;
7250}
7251
Eric Laurentec437d82011-07-26 20:54:46 -07007252status_t AudioFlinger::EffectModule::stop()
7253{
7254 Mutex::Autolock _l(mLock);
7255 return stop_l();
7256}
7257
Mathias Agopian65ab4712010-07-14 17:59:35 -07007258status_t AudioFlinger::EffectModule::stop_l()
7259{
7260 if (mEffectInterface == NULL) {
7261 return NO_INIT;
7262 }
7263 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007264 uint32_t size = sizeof(status_t);
7265 status_t status = (*mEffectInterface)->command(mEffectInterface,
7266 EFFECT_CMD_DISABLE,
7267 0,
7268 NULL,
7269 &size,
7270 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007271 if (status == 0) {
7272 status = cmdStatus;
7273 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007274 if (status == 0 &&
7275 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7276 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7277 sp<ThreadBase> thread = mThread.promote();
7278 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007279 audio_stream_t *stream = thread->stream();
7280 if (stream != NULL) {
7281 stream->remove_audio_effect(stream, mEffectInterface);
7282 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007283 }
7284 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007285 return status;
7286}
7287
Eric Laurent25f43952010-07-28 05:40:18 -07007288status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
7289 uint32_t cmdSize,
7290 void *pCmdData,
7291 uint32_t *replySize,
7292 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007293{
7294 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007295// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007296
Eric Laurentec437d82011-07-26 20:54:46 -07007297 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007298 return NO_INIT;
7299 }
Eric Laurent25f43952010-07-28 05:40:18 -07007300 status_t status = (*mEffectInterface)->command(mEffectInterface,
7301 cmdCode,
7302 cmdSize,
7303 pCmdData,
7304 replySize,
7305 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007306 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07007307 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007308 for (size_t i = 1; i < mHandles.size(); i++) {
7309 sp<EffectHandle> h = mHandles[i].promote();
7310 if (h != 0) {
7311 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
7312 }
7313 }
7314 }
7315 return status;
7316}
7317
7318status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
7319{
Eric Laurentdb7c0792011-08-10 10:37:50 -07007320
Mathias Agopian65ab4712010-07-14 17:59:35 -07007321 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007322 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007323
7324 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007325 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
7326 if (enabled && status != NO_ERROR) {
7327 return status;
7328 }
7329
Mathias Agopian65ab4712010-07-14 17:59:35 -07007330 switch (mState) {
7331 // going from disabled to enabled
7332 case IDLE:
7333 mState = STARTING;
7334 break;
7335 case STOPPED:
7336 mState = RESTART;
7337 break;
7338 case STOPPING:
7339 mState = ACTIVE;
7340 break;
7341
7342 // going from enabled to disabled
7343 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007344 mState = STOPPED;
7345 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007346 case STARTING:
7347 mState = IDLE;
7348 break;
7349 case ACTIVE:
7350 mState = STOPPING;
7351 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007352 case DESTROYED:
7353 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007354 }
7355 for (size_t i = 1; i < mHandles.size(); i++) {
7356 sp<EffectHandle> h = mHandles[i].promote();
7357 if (h != 0) {
7358 h->setEnabled(enabled);
7359 }
7360 }
7361 }
7362 return NO_ERROR;
7363}
7364
Glenn Kastenc59c0042012-02-02 14:06:11 -08007365bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007366{
7367 switch (mState) {
7368 case RESTART:
7369 case STARTING:
7370 case ACTIVE:
7371 return true;
7372 case IDLE:
7373 case STOPPING:
7374 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07007375 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07007376 default:
7377 return false;
7378 }
7379}
7380
Glenn Kastenc59c0042012-02-02 14:06:11 -08007381bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07007382{
7383 switch (mState) {
7384 case RESTART:
7385 case ACTIVE:
7386 case STOPPING:
7387 case STOPPED:
7388 return true;
7389 case IDLE:
7390 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07007391 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007392 default:
7393 return false;
7394 }
7395}
7396
Mathias Agopian65ab4712010-07-14 17:59:35 -07007397status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7398{
7399 Mutex::Autolock _l(mLock);
7400 status_t status = NO_ERROR;
7401
7402 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7403 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07007404 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07007405 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7406 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007407 status_t cmdStatus;
7408 uint32_t volume[2];
7409 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07007410 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007411 volume[0] = *left;
7412 volume[1] = *right;
7413 if (controller) {
7414 pVolume = volume;
7415 }
Eric Laurent25f43952010-07-28 05:40:18 -07007416 status = (*mEffectInterface)->command(mEffectInterface,
7417 EFFECT_CMD_SET_VOLUME,
7418 size,
7419 volume,
7420 &size,
7421 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007422 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7423 *left = volume[0];
7424 *right = volume[1];
7425 }
7426 }
7427 return status;
7428}
7429
7430status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7431{
7432 Mutex::Autolock _l(mLock);
7433 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007434 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7435 // audio pre processing modules on RecordThread can receive both output and
7436 // input device indication in the same call
7437 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7438 if (dev) {
7439 status_t cmdStatus;
7440 uint32_t size = sizeof(status_t);
7441
7442 status = (*mEffectInterface)->command(mEffectInterface,
7443 EFFECT_CMD_SET_DEVICE,
7444 sizeof(uint32_t),
7445 &dev,
7446 &size,
7447 &cmdStatus);
7448 if (status == NO_ERROR) {
7449 status = cmdStatus;
7450 }
7451 }
7452 dev = device & AUDIO_DEVICE_IN_ALL;
7453 if (dev) {
7454 status_t cmdStatus;
7455 uint32_t size = sizeof(status_t);
7456
7457 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7458 EFFECT_CMD_SET_INPUT_DEVICE,
7459 sizeof(uint32_t),
7460 &dev,
7461 &size,
7462 &cmdStatus);
7463 if (status2 == NO_ERROR) {
7464 status2 = cmdStatus;
7465 }
7466 if (status == NO_ERROR) {
7467 status = status2;
7468 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007469 }
7470 }
7471 return status;
7472}
7473
Glenn Kastenf78aee72012-01-04 11:00:47 -08007474status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007475{
7476 Mutex::Autolock _l(mLock);
7477 status_t status = NO_ERROR;
7478 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007479 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007480 uint32_t size = sizeof(status_t);
7481 status = (*mEffectInterface)->command(mEffectInterface,
7482 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08007483 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07007484 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07007485 &size,
7486 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007487 if (status == NO_ERROR) {
7488 status = cmdStatus;
7489 }
7490 }
7491 return status;
7492}
7493
Eric Laurent59255e42011-07-27 19:49:51 -07007494void AudioFlinger::EffectModule::setSuspended(bool suspended)
7495{
7496 Mutex::Autolock _l(mLock);
7497 mSuspended = suspended;
7498}
Glenn Kastena3a85482012-01-04 11:01:11 -08007499
7500bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07007501{
7502 Mutex::Autolock _l(mLock);
7503 return mSuspended;
7504}
7505
Mathias Agopian65ab4712010-07-14 17:59:35 -07007506status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7507{
7508 const size_t SIZE = 256;
7509 char buffer[SIZE];
7510 String8 result;
7511
7512 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7513 result.append(buffer);
7514
7515 bool locked = tryLock(mLock);
7516 // failed to lock - AudioFlinger is probably deadlocked
7517 if (!locked) {
7518 result.append("\t\tCould not lock Fx mutex:\n");
7519 }
7520
7521 result.append("\t\tSession Status State Engine:\n");
7522 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7523 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7524 result.append(buffer);
7525
7526 result.append("\t\tDescriptor:\n");
7527 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7528 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7529 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7530 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7531 result.append(buffer);
7532 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7533 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7534 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7535 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7536 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07007537 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007538 mDescriptor.apiVersion,
7539 mDescriptor.flags);
7540 result.append(buffer);
7541 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7542 mDescriptor.name);
7543 result.append(buffer);
7544 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7545 mDescriptor.implementor);
7546 result.append(buffer);
7547
7548 result.append("\t\t- Input configuration:\n");
7549 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7550 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7551 (uint32_t)mConfig.inputCfg.buffer.raw,
7552 mConfig.inputCfg.buffer.frameCount,
7553 mConfig.inputCfg.samplingRate,
7554 mConfig.inputCfg.channels,
7555 mConfig.inputCfg.format);
7556 result.append(buffer);
7557
7558 result.append("\t\t- Output configuration:\n");
7559 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7560 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7561 (uint32_t)mConfig.outputCfg.buffer.raw,
7562 mConfig.outputCfg.buffer.frameCount,
7563 mConfig.outputCfg.samplingRate,
7564 mConfig.outputCfg.channels,
7565 mConfig.outputCfg.format);
7566 result.append(buffer);
7567
7568 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7569 result.append(buffer);
7570 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7571 for (size_t i = 0; i < mHandles.size(); ++i) {
7572 sp<EffectHandle> handle = mHandles[i].promote();
7573 if (handle != 0) {
7574 handle->dump(buffer, SIZE);
7575 result.append(buffer);
7576 }
7577 }
7578
7579 result.append("\n");
7580
7581 write(fd, result.string(), result.length());
7582
7583 if (locked) {
7584 mLock.unlock();
7585 }
7586
7587 return NO_ERROR;
7588}
7589
7590// ----------------------------------------------------------------------------
7591// EffectHandle implementation
7592// ----------------------------------------------------------------------------
7593
7594#undef LOG_TAG
7595#define LOG_TAG "AudioFlinger::EffectHandle"
7596
7597AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7598 const sp<AudioFlinger::Client>& client,
7599 const sp<IEffectClient>& effectClient,
7600 int32_t priority)
7601 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007602 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007603 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007604{
Steve Block3856b092011-10-20 11:56:00 +01007605 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007606
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007607 if (client == 0) {
7608 return;
7609 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007610 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7611 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7612 if (mCblkMemory != 0) {
7613 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7614
Glenn Kastena0d68332012-01-27 16:47:15 -08007615 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007616 new(mCblk) effect_param_cblk_t();
7617 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007618 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007619 } else {
Steve Block29357bc2012-01-06 19:20:56 +00007620 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007621 return;
7622 }
7623}
7624
7625AudioFlinger::EffectHandle::~EffectHandle()
7626{
Steve Block3856b092011-10-20 11:56:00 +01007627 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007628 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01007629 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007630}
7631
7632status_t AudioFlinger::EffectHandle::enable()
7633{
Steve Block3856b092011-10-20 11:56:00 +01007634 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007635 if (!mHasControl) return INVALID_OPERATION;
7636 if (mEffect == 0) return DEAD_OBJECT;
7637
Eric Laurentdb7c0792011-08-10 10:37:50 -07007638 if (mEnabled) {
7639 return NO_ERROR;
7640 }
7641
Eric Laurent59255e42011-07-27 19:49:51 -07007642 mEnabled = true;
7643
7644 sp<ThreadBase> thread = mEffect->thread().promote();
7645 if (thread != 0) {
7646 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7647 }
7648
7649 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7650 if (mEffect->suspended()) {
7651 return NO_ERROR;
7652 }
7653
Eric Laurentdb7c0792011-08-10 10:37:50 -07007654 status_t status = mEffect->setEnabled(true);
7655 if (status != NO_ERROR) {
7656 if (thread != 0) {
7657 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7658 }
7659 mEnabled = false;
7660 }
7661 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007662}
7663
7664status_t AudioFlinger::EffectHandle::disable()
7665{
Steve Block3856b092011-10-20 11:56:00 +01007666 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007667 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07007668 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007669
Eric Laurentdb7c0792011-08-10 10:37:50 -07007670 if (!mEnabled) {
7671 return NO_ERROR;
7672 }
Eric Laurent59255e42011-07-27 19:49:51 -07007673 mEnabled = false;
7674
7675 if (mEffect->suspended()) {
7676 return NO_ERROR;
7677 }
7678
7679 status_t status = mEffect->setEnabled(false);
7680
7681 sp<ThreadBase> thread = mEffect->thread().promote();
7682 if (thread != 0) {
7683 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7684 }
7685
7686 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007687}
7688
7689void AudioFlinger::EffectHandle::disconnect()
7690{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007691 disconnect(true);
7692}
7693
Glenn Kasten58123c32012-02-03 10:32:24 -08007694void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007695{
Glenn Kasten58123c32012-02-03 10:32:24 -08007696 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007697 if (mEffect == 0) {
7698 return;
7699 }
Glenn Kasten58123c32012-02-03 10:32:24 -08007700 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07007701
Eric Laurenta85a74a2011-10-19 11:44:54 -07007702 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007703 sp<ThreadBase> thread = mEffect->thread().promote();
7704 if (thread != 0) {
7705 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7706 }
Eric Laurent59255e42011-07-27 19:49:51 -07007707 }
7708
Mathias Agopian65ab4712010-07-14 17:59:35 -07007709 // release sp on module => module destructor can be called now
7710 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007711 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08007712 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08007713 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007714 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7715 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08007716 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007717 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07007718 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7719 mClient.clear();
7720 }
7721}
7722
Eric Laurent25f43952010-07-28 05:40:18 -07007723status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7724 uint32_t cmdSize,
7725 void *pCmdData,
7726 uint32_t *replySize,
7727 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007728{
Steve Block3856b092011-10-20 11:56:00 +01007729// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07007730// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007731
7732 // only get parameter command is permitted for applications not controlling the effect
7733 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7734 return INVALID_OPERATION;
7735 }
7736 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007737 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007738
7739 // handle commands that are not forwarded transparently to effect engine
7740 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7741 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7742 // no risk to block the whole media server process or mixer threads is we are stuck here
7743 Mutex::Autolock _l(mCblk->lock);
7744 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7745 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7746 mCblk->serverIndex = 0;
7747 mCblk->clientIndex = 0;
7748 return BAD_VALUE;
7749 }
7750 status_t status = NO_ERROR;
7751 while (mCblk->serverIndex < mCblk->clientIndex) {
7752 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007753 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007754 int *p = (int *)(mBuffer + mCblk->serverIndex);
7755 int size = *p++;
7756 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007757 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007758 break;
7759 }
7760 effect_param_t *param = (effect_param_t *)p;
7761 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007762 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007763 mCblk->serverIndex += size;
7764 continue;
7765 }
Eric Laurent25f43952010-07-28 05:40:18 -07007766 uint32_t psize = sizeof(effect_param_t) +
7767 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7768 param->vsize;
7769 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7770 psize,
7771 p,
7772 &rsize,
7773 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007774 // stop at first error encountered
7775 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007776 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007777 *(int *)pReplyData = reply;
7778 break;
7779 } else if (reply != NO_ERROR) {
7780 *(int *)pReplyData = reply;
7781 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007782 }
7783 mCblk->serverIndex += size;
7784 }
7785 mCblk->serverIndex = 0;
7786 mCblk->clientIndex = 0;
7787 return status;
7788 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007789 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007790 return enable();
7791 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007792 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007793 return disable();
7794 }
7795
7796 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7797}
7798
Eric Laurent59255e42011-07-27 19:49:51 -07007799void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007800{
Steve Block3856b092011-10-20 11:56:00 +01007801 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007802
7803 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007804 mEnabled = enabled;
7805
Mathias Agopian65ab4712010-07-14 17:59:35 -07007806 if (signal && mEffectClient != 0) {
7807 mEffectClient->controlStatusChanged(hasControl);
7808 }
7809}
7810
Eric Laurent25f43952010-07-28 05:40:18 -07007811void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7812 uint32_t cmdSize,
7813 void *pCmdData,
7814 uint32_t replySize,
7815 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007816{
7817 if (mEffectClient != 0) {
7818 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7819 }
7820}
7821
7822
7823
7824void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7825{
7826 if (mEffectClient != 0) {
7827 mEffectClient->enableStatusChanged(enabled);
7828 }
7829}
7830
7831status_t AudioFlinger::EffectHandle::onTransact(
7832 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7833{
7834 return BnEffect::onTransact(code, data, reply, flags);
7835}
7836
7837
7838void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7839{
Glenn Kastena0d68332012-01-27 16:47:15 -08007840 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007841
7842 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08007843 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007844 mPriority,
7845 mHasControl,
7846 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007847 mCblk ? mCblk->clientIndex : 0,
7848 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007849 );
7850
7851 if (locked) {
7852 mCblk->lock.unlock();
7853 }
7854}
7855
7856#undef LOG_TAG
7857#define LOG_TAG "AudioFlinger::EffectChain"
7858
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007859AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007860 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007861 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007862 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7863 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007864{
Dima Zavinfce7a472011-04-19 22:30:36 -07007865 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007866 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007867 return;
7868 }
7869 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7870 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007871}
7872
7873AudioFlinger::EffectChain::~EffectChain()
7874{
7875 if (mOwnInBuffer) {
7876 delete mInBuffer;
7877 }
7878
7879}
7880
Eric Laurent59255e42011-07-27 19:49:51 -07007881// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007882sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007883{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007884 size_t size = mEffects.size();
7885
7886 for (size_t i = 0; i < size; i++) {
7887 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007888 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007889 }
7890 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007891 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007892}
7893
Eric Laurent59255e42011-07-27 19:49:51 -07007894// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007895sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007896{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007897 size_t size = mEffects.size();
7898
7899 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007900 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7901 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007902 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007903 }
7904 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007905 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007906}
7907
Eric Laurent59255e42011-07-27 19:49:51 -07007908// getEffectFromType_l() must be called with ThreadBase::mLock held
7909sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7910 const effect_uuid_t *type)
7911{
Eric Laurent59255e42011-07-27 19:49:51 -07007912 size_t size = mEffects.size();
7913
7914 for (size_t i = 0; i < size; i++) {
7915 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007916 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007917 }
7918 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007919 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007920}
7921
Mathias Agopian65ab4712010-07-14 17:59:35 -07007922// Must be called with EffectChain::mLock locked
7923void AudioFlinger::EffectChain::process_l()
7924{
Eric Laurentdac69112010-09-28 14:09:57 -07007925 sp<ThreadBase> thread = mThread.promote();
7926 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007927 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007928 return;
7929 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007930 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7931 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007932 // always process effects unless no more tracks are on the session and the effect tail
7933 // has been rendered
7934 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007935 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007936 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007937
Eric Laurent544fe9b2011-11-11 15:42:52 -08007938 if (!tracksOnSession && mTailBufferCount == 0) {
7939 doProcess = false;
7940 }
7941
7942 if (activeTrackCnt() == 0) {
7943 // if no track is active and the effect tail has not been rendered,
7944 // the input buffer must be cleared here as the mixer process will not do it
7945 if (tracksOnSession || mTailBufferCount > 0) {
7946 size_t numSamples = thread->frameCount() * thread->channelCount();
7947 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7948 if (mTailBufferCount > 0) {
7949 mTailBufferCount--;
7950 }
7951 }
7952 }
Eric Laurentdac69112010-09-28 14:09:57 -07007953 }
7954
Mathias Agopian65ab4712010-07-14 17:59:35 -07007955 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007956 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007957 for (size_t i = 0; i < size; i++) {
7958 mEffects[i]->process();
7959 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007960 }
7961 for (size_t i = 0; i < size; i++) {
7962 mEffects[i]->updateState();
7963 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007964}
7965
Eric Laurentcab11242010-07-15 12:50:15 -07007966// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007967status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007968{
7969 effect_descriptor_t desc = effect->desc();
7970 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7971
7972 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007973 effect->setChain(this);
7974 sp<ThreadBase> thread = mThread.promote();
7975 if (thread == 0) {
7976 return NO_INIT;
7977 }
7978 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007979
7980 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7981 // Auxiliary effects are inserted at the beginning of mEffects vector as
7982 // they are processed first and accumulated in chain input buffer
7983 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007984
Mathias Agopian65ab4712010-07-14 17:59:35 -07007985 // the input buffer for auxiliary effect contains mono samples in
7986 // 32 bit format. This is to avoid saturation in AudoMixer
7987 // accumulation stage. Saturation is done in EffectModule::process() before
7988 // calling the process in effect engine
7989 size_t numSamples = thread->frameCount();
7990 int32_t *buffer = new int32_t[numSamples];
7991 memset(buffer, 0, numSamples * sizeof(int32_t));
7992 effect->setInBuffer((int16_t *)buffer);
7993 // auxiliary effects output samples to chain input buffer for further processing
7994 // by insert effects
7995 effect->setOutBuffer(mInBuffer);
7996 } else {
7997 // Insert effects are inserted at the end of mEffects vector as they are processed
7998 // after track and auxiliary effects.
7999 // Insert effect order as a function of indicated preference:
8000 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
8001 // another effect is present
8002 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
8003 // last effect claiming first position
8004 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
8005 // first effect claiming last position
8006 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
8007 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
8008 // already present
8009
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008010 size_t size = mEffects.size();
8011 size_t idx_insert = size;
8012 ssize_t idx_insert_first = -1;
8013 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008014
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008015 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008016 effect_descriptor_t d = mEffects[i]->desc();
8017 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
8018 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
8019 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
8020 // check invalid effect chaining combinations
8021 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
8022 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008023 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008024 return INVALID_OPERATION;
8025 }
8026 // remember position of first insert effect and by default
8027 // select this as insert position for new effect
8028 if (idx_insert == size) {
8029 idx_insert = i;
8030 }
8031 // remember position of last insert effect claiming
8032 // first position
8033 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
8034 idx_insert_first = i;
8035 }
8036 // remember position of first insert effect claiming
8037 // last position
8038 if (iPref == EFFECT_FLAG_INSERT_LAST &&
8039 idx_insert_last == -1) {
8040 idx_insert_last = i;
8041 }
8042 }
8043 }
8044
8045 // modify idx_insert from first position if needed
8046 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
8047 if (idx_insert_last != -1) {
8048 idx_insert = idx_insert_last;
8049 } else {
8050 idx_insert = size;
8051 }
8052 } else {
8053 if (idx_insert_first != -1) {
8054 idx_insert = idx_insert_first + 1;
8055 }
8056 }
8057
8058 // always read samples from chain input buffer
8059 effect->setInBuffer(mInBuffer);
8060
8061 // if last effect in the chain, output samples to chain
8062 // output buffer, otherwise to chain input buffer
8063 if (idx_insert == size) {
8064 if (idx_insert != 0) {
8065 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
8066 mEffects[idx_insert-1]->configure();
8067 }
8068 effect->setOutBuffer(mOutBuffer);
8069 } else {
8070 effect->setOutBuffer(mInBuffer);
8071 }
8072 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008073
Steve Block3856b092011-10-20 11:56:00 +01008074 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008075 }
8076 effect->configure();
8077 return NO_ERROR;
8078}
8079
Eric Laurentcab11242010-07-15 12:50:15 -07008080// removeEffect_l() must be called with PlaybackThread::mLock held
8081size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008082{
8083 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008084 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008085 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
8086
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008087 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008088 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07008089 // calling stop here will remove pre-processing effect from the audio HAL.
8090 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
8091 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07008092 if (mEffects[i]->state() == EffectModule::ACTIVE ||
8093 mEffects[i]->state() == EffectModule::STOPPING) {
8094 mEffects[i]->stop();
8095 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008096 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
8097 delete[] effect->inBuffer();
8098 } else {
8099 if (i == size - 1 && i != 0) {
8100 mEffects[i - 1]->setOutBuffer(mOutBuffer);
8101 mEffects[i - 1]->configure();
8102 }
8103 }
8104 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01008105 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008106 break;
8107 }
8108 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008109
8110 return mEffects.size();
8111}
8112
Eric Laurentcab11242010-07-15 12:50:15 -07008113// setDevice_l() must be called with PlaybackThread::mLock held
8114void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008115{
8116 size_t size = mEffects.size();
8117 for (size_t i = 0; i < size; i++) {
8118 mEffects[i]->setDevice(device);
8119 }
8120}
8121
Eric Laurentcab11242010-07-15 12:50:15 -07008122// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08008123void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008124{
8125 size_t size = mEffects.size();
8126 for (size_t i = 0; i < size; i++) {
8127 mEffects[i]->setMode(mode);
8128 }
8129}
8130
Eric Laurentcab11242010-07-15 12:50:15 -07008131// setVolume_l() must be called with PlaybackThread::mLock held
8132bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008133{
8134 uint32_t newLeft = *left;
8135 uint32_t newRight = *right;
8136 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07008137 int ctrlIdx = -1;
8138 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008139
Eric Laurentcab11242010-07-15 12:50:15 -07008140 // first update volume controller
8141 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07008142 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07008143 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
8144 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07008145 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07008146 break;
8147 }
8148 }
8149
8150 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07008151 if (hasControl) {
8152 *left = mNewLeftVolume;
8153 *right = mNewRightVolume;
8154 }
8155 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07008156 }
8157
8158 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07008159 mLeftVolume = newLeft;
8160 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008161
8162 // second get volume update from volume controller
8163 if (ctrlIdx >= 0) {
8164 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07008165 mNewLeftVolume = newLeft;
8166 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008167 }
8168 // then indicate volume to all other effects in chain.
8169 // Pass altered volume to effects before volume controller
8170 // and requested volume to effects after controller
8171 uint32_t lVol = newLeft;
8172 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008173
Mathias Agopian65ab4712010-07-14 17:59:35 -07008174 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07008175 if ((int)i == ctrlIdx) continue;
8176 // this also works for ctrlIdx == -1 when there is no volume controller
8177 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008178 lVol = *left;
8179 rVol = *right;
8180 }
8181 mEffects[i]->setVolume(&lVol, &rVol, false);
8182 }
8183 *left = newLeft;
8184 *right = newRight;
8185
8186 return hasControl;
8187}
8188
Mathias Agopian65ab4712010-07-14 17:59:35 -07008189status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
8190{
8191 const size_t SIZE = 256;
8192 char buffer[SIZE];
8193 String8 result;
8194
8195 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
8196 result.append(buffer);
8197
8198 bool locked = tryLock(mLock);
8199 // failed to lock - AudioFlinger is probably deadlocked
8200 if (!locked) {
8201 result.append("\tCould not lock mutex:\n");
8202 }
8203
Eric Laurentcab11242010-07-15 12:50:15 -07008204 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
8205 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008206 mEffects.size(),
8207 (uint32_t)mInBuffer,
8208 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008209 mActiveTrackCnt);
8210 result.append(buffer);
8211 write(fd, result.string(), result.size());
8212
8213 for (size_t i = 0; i < mEffects.size(); ++i) {
8214 sp<EffectModule> effect = mEffects[i];
8215 if (effect != 0) {
8216 effect->dump(fd, args);
8217 }
8218 }
8219
8220 if (locked) {
8221 mLock.unlock();
8222 }
8223
8224 return NO_ERROR;
8225}
8226
Eric Laurent59255e42011-07-27 19:49:51 -07008227// must be called with ThreadBase::mLock held
8228void AudioFlinger::EffectChain::setEffectSuspended_l(
8229 const effect_uuid_t *type, bool suspend)
8230{
8231 sp<SuspendedEffectDesc> desc;
8232 // use effect type UUID timelow as key as there is no real risk of identical
8233 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008234 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008235 if (suspend) {
8236 if (index >= 0) {
8237 desc = mSuspendedEffects.valueAt(index);
8238 } else {
8239 desc = new SuspendedEffectDesc();
8240 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
8241 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01008242 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008243 }
8244 if (desc->mRefCount++ == 0) {
8245 sp<EffectModule> effect = getEffectIfEnabled(type);
8246 if (effect != 0) {
8247 desc->mEffect = effect;
8248 effect->setSuspended(true);
8249 effect->setEnabled(false);
8250 }
8251 }
8252 } else {
8253 if (index < 0) {
8254 return;
8255 }
8256 desc = mSuspendedEffects.valueAt(index);
8257 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008258 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008259 desc->mRefCount = 1;
8260 }
8261 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01008262 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008263 if (desc->mEffect != 0) {
8264 sp<EffectModule> effect = desc->mEffect.promote();
8265 if (effect != 0) {
8266 effect->setSuspended(false);
8267 sp<EffectHandle> handle = effect->controlHandle();
8268 if (handle != 0) {
8269 effect->setEnabled(handle->enabled());
8270 }
8271 }
8272 desc->mEffect.clear();
8273 }
8274 mSuspendedEffects.removeItemsAt(index);
8275 }
8276 }
8277}
8278
8279// must be called with ThreadBase::mLock held
8280void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
8281{
8282 sp<SuspendedEffectDesc> desc;
8283
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008284 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07008285 if (suspend) {
8286 if (index >= 0) {
8287 desc = mSuspendedEffects.valueAt(index);
8288 } else {
8289 desc = new SuspendedEffectDesc();
8290 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01008291 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07008292 }
8293 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08008294 Vector< sp<EffectModule> > effects;
8295 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07008296 for (size_t i = 0; i < effects.size(); i++) {
8297 setEffectSuspended_l(&effects[i]->desc().type, true);
8298 }
8299 }
8300 } else {
8301 if (index < 0) {
8302 return;
8303 }
8304 desc = mSuspendedEffects.valueAt(index);
8305 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008306 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008307 desc->mRefCount = 1;
8308 }
8309 if (--desc->mRefCount == 0) {
8310 Vector<const effect_uuid_t *> types;
8311 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
8312 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
8313 continue;
8314 }
8315 types.add(&mSuspendedEffects.valueAt(i)->mType);
8316 }
8317 for (size_t i = 0; i < types.size(); i++) {
8318 setEffectSuspended_l(types[i], false);
8319 }
Steve Block3856b092011-10-20 11:56:00 +01008320 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008321 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
8322 }
8323 }
8324}
8325
Eric Laurent6bffdb82011-09-23 08:40:41 -07008326
8327// The volume effect is used for automated tests only
8328#ifndef OPENSL_ES_H_
8329static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
8330 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
8331const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
8332#endif //OPENSL_ES_H_
8333
Eric Laurentdb7c0792011-08-10 10:37:50 -07008334bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
8335{
8336 // auxiliary effects and visualizer are never suspended on output mix
8337 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8338 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07008339 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8340 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008341 return false;
8342 }
8343 return true;
8344}
8345
Glenn Kastend0539712012-01-30 12:56:03 -08008346void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07008347{
Glenn Kastend0539712012-01-30 12:56:03 -08008348 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07008349 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08008350 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8351 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07008352 }
Eric Laurent59255e42011-07-27 19:49:51 -07008353 }
Eric Laurent59255e42011-07-27 19:49:51 -07008354}
8355
8356sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8357 const effect_uuid_t *type)
8358{
Glenn Kasten090f0192012-01-30 13:00:02 -08008359 sp<EffectModule> effect = getEffectFromType_l(type);
8360 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008361}
8362
8363void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8364 bool enabled)
8365{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008366 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008367 if (enabled) {
8368 if (index < 0) {
8369 // if the effect is not suspend check if all effects are suspended
8370 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8371 if (index < 0) {
8372 return;
8373 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07008374 if (!isEffectEligibleForSuspend(effect->desc())) {
8375 return;
8376 }
Eric Laurent59255e42011-07-27 19:49:51 -07008377 setEffectSuspended_l(&effect->desc().type, enabled);
8378 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07008379 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008380 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07008381 return;
8382 }
Eric Laurent59255e42011-07-27 19:49:51 -07008383 }
Steve Block3856b092011-10-20 11:56:00 +01008384 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008385 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008386 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8387 // if effect is requested to suspended but was not yet enabled, supend it now.
8388 if (desc->mEffect == 0) {
8389 desc->mEffect = effect;
8390 effect->setEnabled(false);
8391 effect->setSuspended(true);
8392 }
8393 } else {
8394 if (index < 0) {
8395 return;
8396 }
Steve Block3856b092011-10-20 11:56:00 +01008397 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008398 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008399 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8400 desc->mEffect.clear();
8401 effect->setSuspended(false);
8402 }
8403}
8404
Mathias Agopian65ab4712010-07-14 17:59:35 -07008405#undef LOG_TAG
8406#define LOG_TAG "AudioFlinger"
8407
8408// ----------------------------------------------------------------------------
8409
8410status_t AudioFlinger::onTransact(
8411 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8412{
8413 return BnAudioFlinger::onTransact(code, data, reply, flags);
8414}
8415
Mathias Agopian65ab4712010-07-14 17:59:35 -07008416}; // namespace android