blob: eeecc4c6309a1d82337e04f01584e80dfcef905a [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
Gloria Wang9ee159b2011-02-24 14:51:45 -080040#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080041#include <media/IMediaDeathNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042
43#include <private/media/AudioTrackShared.h>
44#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070045
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070047#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080051#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
Mathias Agopian65ab4712010-07-14 17:59:35 -070053#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070054#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070055#include <audio_effects/effect_ns.h>
56#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Glenn Kasten3b21c502011-12-15 09:52:39 -080058#include <audio_utils/primitives.h>
59
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070060#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070061#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070062// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
63
John Grossman4ff14ba2012-02-08 16:37:41 -080064#include <common_time/cc_helper.h>
65#include <common_time/local_clock.h>
66
Mathias Agopian65ab4712010-07-14 17:59:35 -070067// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070068
Eric Laurentde070132010-07-13 04:45:46 -070069
Mathias Agopian65ab4712010-07-14 17:59:35 -070070namespace android {
71
Glenn Kastenec1d6b52011-12-12 09:04:45 -080072static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
73static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070074
Mathias Agopian65ab4712010-07-14 17:59:35 -070075static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -080076static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070077
78// retry counts for buffer fill timeout
79// 50 * ~20msecs = 1 second
80static const int8_t kMaxTrackRetries = 50;
81static const int8_t kMaxTrackStartupRetries = 50;
82// allow less retry attempts on direct output thread.
83// direct outputs can be a scarce resource in audio hardware and should
84// be released as quickly as possible.
85static const int8_t kMaxTrackRetriesDirect = 2;
86
87static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -080088static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
Glenn Kasten7dede872011-12-13 11:04:14 -080090// don't warn about blocked writes or record buffer overflows more often than this
91static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -070092
Eric Laurent7c7f10b2011-06-17 21:29:58 -070093// RecordThread loop sleep time upon application overrun or audio HAL read error
94static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070095
Glenn Kasten7dede872011-12-13 11:04:14 -080096// maximum time to wait for setParameters to complete
97static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -070098
Eric Laurent7cafbb32011-11-22 18:50:29 -080099// minimum sleep time for the mixer thread loop when tracks are active but in underrun
100static const uint32_t kMinThreadSleepTimeUs = 5000;
101// maximum divider applied to the active sleep time in the mixer thread loop
102static const uint32_t kMaxThreadSleepTimeShift = 2;
103
John Grossman4ff14ba2012-02-08 16:37:41 -0800104nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800105
Mathias Agopian65ab4712010-07-14 17:59:35 -0700106// ----------------------------------------------------------------------------
107
Gloria Wang9ee159b2011-02-24 14:51:45 -0800108// To collect the amplifier usage
109static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800110 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
111 if (service == NULL) {
112 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800113 return;
114 }
115
116 service->addBatteryData(params);
117}
118
Dima Zavin799a70e2011-04-18 16:57:27 -0700119static int load_audio_interface(const char *if_name, const hw_module_t **mod,
120 audio_hw_device_t **dev)
121{
122 int rc;
123
124 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
125 if (rc)
126 goto out;
127
128 rc = audio_hw_device_open(*mod, dev);
Steve Block29357bc2012-01-06 19:20:56 +0000129 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin799a70e2011-04-18 16:57:27 -0700130 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
131 if (rc)
132 goto out;
133
134 return 0;
135
136out:
137 *mod = NULL;
138 *dev = NULL;
139 return rc;
140}
141
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800142static const char * const audio_interfaces[] = {
Dima Zavin799a70e2011-04-18 16:57:27 -0700143 "primary",
144 "a2dp",
145 "usb",
146};
147#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
148
Mathias Agopian65ab4712010-07-14 17:59:35 -0700149// ----------------------------------------------------------------------------
150
151AudioFlinger::AudioFlinger()
152 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800153 mPrimaryHardwareDev(NULL),
154 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
155 mMasterVolume(1.0f),
156 mMasterVolumeSupportLvl(MVS_NONE),
157 mMasterMute(false),
158 mNextUniqueId(1),
159 mMode(AUDIO_MODE_INVALID),
160 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700161{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700162}
163
164void AudioFlinger::onFirstRef()
165{
Dima Zavin799a70e2011-04-18 16:57:27 -0700166 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700167
Eric Laurent93575202011-01-18 18:39:02 -0800168 Mutex::Autolock _l(mLock);
169
Dima Zavin799a70e2011-04-18 16:57:27 -0700170 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800171 char val_str[PROPERTY_VALUE_MAX] = { 0 };
172 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
173 uint32_t int_val;
174 if (1 == sscanf(val_str, "%u", &int_val)) {
175 mStandbyTimeInNsecs = milliseconds(int_val);
176 ALOGI("Using %u mSec as standby time.", int_val);
177 } else {
178 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
179 ALOGI("Using default %u mSec as standby time.",
180 (uint32_t)(mStandbyTimeInNsecs / 1000000));
181 }
182 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700183
Dima Zavin799a70e2011-04-18 16:57:27 -0700184 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
185 const hw_module_t *mod;
186 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700187
Dima Zavin799a70e2011-04-18 16:57:27 -0700188 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
189 if (rc)
190 continue;
191
Steve Blockdf64d152012-01-04 20:05:49 +0000192 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700193 mod->name, mod->id);
Dima Zavin799a70e2011-04-18 16:57:27 -0700194 mAudioHwDevs.push(dev);
195
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800196 if (mPrimaryHardwareDev == NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700197 mPrimaryHardwareDev = dev;
Steve Blockdf64d152012-01-04 20:05:49 +0000198 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700199 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700200 }
201 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700202
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800203 if (mPrimaryHardwareDev == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000204 ALOGE("Primary audio interface not found");
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800205 // proceed, all later accesses to mPrimaryHardwareDev verify it's safe with initCheck()
Dima Zavin799a70e2011-04-18 16:57:27 -0700206 }
207
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800208 // Currently (mPrimaryHardwareDev == NULL) == (mAudioHwDevs.size() == 0), but the way the
209 // primary HW dev is selected can change so these conditions might not always be equivalent.
210 // When that happens, re-visit all the code that assumes this.
211
212 AutoMutex lock(mHardwareLock);
213
John Grossman4ff14ba2012-02-08 16:37:41 -0800214 // Determine the level of master volume support the primary audio HAL has,
215 // and set the initial master volume at the same time.
216 float initialVolume = 1.0;
217 mMasterVolumeSupportLvl = MVS_NONE;
218 if (0 == mPrimaryHardwareDev->init_check(mPrimaryHardwareDev)) {
219 audio_hw_device_t *dev = mPrimaryHardwareDev;
220
221 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
222 if ((NULL != dev->get_master_volume) &&
223 (NO_ERROR == dev->get_master_volume(dev, &initialVolume))) {
224 mMasterVolumeSupportLvl = MVS_FULL;
225 } else {
226 mMasterVolumeSupportLvl = MVS_SETONLY;
227 initialVolume = 1.0;
228 }
229
230 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
231 if ((NULL == dev->set_master_volume) ||
232 (NO_ERROR != dev->set_master_volume(dev, initialVolume))) {
233 mMasterVolumeSupportLvl = MVS_NONE;
234 }
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800235 mHardwareStatus = AUDIO_HW_IDLE;
John Grossman4ff14ba2012-02-08 16:37:41 -0800236 }
237
238 // Set the mode for each audio HAL, and try to set the initial volume (if
239 // supported) for all of the non-primary audio HALs.
Dima Zavin799a70e2011-04-18 16:57:27 -0700240 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
241 audio_hw_device_t *dev = mAudioHwDevs[i];
242
243 mHardwareStatus = AUDIO_HW_INIT;
244 rc = dev->init_check(dev);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800245 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700246 if (rc == 0) {
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800247 mMode = AUDIO_MODE_NORMAL; // assigned multiple times with same value
Dima Zavin799a70e2011-04-18 16:57:27 -0700248 mHardwareStatus = AUDIO_HW_SET_MODE;
249 dev->set_mode(dev, mMode);
John Grossman4ff14ba2012-02-08 16:37:41 -0800250
251 if ((dev != mPrimaryHardwareDev) &&
252 (NULL != dev->set_master_volume)) {
253 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
254 dev->set_master_volume(dev, initialVolume);
255 }
256
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800257 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700258 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700259 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800260
261 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
262 ? initialVolume
263 : 1.0;
264 mMasterVolume = initialVolume;
265 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700266}
267
268AudioFlinger::~AudioFlinger()
269{
Dima Zavin799a70e2011-04-18 16:57:27 -0700270
Mathias Agopian65ab4712010-07-14 17:59:35 -0700271 while (!mRecordThreads.isEmpty()) {
272 // closeInput() will remove first entry from mRecordThreads
273 closeInput(mRecordThreads.keyAt(0));
274 }
275 while (!mPlaybackThreads.isEmpty()) {
276 // closeOutput() will remove first entry from mPlaybackThreads
277 closeOutput(mPlaybackThreads.keyAt(0));
278 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700279
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800280 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
281 // no mHardwareLock needed, as there are no other references to this
282 audio_hw_device_close(mAudioHwDevs[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700283 }
284}
285
Dima Zavin799a70e2011-04-18 16:57:27 -0700286audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
287{
288 /* first matching HW device is returned */
289 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
290 audio_hw_device_t *dev = mAudioHwDevs[i];
291 if ((dev->get_supported_devices(dev) & devices) == devices)
292 return dev;
293 }
294 return NULL;
295}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700296
297status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
298{
299 const size_t SIZE = 256;
300 char buffer[SIZE];
301 String8 result;
302
303 result.append("Clients:\n");
304 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800305 sp<Client> client = mClients.valueAt(i).promote();
306 if (client != 0) {
307 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
308 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700309 }
310 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700311
312 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800313 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700314 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
315 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800316 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700317 result.append(buffer);
318 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700319 write(fd, result.string(), result.size());
320 return NO_ERROR;
321}
322
323
324status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
325{
326 const size_t SIZE = 256;
327 char buffer[SIZE];
328 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800329 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700330
John Grossman4ff14ba2012-02-08 16:37:41 -0800331 snprintf(buffer, SIZE, "Hardware status: %d\n"
332 "Standby Time mSec: %u\n",
333 hardwareStatus,
334 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700335 result.append(buffer);
336 write(fd, result.string(), result.size());
337 return NO_ERROR;
338}
339
340status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
341{
342 const size_t SIZE = 256;
343 char buffer[SIZE];
344 String8 result;
345 snprintf(buffer, SIZE, "Permission Denial: "
346 "can't dump AudioFlinger from pid=%d, uid=%d\n",
347 IPCThreadState::self()->getCallingPid(),
348 IPCThreadState::self()->getCallingUid());
349 result.append(buffer);
350 write(fd, result.string(), result.size());
351 return NO_ERROR;
352}
353
354static bool tryLock(Mutex& mutex)
355{
356 bool locked = false;
357 for (int i = 0; i < kDumpLockRetries; ++i) {
358 if (mutex.tryLock() == NO_ERROR) {
359 locked = true;
360 break;
361 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800362 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700363 }
364 return locked;
365}
366
367status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
368{
Glenn Kasten44deb052012-02-05 18:09:08 -0800369 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700370 dumpPermissionDenial(fd, args);
371 } else {
372 // get state of hardware lock
373 bool hardwareLocked = tryLock(mHardwareLock);
374 if (!hardwareLocked) {
375 String8 result(kHardwareLockedString);
376 write(fd, result.string(), result.size());
377 } else {
378 mHardwareLock.unlock();
379 }
380
381 bool locked = tryLock(mLock);
382
383 // failed to lock - AudioFlinger is probably deadlocked
384 if (!locked) {
385 String8 result(kDeadlockedString);
386 write(fd, result.string(), result.size());
387 }
388
389 dumpClients(fd, args);
390 dumpInternals(fd, args);
391
392 // dump playback threads
393 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
394 mPlaybackThreads.valueAt(i)->dump(fd, args);
395 }
396
397 // dump record threads
398 for (size_t i = 0; i < mRecordThreads.size(); i++) {
399 mRecordThreads.valueAt(i)->dump(fd, args);
400 }
401
Dima Zavin799a70e2011-04-18 16:57:27 -0700402 // dump all hardware devs
403 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
404 audio_hw_device_t *dev = mAudioHwDevs[i];
405 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700406 }
407 if (locked) mLock.unlock();
408 }
409 return NO_ERROR;
410}
411
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800412sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
413{
414 // If pid is already in the mClients wp<> map, then use that entry
415 // (for which promote() is always != 0), otherwise create a new entry and Client.
416 sp<Client> client = mClients.valueFor(pid).promote();
417 if (client == 0) {
418 client = new Client(this, pid);
419 mClients.add(pid, client);
420 }
421
422 return client;
423}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700424
425// IAudioFlinger interface
426
427
428sp<IAudioTrack> AudioFlinger::createTrack(
429 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800430 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700431 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800432 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700433 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700434 int frameCount,
Glenn Kasten5cf034d2012-02-21 10:35:56 -0800435 // FIXME dead, remove from IAudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700436 uint32_t flags,
437 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800438 audio_io_handle_t output,
John Grossman4ff14ba2012-02-08 16:37:41 -0800439 bool isTimed,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700440 int *sessionId,
441 status_t *status)
442{
443 sp<PlaybackThread::Track> track;
444 sp<TrackHandle> trackHandle;
445 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700446 status_t lStatus;
447 int lSessionId;
448
Glenn Kasten263709e2012-01-06 08:40:01 -0800449 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
450 // but if someone uses binder directly they could bypass that and cause us to crash
451 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000452 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700453 lStatus = BAD_VALUE;
454 goto Exit;
455 }
456
457 {
458 Mutex::Autolock _l(mLock);
459 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700460 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700461 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000462 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700463 lStatus = BAD_VALUE;
464 goto Exit;
465 }
466
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800467 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700468
Steve Block3856b092011-10-20 11:56:00 +0100469 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700470 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700471 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700472 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
473 if (mPlaybackThreads.keyAt(i) != output) {
474 // prevent same audio session on different output threads
475 uint32_t sessions = t->hasAudioSession(*sessionId);
476 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000477 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700478 lStatus = BAD_VALUE;
479 goto Exit;
480 }
481 // check if an effect with same session ID is waiting for a track to be created
482 if (sessions & PlaybackThread::EFFECT_SESSION) {
483 effectThread = t.get();
484 }
Eric Laurentde070132010-07-13 04:45:46 -0700485 }
486 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700487 lSessionId = *sessionId;
488 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700489 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700490 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700491 if (sessionId != NULL) {
492 *sessionId = lSessionId;
493 }
494 }
Steve Block3856b092011-10-20 11:56:00 +0100495 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700496
497 track = thread->createTrack_l(client, streamType, sampleRate, format,
John Grossman4ff14ba2012-02-08 16:37:41 -0800498 channelMask, frameCount, sharedBuffer, lSessionId, isTimed, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700499
500 // move effect chain to this output thread if an effect on same session was waiting
501 // for a track to be created
502 if (lStatus == NO_ERROR && effectThread != NULL) {
503 Mutex::Autolock _dl(thread->mLock);
504 Mutex::Autolock _sl(effectThread->mLock);
505 moveEffectChain_l(lSessionId, effectThread, thread, true);
506 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700507 }
508 if (lStatus == NO_ERROR) {
509 trackHandle = new TrackHandle(track);
510 } else {
511 // remove local strong reference to Client before deleting the Track so that the Client
512 // destructor is called by the TrackBase destructor with mLock held
513 client.clear();
514 track.clear();
515 }
516
517Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700518 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700519 *status = lStatus;
520 }
521 return trackHandle;
522}
523
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800524uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700525{
526 Mutex::Autolock _l(mLock);
527 PlaybackThread *thread = checkPlaybackThread_l(output);
528 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000529 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700530 return 0;
531 }
532 return thread->sampleRate();
533}
534
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800535int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700536{
537 Mutex::Autolock _l(mLock);
538 PlaybackThread *thread = checkPlaybackThread_l(output);
539 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000540 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700541 return 0;
542 }
543 return thread->channelCount();
544}
545
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800546audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700547{
548 Mutex::Autolock _l(mLock);
549 PlaybackThread *thread = checkPlaybackThread_l(output);
550 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000551 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800552 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700553 }
554 return thread->format();
555}
556
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800557size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700558{
559 Mutex::Autolock _l(mLock);
560 PlaybackThread *thread = checkPlaybackThread_l(output);
561 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000562 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700563 return 0;
564 }
565 return thread->frameCount();
566}
567
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800568uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700569{
570 Mutex::Autolock _l(mLock);
571 PlaybackThread *thread = checkPlaybackThread_l(output);
572 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000573 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700574 return 0;
575 }
576 return thread->latency();
577}
578
579status_t AudioFlinger::setMasterVolume(float value)
580{
Eric Laurenta1884f92011-08-23 08:25:03 -0700581 status_t ret = initCheck();
582 if (ret != NO_ERROR) {
583 return ret;
584 }
585
Mathias Agopian65ab4712010-07-14 17:59:35 -0700586 // check calling permissions
587 if (!settingsAllowed()) {
588 return PERMISSION_DENIED;
589 }
590
John Grossman4ff14ba2012-02-08 16:37:41 -0800591 float swmv = value;
592
Mathias Agopian65ab4712010-07-14 17:59:35 -0700593 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800594 if (MVS_NONE != mMasterVolumeSupportLvl) {
595 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
596 AutoMutex lock(mHardwareLock);
597 audio_hw_device_t *dev = mAudioHwDevs[i];
598
599 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
600 if (NULL != dev->set_master_volume) {
601 dev->set_master_volume(dev, value);
602 }
603 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800604 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800605
606 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700607 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700608
Eric Laurent93575202011-01-18 18:39:02 -0800609 Mutex::Autolock _l(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -0800610 mMasterVolume = value;
611 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800612 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700613 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700614
615 return NO_ERROR;
616}
617
Glenn Kastenf78aee72012-01-04 11:00:47 -0800618status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700619{
Eric Laurenta1884f92011-08-23 08:25:03 -0700620 status_t ret = initCheck();
621 if (ret != NO_ERROR) {
622 return ret;
623 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700624
625 // check calling permissions
626 if (!settingsAllowed()) {
627 return PERMISSION_DENIED;
628 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800629 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000630 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700631 return BAD_VALUE;
632 }
633
634 { // scope for the lock
635 AutoMutex lock(mHardwareLock);
636 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700637 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700638 mHardwareStatus = AUDIO_HW_IDLE;
639 }
640
641 if (NO_ERROR == ret) {
642 Mutex::Autolock _l(mLock);
643 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800644 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700645 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700646 }
647
648 return ret;
649}
650
651status_t AudioFlinger::setMicMute(bool state)
652{
Eric Laurenta1884f92011-08-23 08:25:03 -0700653 status_t ret = initCheck();
654 if (ret != NO_ERROR) {
655 return ret;
656 }
657
Mathias Agopian65ab4712010-07-14 17:59:35 -0700658 // check calling permissions
659 if (!settingsAllowed()) {
660 return PERMISSION_DENIED;
661 }
662
663 AutoMutex lock(mHardwareLock);
664 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700665 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700666 mHardwareStatus = AUDIO_HW_IDLE;
667 return ret;
668}
669
670bool AudioFlinger::getMicMute() const
671{
Eric Laurenta1884f92011-08-23 08:25:03 -0700672 status_t ret = initCheck();
673 if (ret != NO_ERROR) {
674 return false;
675 }
676
Dima Zavinfce7a472011-04-19 22:30:36 -0700677 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800678 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700679 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700680 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700681 mHardwareStatus = AUDIO_HW_IDLE;
682 return state;
683}
684
685status_t AudioFlinger::setMasterMute(bool muted)
686{
687 // check calling permissions
688 if (!settingsAllowed()) {
689 return PERMISSION_DENIED;
690 }
691
Eric Laurent93575202011-01-18 18:39:02 -0800692 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800693 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700694 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800695 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700696 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700697
698 return NO_ERROR;
699}
700
701float AudioFlinger::masterVolume() const
702{
Glenn Kasten98067102011-12-13 11:47:54 -0800703 Mutex::Autolock _l(mLock);
704 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700705}
706
John Grossman4ff14ba2012-02-08 16:37:41 -0800707float AudioFlinger::masterVolumeSW() const
708{
709 Mutex::Autolock _l(mLock);
710 return masterVolumeSW_l();
711}
712
Mathias Agopian65ab4712010-07-14 17:59:35 -0700713bool AudioFlinger::masterMute() const
714{
Glenn Kasten98067102011-12-13 11:47:54 -0800715 Mutex::Autolock _l(mLock);
716 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700717}
718
John Grossman4ff14ba2012-02-08 16:37:41 -0800719float AudioFlinger::masterVolume_l() const
720{
721 if (MVS_FULL == mMasterVolumeSupportLvl) {
722 float ret_val;
723 AutoMutex lock(mHardwareLock);
724
725 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800726 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
727 (NULL != mPrimaryHardwareDev->get_master_volume),
728 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800729
730 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
731 mHardwareStatus = AUDIO_HW_IDLE;
732 return ret_val;
733 }
734
735 return mMasterVolume;
736}
737
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800738status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
739 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700740{
741 // check calling permissions
742 if (!settingsAllowed()) {
743 return PERMISSION_DENIED;
744 }
745
Glenn Kasten263709e2012-01-06 08:40:01 -0800746 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000747 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700748 return BAD_VALUE;
749 }
750
751 AutoMutex lock(mLock);
752 PlaybackThread *thread = NULL;
753 if (output) {
754 thread = checkPlaybackThread_l(output);
755 if (thread == NULL) {
756 return BAD_VALUE;
757 }
758 }
759
760 mStreamTypes[stream].volume = value;
761
762 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800763 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700764 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700765 }
766 } else {
767 thread->setStreamVolume(stream, value);
768 }
769
770 return NO_ERROR;
771}
772
Glenn Kastenfff6d712012-01-12 16:38:12 -0800773status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700774{
775 // check calling permissions
776 if (!settingsAllowed()) {
777 return PERMISSION_DENIED;
778 }
779
Glenn Kasten263709e2012-01-06 08:40:01 -0800780 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700781 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000782 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700783 return BAD_VALUE;
784 }
785
Eric Laurent93575202011-01-18 18:39:02 -0800786 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700787 mStreamTypes[stream].mute = muted;
788 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700789 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700790
791 return NO_ERROR;
792}
793
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800794float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700795{
Glenn Kasten263709e2012-01-06 08:40:01 -0800796 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700797 return 0.0f;
798 }
799
800 AutoMutex lock(mLock);
801 float volume;
802 if (output) {
803 PlaybackThread *thread = checkPlaybackThread_l(output);
804 if (thread == NULL) {
805 return 0.0f;
806 }
807 volume = thread->streamVolume(stream);
808 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800809 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700810 }
811
812 return volume;
813}
814
Glenn Kastenfff6d712012-01-12 16:38:12 -0800815bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700816{
Glenn Kasten263709e2012-01-06 08:40:01 -0800817 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700818 return true;
819 }
820
Glenn Kasten6637baa2012-01-09 09:40:36 -0800821 AutoMutex lock(mLock);
822 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700823}
824
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800825status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700826{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800827 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700828 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
829 // check calling permissions
830 if (!settingsAllowed()) {
831 return PERMISSION_DENIED;
832 }
833
Mathias Agopian65ab4712010-07-14 17:59:35 -0700834 // ioHandle == 0 means the parameters are global to the audio hardware interface
835 if (ioHandle == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700836 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800837 {
838 AutoMutex lock(mHardwareLock);
839 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700840 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
841 audio_hw_device_t *dev = mAudioHwDevs[i];
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800842 status_t result = dev->set_parameters(dev, keyValuePairs.string());
Dima Zavin799a70e2011-04-18 16:57:27 -0700843 final_result = result ?: final_result;
844 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800846 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700847 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
848 AudioParameter param = AudioParameter(keyValuePairs);
849 String8 value;
850 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
851 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700852 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
853 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700854 for (size_t i = 0; i < mRecordThreads.size(); i++) {
855 sp<RecordThread> thread = mRecordThreads.valueAt(i);
856 RecordThread::RecordTrack *track = thread->track();
857 if (track != NULL) {
858 audio_devices_t device = (audio_devices_t)(
859 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700860 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700861 thread->setEffectSuspended(FX_IID_AEC,
862 suspend,
863 track->sessionId());
864 thread->setEffectSuspended(FX_IID_NS,
865 suspend,
866 track->sessionId());
867 }
868 }
Eric Laurentbee53372011-08-29 12:42:48 -0700869 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700870 }
871 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700872 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700873 }
874
875 // hold a strong ref on thread in case closeOutput() or closeInput() is called
876 // and the thread is exited once the lock is released
877 sp<ThreadBase> thread;
878 {
879 Mutex::Autolock _l(mLock);
880 thread = checkPlaybackThread_l(ioHandle);
881 if (thread == NULL) {
882 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800883 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700884 // indicate output device change to all input threads for pre processing
885 AudioParameter param = AudioParameter(keyValuePairs);
886 int value;
887 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
888 for (size_t i = 0; i < mRecordThreads.size(); i++) {
889 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
890 }
891 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700892 }
893 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800894 if (thread != 0) {
895 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700896 }
897 return BAD_VALUE;
898}
899
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800900String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700901{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800902// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700903// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
904
905 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700906 String8 out_s8;
907
Dima Zavin799a70e2011-04-18 16:57:27 -0700908 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800909 char *s;
910 {
911 AutoMutex lock(mHardwareLock);
912 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700913 audio_hw_device_t *dev = mAudioHwDevs[i];
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800914 s = dev->get_parameters(dev, keys.string());
915 mHardwareStatus = AUDIO_HW_IDLE;
916 }
John Grossmanef7740b2012-02-09 11:28:36 -0800917 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700918 free(s);
919 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700920 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700921 }
922
923 Mutex::Autolock _l(mLock);
924
925 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
926 if (playbackThread != NULL) {
927 return playbackThread->getParameters(keys);
928 }
929 RecordThread *recordThread = checkRecordThread_l(ioHandle);
930 if (recordThread != NULL) {
931 return recordThread->getParameters(keys);
932 }
933 return String8("");
934}
935
Glenn Kastenf587ba52012-01-26 16:25:10 -0800936size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700937{
Eric Laurenta1884f92011-08-23 08:25:03 -0700938 status_t ret = initCheck();
939 if (ret != NO_ERROR) {
940 return 0;
941 }
942
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800943 AutoMutex lock(mHardwareLock);
944 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
945 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
946 mHardwareStatus = AUDIO_HW_IDLE;
947 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700948}
949
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800950unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700951{
952 if (ioHandle == 0) {
953 return 0;
954 }
955
956 Mutex::Autolock _l(mLock);
957
958 RecordThread *recordThread = checkRecordThread_l(ioHandle);
959 if (recordThread != NULL) {
960 return recordThread->getInputFramesLost();
961 }
962 return 0;
963}
964
965status_t AudioFlinger::setVoiceVolume(float value)
966{
Eric Laurenta1884f92011-08-23 08:25:03 -0700967 status_t ret = initCheck();
968 if (ret != NO_ERROR) {
969 return ret;
970 }
971
Mathias Agopian65ab4712010-07-14 17:59:35 -0700972 // check calling permissions
973 if (!settingsAllowed()) {
974 return PERMISSION_DENIED;
975 }
976
977 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800978 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700979 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700980 mHardwareStatus = AUDIO_HW_IDLE;
981
982 return ret;
983}
984
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800985status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
986 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700987{
988 status_t status;
989
990 Mutex::Autolock _l(mLock);
991
992 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
993 if (playbackThread != NULL) {
994 return playbackThread->getRenderPosition(halFrames, dspFrames);
995 }
996
997 return BAD_VALUE;
998}
999
1000void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1001{
1002
1003 Mutex::Autolock _l(mLock);
1004
Glenn Kastenbb001922012-02-03 11:10:26 -08001005 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001006 if (mNotificationClients.indexOfKey(pid) < 0) {
1007 sp<NotificationClient> notificationClient = new NotificationClient(this,
1008 client,
1009 pid);
Steve Block3856b092011-10-20 11:56:00 +01001010 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001011
1012 mNotificationClients.add(pid, notificationClient);
1013
1014 sp<IBinder> binder = client->asBinder();
1015 binder->linkToDeath(notificationClient);
1016
1017 // the config change is always sent from playback or record threads to avoid deadlock
1018 // with AudioSystem::gLock
1019 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1020 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1021 }
1022
1023 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1024 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1025 }
1026 }
1027}
1028
1029void AudioFlinger::removeNotificationClient(pid_t pid)
1030{
1031 Mutex::Autolock _l(mLock);
1032
Glenn Kastena3b09252012-01-20 09:19:01 -08001033 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001034
Steve Block3856b092011-10-20 11:56:00 +01001035 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001036 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001037 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001038 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001039 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001040 ALOGV(" pid %d @ %d", ref->mPid, i);
1041 if (ref->mPid == pid) {
1042 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001043 mAudioSessionRefs.removeAt(i);
1044 delete ref;
1045 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001046 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001047 } else {
1048 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001049 }
1050 }
1051 if (removed) {
1052 purgeStaleEffects_l();
1053 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001054}
1055
1056// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001057void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001058{
1059 size_t size = mNotificationClients.size();
1060 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001061 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1062 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001063 }
1064}
1065
1066// removeClient_l() must be called with AudioFlinger::mLock held
1067void AudioFlinger::removeClient_l(pid_t pid)
1068{
Steve Block3856b092011-10-20 11:56:00 +01001069 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001070 mClients.removeItem(pid);
1071}
1072
1073
1074// ----------------------------------------------------------------------------
1075
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001076AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1077 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001079 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001080 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
1081 // mChannelMask
1082 mChannelCount(0),
1083 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1084 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001085 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001086 mDevice(device),
1087 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001088{
1089}
1090
1091AudioFlinger::ThreadBase::~ThreadBase()
1092{
1093 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001094 // do not lock the mutex in destructor
1095 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001096 if (mPowerManager != 0) {
1097 sp<IBinder> binder = mPowerManager->asBinder();
1098 binder->unlinkToDeath(mDeathRecipient);
1099 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001100}
1101
1102void AudioFlinger::ThreadBase::exit()
1103{
Steve Block3856b092011-10-20 11:56:00 +01001104 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001105 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001106 // This lock prevents the following race in thread (uniprocessor for illustration):
1107 // if (!exitPending()) {
1108 // // context switch from here to exit()
1109 // // exit() calls requestExit(), what exitPending() observes
1110 // // exit() calls signal(), which is dropped since no waiters
1111 // // context switch back from exit() to here
1112 // mWaitWorkCV.wait(...);
1113 // // now thread is hung
1114 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001115 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001116 requestExit();
1117 mWaitWorkCV.signal();
1118 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001119 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1120 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001121 requestExitAndWait();
1122}
1123
Mathias Agopian65ab4712010-07-14 17:59:35 -07001124status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1125{
1126 status_t status;
1127
Steve Block3856b092011-10-20 11:56:00 +01001128 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001129 Mutex::Autolock _l(mLock);
1130
1131 mNewParameters.add(keyValuePairs);
1132 mWaitWorkCV.signal();
1133 // wait condition with timeout in case the thread loop has exited
1134 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001135 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001136 status = mParamStatus;
1137 mWaitWorkCV.signal();
1138 } else {
1139 status = TIMED_OUT;
1140 }
1141 return status;
1142}
1143
1144void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1145{
1146 Mutex::Autolock _l(mLock);
1147 sendConfigEvent_l(event, param);
1148}
1149
1150// sendConfigEvent_l() must be called with ThreadBase::mLock held
1151void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1152{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001153 ConfigEvent configEvent;
1154 configEvent.mEvent = event;
1155 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001156 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001157 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001158 mWaitWorkCV.signal();
1159}
1160
1161void AudioFlinger::ThreadBase::processConfigEvents()
1162{
1163 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001164 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001165 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001166 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001167 mConfigEvents.removeAt(0);
1168 // release mLock before locking AudioFlinger mLock: lock order is always
1169 // AudioFlinger then ThreadBase to avoid cross deadlock
1170 mLock.unlock();
1171 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001172 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001173 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001174 mLock.lock();
1175 }
1176 mLock.unlock();
1177}
1178
1179status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1180{
1181 const size_t SIZE = 256;
1182 char buffer[SIZE];
1183 String8 result;
1184
1185 bool locked = tryLock(mLock);
1186 if (!locked) {
1187 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1188 write(fd, buffer, strlen(buffer));
1189 }
1190
Eric Laurent612bbb52012-03-14 15:03:26 -07001191 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1192 result.append(buffer);
1193 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1194 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001195 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1196 result.append(buffer);
1197 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1198 result.append(buffer);
1199 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1200 result.append(buffer);
1201 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1202 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001203 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1204 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001205 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1206 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001207 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001208 result.append(buffer);
1209
1210 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1211 result.append(buffer);
1212 result.append(" Index Command");
1213 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1214 snprintf(buffer, SIZE, "\n %02d ", i);
1215 result.append(buffer);
1216 result.append(mNewParameters[i]);
1217 }
1218
1219 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1220 result.append(buffer);
1221 snprintf(buffer, SIZE, " Index event param\n");
1222 result.append(buffer);
1223 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001224 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001225 result.append(buffer);
1226 }
1227 result.append("\n");
1228
1229 write(fd, result.string(), result.size());
1230
1231 if (locked) {
1232 mLock.unlock();
1233 }
1234 return NO_ERROR;
1235}
1236
Eric Laurent1d2bff02011-07-24 17:49:51 -07001237status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1238{
1239 const size_t SIZE = 256;
1240 char buffer[SIZE];
1241 String8 result;
1242
1243 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1244 write(fd, buffer, strlen(buffer));
1245
1246 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1247 sp<EffectChain> chain = mEffectChains[i];
1248 if (chain != 0) {
1249 chain->dump(fd, args);
1250 }
1251 }
1252 return NO_ERROR;
1253}
1254
Eric Laurentfeb0db62011-07-22 09:04:31 -07001255void AudioFlinger::ThreadBase::acquireWakeLock()
1256{
1257 Mutex::Autolock _l(mLock);
1258 acquireWakeLock_l();
1259}
1260
1261void AudioFlinger::ThreadBase::acquireWakeLock_l()
1262{
1263 if (mPowerManager == 0) {
1264 // use checkService() to avoid blocking if power service is not up yet
1265 sp<IBinder> binder =
1266 defaultServiceManager()->checkService(String16("power"));
1267 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001268 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001269 } else {
1270 mPowerManager = interface_cast<IPowerManager>(binder);
1271 binder->linkToDeath(mDeathRecipient);
1272 }
1273 }
1274 if (mPowerManager != 0) {
1275 sp<IBinder> binder = new BBinder();
1276 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1277 binder,
1278 String16(mName));
1279 if (status == NO_ERROR) {
1280 mWakeLockToken = binder;
1281 }
Steve Block3856b092011-10-20 11:56:00 +01001282 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001283 }
1284}
1285
1286void AudioFlinger::ThreadBase::releaseWakeLock()
1287{
1288 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001289 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001290}
1291
1292void AudioFlinger::ThreadBase::releaseWakeLock_l()
1293{
1294 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001295 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001296 if (mPowerManager != 0) {
1297 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1298 }
1299 mWakeLockToken.clear();
1300 }
1301}
1302
1303void AudioFlinger::ThreadBase::clearPowerManager()
1304{
1305 Mutex::Autolock _l(mLock);
1306 releaseWakeLock_l();
1307 mPowerManager.clear();
1308}
1309
1310void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1311{
1312 sp<ThreadBase> thread = mThread.promote();
1313 if (thread != 0) {
1314 thread->clearPowerManager();
1315 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001316 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001317}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001318
Eric Laurent59255e42011-07-27 19:49:51 -07001319void AudioFlinger::ThreadBase::setEffectSuspended(
1320 const effect_uuid_t *type, bool suspend, int sessionId)
1321{
1322 Mutex::Autolock _l(mLock);
1323 setEffectSuspended_l(type, suspend, sessionId);
1324}
1325
1326void AudioFlinger::ThreadBase::setEffectSuspended_l(
1327 const effect_uuid_t *type, bool suspend, int sessionId)
1328{
Glenn Kasten090f0192012-01-30 13:00:02 -08001329 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001330 if (chain != 0) {
1331 if (type != NULL) {
1332 chain->setEffectSuspended_l(type, suspend);
1333 } else {
1334 chain->setEffectSuspendedAll_l(suspend);
1335 }
1336 }
1337
1338 updateSuspendedSessions_l(type, suspend, sessionId);
1339}
1340
1341void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1342{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001343 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001344 if (index < 0) {
1345 return;
1346 }
1347
1348 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1349 mSuspendedSessions.editValueAt(index);
1350
1351 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001352 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001353 for (int j = 0; j < desc->mRefCount; j++) {
1354 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1355 chain->setEffectSuspendedAll_l(true);
1356 } else {
Steve Block3856b092011-10-20 11:56:00 +01001357 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001358 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001359 chain->setEffectSuspended_l(&desc->mType, true);
1360 }
1361 }
1362 }
1363}
1364
Eric Laurent59255e42011-07-27 19:49:51 -07001365void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1366 bool suspend,
1367 int sessionId)
1368{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001369 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001370
1371 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1372
1373 if (suspend) {
1374 if (index >= 0) {
1375 sessionEffects = mSuspendedSessions.editValueAt(index);
1376 } else {
1377 mSuspendedSessions.add(sessionId, sessionEffects);
1378 }
1379 } else {
1380 if (index < 0) {
1381 return;
1382 }
1383 sessionEffects = mSuspendedSessions.editValueAt(index);
1384 }
1385
1386
1387 int key = EffectChain::kKeyForSuspendAll;
1388 if (type != NULL) {
1389 key = type->timeLow;
1390 }
1391 index = sessionEffects.indexOfKey(key);
1392
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001393 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001394 if (suspend) {
1395 if (index >= 0) {
1396 desc = sessionEffects.valueAt(index);
1397 } else {
1398 desc = new SuspendedSessionDesc();
1399 if (type != NULL) {
1400 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1401 }
1402 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001403 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001404 }
1405 desc->mRefCount++;
1406 } else {
1407 if (index < 0) {
1408 return;
1409 }
1410 desc = sessionEffects.valueAt(index);
1411 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001412 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001413 sessionEffects.removeItemsAt(index);
1414 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001415 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001416 sessionId);
1417 mSuspendedSessions.removeItem(sessionId);
1418 }
1419 }
1420 }
1421 if (!sessionEffects.isEmpty()) {
1422 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1423 }
1424}
1425
1426void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1427 bool enabled,
1428 int sessionId)
1429{
1430 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001431 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1432}
Eric Laurent59255e42011-07-27 19:49:51 -07001433
Eric Laurenta85a74a2011-10-19 11:44:54 -07001434void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1435 bool enabled,
1436 int sessionId)
1437{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001438 if (mType != RECORD) {
1439 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1440 // another session. This gives the priority to well behaved effect control panels
1441 // and applications not using global effects.
1442 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1443 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1444 }
1445 }
Eric Laurent59255e42011-07-27 19:49:51 -07001446
1447 sp<EffectChain> chain = getEffectChain_l(sessionId);
1448 if (chain != 0) {
1449 chain->checkSuspendOnEffectEnabled(effect, enabled);
1450 }
1451}
1452
Mathias Agopian65ab4712010-07-14 17:59:35 -07001453// ----------------------------------------------------------------------------
1454
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001455AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1456 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001457 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001458 uint32_t device,
1459 type_t type)
1460 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001461 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1462 // Assumes constructor is called by AudioFlinger with it's mLock held,
1463 // but it would be safer to explicitly pass initial masterMute as parameter
1464 mMasterMute(audioFlinger->masterMute_l()),
1465 // mStreamTypes[] initialized in constructor body
1466 mOutput(output),
1467 // Assumes constructor is called by AudioFlinger with it's mLock held,
1468 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001469 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001470 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001471 mMixerStatus(MIXER_IDLE),
Glenn Kasten66fcab92012-02-24 14:59:21 -08001472 mPrevMixerStatus(MIXER_IDLE),
1473 standbyDelay(AudioFlinger::mStandbyTimeInNsecs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001474{
Glenn Kasten480b4682012-02-28 12:30:08 -08001475 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001476
Mathias Agopian65ab4712010-07-14 17:59:35 -07001477 readOutputParameters();
1478
Glenn Kasten263709e2012-01-06 08:40:01 -08001479 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001480 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1481 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1482 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001483 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1484 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001485 // initialized by stream_type_t default constructor
1486 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001487 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001488 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1489 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001490}
1491
1492AudioFlinger::PlaybackThread::~PlaybackThread()
1493{
1494 delete [] mMixBuffer;
1495}
1496
1497status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1498{
1499 dumpInternals(fd, args);
1500 dumpTracks(fd, args);
1501 dumpEffectChains(fd, args);
1502 return NO_ERROR;
1503}
1504
1505status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1506{
1507 const size_t SIZE = 256;
1508 char buffer[SIZE];
1509 String8 result;
1510
1511 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1512 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001513 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 -07001514 for (size_t i = 0; i < mTracks.size(); ++i) {
1515 sp<Track> track = mTracks[i];
1516 if (track != 0) {
1517 track->dump(buffer, SIZE);
1518 result.append(buffer);
1519 }
1520 }
1521
1522 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1523 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001524 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 -07001525 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001526 sp<Track> track = mActiveTracks[i].promote();
1527 if (track != 0) {
1528 track->dump(buffer, SIZE);
1529 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001530 }
1531 }
1532 write(fd, result.string(), result.size());
1533 return NO_ERROR;
1534}
1535
Mathias Agopian65ab4712010-07-14 17:59:35 -07001536status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1537{
1538 const size_t SIZE = 256;
1539 char buffer[SIZE];
1540 String8 result;
1541
1542 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1543 result.append(buffer);
1544 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1545 result.append(buffer);
1546 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1547 result.append(buffer);
1548 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1549 result.append(buffer);
1550 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1551 result.append(buffer);
1552 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1553 result.append(buffer);
1554 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1555 result.append(buffer);
1556 write(fd, result.string(), result.size());
1557
1558 dumpBase(fd, args);
1559
1560 return NO_ERROR;
1561}
1562
1563// Thread virtuals
1564status_t AudioFlinger::PlaybackThread::readyToRun()
1565{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001566 status_t status = initCheck();
1567 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001568 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001569 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001570 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001571 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001572 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001573}
1574
1575void AudioFlinger::PlaybackThread::onFirstRef()
1576{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001577 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001578}
1579
1580// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1581sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1582 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001583 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001584 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001585 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001586 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001587 int frameCount,
1588 const sp<IMemory>& sharedBuffer,
1589 int sessionId,
John Grossman4ff14ba2012-02-08 16:37:41 -08001590 bool isTimed,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001591 status_t *status)
1592{
1593 sp<Track> track;
1594 status_t lStatus;
1595
1596 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001597 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1598 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001599 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001600 "for output %p with format %d",
1601 sampleRate, format, channelMask, mOutput, mFormat);
1602 lStatus = BAD_VALUE;
1603 goto Exit;
1604 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001605 }
1606 } else {
1607 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1608 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001609 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610 lStatus = BAD_VALUE;
1611 goto Exit;
1612 }
1613 }
1614
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001615 lStatus = initCheck();
1616 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001617 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001618 goto Exit;
1619 }
1620
1621 { // scope for mLock
1622 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001623
1624 // all tracks in same audio session must share the same routing strategy otherwise
1625 // conflicts will happen when tracks are moved from one output to another by audio policy
1626 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001627 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001628 for (size_t i = 0; i < mTracks.size(); ++i) {
1629 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001630 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001631 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001632 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001633 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001634 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001635 lStatus = BAD_VALUE;
1636 goto Exit;
1637 }
1638 }
1639 }
1640
John Grossman4ff14ba2012-02-08 16:37:41 -08001641 if (!isTimed) {
1642 track = new Track(this, client, streamType, sampleRate, format,
1643 channelMask, frameCount, sharedBuffer, sessionId);
1644 } else {
1645 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1646 channelMask, frameCount, sharedBuffer, sessionId);
1647 }
1648 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001649 lStatus = NO_MEMORY;
1650 goto Exit;
1651 }
1652 mTracks.add(track);
1653
1654 sp<EffectChain> chain = getEffectChain_l(sessionId);
1655 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001656 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001657 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001658 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001659 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001660 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001661
1662 // invalidate track immediately if the stream type was moved to another thread since
1663 // createTrack() was called by the client process.
1664 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001665 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001666 this, streamType);
Eric Laurent9f6530f2011-08-30 10:18:54 -07001667 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1668 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001669 }
1670 lStatus = NO_ERROR;
1671
1672Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001673 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001674 *status = lStatus;
1675 }
1676 return track;
1677}
1678
1679uint32_t AudioFlinger::PlaybackThread::latency() const
1680{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001681 Mutex::Autolock _l(mLock);
1682 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001683 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001684 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685 return 0;
1686 }
1687}
1688
Glenn Kasten6637baa2012-01-09 09:40:36 -08001689void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001690{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001691 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001692 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001693}
1694
Glenn Kasten6637baa2012-01-09 09:40:36 -08001695void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001696{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001697 Mutex::Autolock _l(mLock);
1698 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001699}
1700
Glenn Kasten6637baa2012-01-09 09:40:36 -08001701void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001702{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001703 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001704 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001705}
1706
Glenn Kasten6637baa2012-01-09 09:40:36 -08001707void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001708{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001709 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001710 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001711}
1712
Glenn Kastenfff6d712012-01-12 16:38:12 -08001713float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001714{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001715 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001716 return mStreamTypes[stream].volume;
1717}
1718
Mathias Agopian65ab4712010-07-14 17:59:35 -07001719// addTrack_l() must be called with ThreadBase::mLock held
1720status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1721{
1722 status_t status = ALREADY_EXISTS;
1723
1724 // set retry count for buffer fill
1725 track->mRetryCount = kMaxTrackStartupRetries;
1726 if (mActiveTracks.indexOf(track) < 0) {
1727 // the track is newly added, make sure it fills up all its
1728 // buffers before playing. This is to ensure the client will
1729 // effectively get the latency it requested.
1730 track->mFillingUpStatus = Track::FS_FILLING;
1731 track->mResetDone = false;
1732 mActiveTracks.add(track);
1733 if (track->mainBuffer() != mMixBuffer) {
1734 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1735 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001736 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001737 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001738 }
1739 }
1740
1741 status = NO_ERROR;
1742 }
1743
Steve Block3856b092011-10-20 11:56:00 +01001744 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001745 mWaitWorkCV.broadcast();
1746
1747 return status;
1748}
1749
1750// destroyTrack_l() must be called with ThreadBase::mLock held
1751void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1752{
1753 track->mState = TrackBase::TERMINATED;
1754 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001755 removeTrack_l(track);
1756 }
1757}
1758
1759void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1760{
1761 mTracks.remove(track);
1762 deleteTrackName_l(track->name());
1763 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1764 if (chain != 0) {
1765 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001766 }
1767}
1768
1769String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1770{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001771 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001772 char *s;
1773
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001774 Mutex::Autolock _l(mLock);
1775 if (initCheck() != NO_ERROR) {
1776 return out_s8;
1777 }
1778
Dima Zavin799a70e2011-04-18 16:57:27 -07001779 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001780 out_s8 = String8(s);
1781 free(s);
1782 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001783}
1784
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001785// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001786void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1787 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001788 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001789
Steve Block3856b092011-10-20 11:56:00 +01001790 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001791
1792 switch (event) {
1793 case AudioSystem::OUTPUT_OPENED:
1794 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001795 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001796 desc.samplingRate = mSampleRate;
1797 desc.format = mFormat;
1798 desc.frameCount = mFrameCount;
1799 desc.latency = latency();
1800 param2 = &desc;
1801 break;
1802
1803 case AudioSystem::STREAM_CONFIG_CHANGED:
1804 param2 = &param;
1805 case AudioSystem::OUTPUT_CLOSED:
1806 default:
1807 break;
1808 }
1809 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1810}
1811
1812void AudioFlinger::PlaybackThread::readOutputParameters()
1813{
Dima Zavin799a70e2011-04-18 16:57:27 -07001814 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001815 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1816 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001817 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001818 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001819 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001820
1821 // FIXME - Current mixer implementation only supports stereo output: Always
1822 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001823 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001824 mMixBuffer = new int16_t[mFrameCount * 2];
1825 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1826
Eric Laurentde070132010-07-13 04:45:46 -07001827 // force reconfiguration of effect chains and engines to take new buffer size and audio
1828 // parameters into account
1829 // Note that mLock is not held when readOutputParameters() is called from the constructor
1830 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1831 // matter.
1832 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1833 Vector< sp<EffectChain> > effectChains = mEffectChains;
1834 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001835 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001836 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001837}
1838
1839status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1840{
Glenn Kastena0d68332012-01-27 16:47:15 -08001841 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001842 return BAD_VALUE;
1843 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001844 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001845 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001846 return INVALID_OPERATION;
1847 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001848 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001849
Dima Zavin799a70e2011-04-18 16:57:27 -07001850 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001851}
1852
Eric Laurent39e94f82010-07-28 01:32:47 -07001853uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001854{
1855 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001856 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001857 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001858 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001859 }
1860
1861 for (size_t i = 0; i < mTracks.size(); ++i) {
1862 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001863 if (sessionId == track->sessionId() &&
1864 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001865 result |= TRACK_SESSION;
1866 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001867 }
1868 }
1869
Eric Laurent39e94f82010-07-28 01:32:47 -07001870 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001871}
1872
Eric Laurentde070132010-07-13 04:45:46 -07001873uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1874{
Dima Zavinfce7a472011-04-19 22:30:36 -07001875 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001876 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001877 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1878 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001879 }
1880 for (size_t i = 0; i < mTracks.size(); i++) {
1881 sp<Track> track = mTracks[i];
1882 if (sessionId == track->sessionId() &&
1883 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001884 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07001885 }
1886 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001887 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001888}
1889
Mathias Agopian65ab4712010-07-14 17:59:35 -07001890
Glenn Kastenaed850d2012-01-26 09:46:34 -08001891AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001892{
1893 Mutex::Autolock _l(mLock);
1894 return mOutput;
1895}
1896
1897AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1898{
1899 Mutex::Autolock _l(mLock);
1900 AudioStreamOut *output = mOutput;
1901 mOutput = NULL;
1902 return output;
1903}
1904
1905// this method must always be called either with ThreadBase mLock held or inside the thread loop
1906audio_stream_t* AudioFlinger::PlaybackThread::stream()
1907{
1908 if (mOutput == NULL) {
1909 return NULL;
1910 }
1911 return &mOutput->stream->common;
1912}
1913
Eric Laurent162b40b2011-12-05 09:47:19 -08001914uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1915{
1916 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1917 // decoding and transfer time. So sleeping for half of the latency would likely cause
1918 // underruns
1919 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1920 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1921 } else {
1922 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1923 }
1924}
1925
Mathias Agopian65ab4712010-07-14 17:59:35 -07001926// ----------------------------------------------------------------------------
1927
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001928AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001929 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten000f0e32012-03-01 17:10:56 -08001930 : PlaybackThread(audioFlinger, output, id, device, type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001931{
Glenn Kasten000f0e32012-03-01 17:10:56 -08001932 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001933 // FIXME - Current mixer implementation only supports stereo output
1934 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001935 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001936 }
1937}
1938
1939AudioFlinger::MixerThread::~MixerThread()
1940{
1941 delete mAudioMixer;
1942}
1943
Glenn Kasten83efdd02012-02-24 07:21:32 -08001944class CpuStats {
1945public:
1946 void sample();
1947#ifdef DEBUG_CPU_USAGE
1948private:
1949 ThreadCpuUsage mCpu;
1950#endif
1951};
1952
1953void CpuStats::sample() {
1954#ifdef DEBUG_CPU_USAGE
1955 const CentralTendencyStatistics& stats = mCpu.statistics();
1956 mCpu.sampleAndEnable();
1957 unsigned n = stats.n();
1958 // mCpu.elapsed() is expensive, so don't call it every loop
1959 if ((n & 127) == 1) {
1960 long long elapsed = mCpu.elapsed();
1961 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1962 double perLoop = elapsed / (double) n;
1963 double perLoop100 = perLoop * 0.01;
1964 double mean = stats.mean();
1965 double stddev = stats.stddev();
1966 double minimum = stats.minimum();
1967 double maximum = stats.maximum();
1968 mCpu.resetStatistics();
1969 ALOGI("CPU usage over past %.1f secs (%u mixer loops at %.1f mean ms per loop):\n us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f",
1970 elapsed * .000000001, n, perLoop * .000001,
1971 mean * .001,
1972 stddev * .001,
1973 minimum * .001,
1974 maximum * .001,
1975 mean / perLoop100,
1976 stddev / perLoop100,
1977 minimum / perLoop100,
1978 maximum / perLoop100);
1979 }
1980 }
1981#endif
1982};
1983
Glenn Kasten37d825e2012-02-24 07:21:48 -08001984void AudioFlinger::PlaybackThread::checkSilentMode_l()
1985{
1986 if (!mMasterMute) {
1987 char value[PROPERTY_VALUE_MAX];
1988 if (property_get("ro.audio.silent", value, "0") > 0) {
1989 char *endptr;
1990 unsigned long ul = strtoul(value, &endptr, 0);
1991 if (*endptr == '\0' && ul != 0) {
1992 ALOGD("Silence is golden");
1993 // The setprop command will not allow a property to be changed after
1994 // the first time it is set, so we don't have to worry about un-muting.
1995 setMasterMute_l(true);
1996 }
1997 }
1998 }
1999}
2000
Glenn Kasten000f0e32012-03-01 17:10:56 -08002001bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002002{
2003 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002004
Glenn Kasten000f0e32012-03-01 17:10:56 -08002005 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002006
2007 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002008 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002009if (mType == MIXER) {
2010 longStandbyExit = false;
2011}
Glenn Kasten688a6402012-02-29 07:57:06 -08002012
Glenn Kasten000f0e32012-03-01 17:10:56 -08002013 // DUPLICATING
2014 // FIXME could this be made local to while loop?
2015 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002016
Glenn Kasten66fcab92012-02-24 14:59:21 -08002017 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002018 sleepTime = idleSleepTime;
2019
2020if (mType == MIXER) {
2021 sleepTimeShift = 0;
2022}
2023
2024 // MIXER
Glenn Kasten83efdd02012-02-24 07:21:32 -08002025 CpuStats cpuStats;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002026
Eric Laurentfeb0db62011-07-22 09:04:31 -07002027 acquireWakeLock();
2028
Mathias Agopian65ab4712010-07-14 17:59:35 -07002029 while (!exitPending())
2030 {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002031if (mType == MIXER) {
Glenn Kasten83efdd02012-02-24 07:21:32 -08002032 cpuStats.sample();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002033}
Glenn Kasten688a6402012-02-29 07:57:06 -08002034
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002035 Vector< sp<EffectChain> > effectChains;
2036
Mathias Agopian65ab4712010-07-14 17:59:35 -07002037 processConfigEvents();
2038
Mathias Agopian65ab4712010-07-14 17:59:35 -07002039 { // scope for mLock
2040
2041 Mutex::Autolock _l(mLock);
2042
2043 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002044 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002045 }
2046
Glenn Kastenfa26a852012-03-06 11:28:04 -08002047 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002048
Mathias Agopian65ab4712010-07-14 17:59:35 -07002049 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002050 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002051 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002052 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002053
2054 threadLoop_standby();
2055
Mathias Agopian65ab4712010-07-14 17:59:35 -07002056 mStandby = true;
2057 mBytesWritten = 0;
2058 }
2059
Glenn Kasten3e074702012-02-28 18:40:35 -08002060 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002061 // we're about to wait, flush the binder command buffer
2062 IPCThreadState::self()->flushCommands();
2063
Glenn Kastenfa26a852012-03-06 11:28:04 -08002064 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002065
Mathias Agopian65ab4712010-07-14 17:59:35 -07002066 if (exitPending()) break;
2067
Eric Laurentfeb0db62011-07-22 09:04:31 -07002068 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002069 // wait until we have something to do...
Glenn Kastenc0b52832012-02-24 11:18:09 -08002070 ALOGV("Thread %p type %d TID %d going to sleep", this, mType, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002071 mWaitWorkCV.wait(mLock);
Glenn Kastenc0b52832012-02-24 11:18:09 -08002072 ALOGV("Thread %p type %d TID %d waking up", this, mType, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002073 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002074
Eric Laurent27741442012-01-17 19:20:12 -08002075 mPrevMixerStatus = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002076
Glenn Kasten37d825e2012-02-24 07:21:48 -08002077 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002078
Glenn Kasten000f0e32012-03-01 17:10:56 -08002079 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002080 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002081 if (mType == MIXER) {
2082 sleepTimeShift = 0;
2083 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002084
Mathias Agopian65ab4712010-07-14 17:59:35 -07002085 continue;
2086 }
2087 }
2088
Glenn Kastenfec279f2012-03-08 07:47:15 -08002089 mixer_state newMixerStatus = prepareTracks_l(&tracksToRemove);
2090 // Shift in the new status; this could be a queue if it's
2091 // useful to filter the mixer status over several cycles.
2092 mPrevMixerStatus = mMixerStatus;
2093 mMixerStatus = newMixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002094
2095 // prevent any changes in effect chain list and in each effect chain
2096 // during mixing and effect process as the audio buffers could be deleted
2097 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002098 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002099 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002100
Glenn Kastenfec279f2012-03-08 07:47:15 -08002101 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002102 threadLoop_mix();
2103 } else {
2104 threadLoop_sleepTime();
2105 }
2106
2107 if (mSuspended > 0) {
2108 sleepTime = suspendSleepTimeUs();
2109 }
2110
2111 // only process effects if we're going to write
2112 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002113 for (size_t i = 0; i < effectChains.size(); i ++) {
2114 effectChains[i]->process_l();
2115 }
2116 }
2117
2118 // enable changes in effect chain
2119 unlockEffectChains(effectChains);
2120
2121 // sleepTime == 0 means we must write to audio hardware
2122 if (sleepTime == 0) {
2123
2124 threadLoop_write();
2125
2126if (mType == MIXER) {
2127 // write blocked detection
2128 nsecs_t now = systemTime();
2129 nsecs_t delta = now - mLastWriteTime;
2130 if (!mStandby && delta > maxPeriod) {
2131 mNumDelayedWrites++;
2132 if ((now - lastWarning) > kWarningThrottleNs) {
2133 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2134 ns2ms(delta), mNumDelayedWrites, this);
2135 lastWarning = now;
2136 }
2137 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2138 // a different threshold. Or completely removed for what it is worth anyway...
2139 if (mStandby) {
2140 longStandbyExit = true;
2141 }
2142 }
2143}
2144
2145 mStandby = false;
2146 } else {
2147 usleep(sleepTime);
2148 }
2149
2150 // finally let go of removed track(s), without the lock held
2151 // since we can't guarantee the destructors won't acquire that
2152 // same lock.
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002153 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002154
Glenn Kastenfa26a852012-03-06 11:28:04 -08002155 // FIXME I don't understand the need for this here;
2156 // it was in the original code but maybe the
2157 // assignment in saveOutputTracks() makes this unnecessary?
2158 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002159
2160 // Effect chains will be actually deleted here if they were removed from
2161 // mEffectChains list during mixing or effects processing
2162 effectChains.clear();
2163
2164 // FIXME Note that the above .clear() is no longer necessary since effectChains
2165 // is now local to this block, but will keep it for now (at least until merge done).
2166 }
2167
2168if (mType == MIXER || mType == DIRECT) {
2169 // put output stream into standby mode
2170 if (!mStandby) {
2171 mOutput->stream->common.standby(&mOutput->stream->common);
2172 }
2173}
2174if (mType == DUPLICATING) {
2175 // for DuplicatingThread, standby mode is handled by the outputTracks
2176}
2177
2178 releaseWakeLock();
2179
2180 ALOGV("Thread %p type %d exiting", this, mType);
2181 return false;
2182}
2183
2184// shared by MIXER and DIRECT, overridden by DUPLICATING
2185void AudioFlinger::PlaybackThread::threadLoop_write()
2186{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002187 // FIXME rewrite to reduce number of system calls
2188 mLastWriteTime = systemTime();
2189 mInWrite = true;
2190 mBytesWritten += mixBufferSize;
2191 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2192 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2193 mNumWrites++;
2194 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002195}
2196
2197// shared by MIXER and DIRECT, overridden by DUPLICATING
2198void AudioFlinger::PlaybackThread::threadLoop_standby()
2199{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002200 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2201 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002202}
2203
2204void AudioFlinger::MixerThread::threadLoop_mix()
2205{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002206 // obtain the presentation timestamp of the next output buffer
2207 int64_t pts;
2208 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002209
Glenn Kasten952eeb22012-03-06 11:30:57 -08002210 if (NULL != mOutput->stream->get_next_write_timestamp) {
2211 status = mOutput->stream->get_next_write_timestamp(
2212 mOutput->stream, &pts);
2213 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002214
Glenn Kasten952eeb22012-03-06 11:30:57 -08002215 if (status != NO_ERROR) {
2216 pts = AudioBufferProvider::kInvalidPTS;
2217 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002218
Glenn Kasten952eeb22012-03-06 11:30:57 -08002219 // mix buffers...
2220 mAudioMixer->process(pts);
2221 // increase sleep time progressively when application underrun condition clears.
2222 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2223 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2224 // such that we would underrun the audio HAL.
2225 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2226 sleepTimeShift--;
2227 }
2228 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002229 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002230 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002231}
2232
2233void AudioFlinger::MixerThread::threadLoop_sleepTime()
2234{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002235 // If no tracks are ready, sleep once for the duration of an output
2236 // buffer size, then write 0s to the output
2237 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002238 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002239 sleepTime = activeSleepTime >> sleepTimeShift;
2240 if (sleepTime < kMinThreadSleepTimeUs) {
2241 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002242 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002243 // reduce sleep time in case of consecutive application underruns to avoid
2244 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2245 // duration we would end up writing less data than needed by the audio HAL if
2246 // the condition persists.
2247 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2248 sleepTimeShift++;
2249 }
2250 } else {
2251 sleepTime = idleSleepTime;
2252 }
2253 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002254 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002255 memset (mMixBuffer, 0, mixBufferSize);
2256 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002257 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002258 }
2259 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002260}
2261
2262// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002263AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002264 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002265{
2266
Glenn Kasten29c23c32012-01-26 13:37:52 -08002267 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002268 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002269 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002270 size_t mixedTracks = 0;
2271 size_t tracksWithEffect = 0;
2272
2273 float masterVolume = mMasterVolume;
2274 bool masterMute = mMasterMute;
2275
Eric Laurent571d49c2010-08-11 05:20:11 -07002276 if (masterMute) {
2277 masterVolume = 0;
2278 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002279 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002280 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002281 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002282 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002283 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002284 masterVolume = (float)((v + (1 << 23)) >> 24);
2285 chain.clear();
2286 }
2287
2288 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002289 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002290 if (t == 0) continue;
2291
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002292 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002293 Track* const track = t.get();
2294 audio_track_cblk_t* cblk = track->cblk();
2295
2296 // The first time a track is added we wait
2297 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002298 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002299 // make sure that we have enough frames to mix one full buffer.
2300 // enforce this condition only once to enable draining the buffer in case the client
2301 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002302 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002303 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002304 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002305 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002306 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002307 if (t->sampleRate() == (int)mSampleRate) {
2308 minFrames = mFrameCount;
2309 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002310 // +1 for rounding and +1 for additional sample needed for interpolation
2311 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2312 // add frames already consumed but not yet released by the resampler
2313 // because cblk->framesReady() will include these frames
2314 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2315 // the minimum track buffer size is normally twice the number of frames necessary
2316 // to fill one buffer and the resampler should not leave more than one buffer worth
2317 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002318 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002319 }
2320 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002321 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002322 !track->isPaused() && !track->isTerminated())
2323 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002324 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002325
2326 mixedTracks++;
2327
2328 // track->mainBuffer() != mMixBuffer means there is an effect chain
2329 // connected to the track
2330 chain.clear();
2331 if (track->mainBuffer() != mMixBuffer) {
2332 chain = getEffectChain_l(track->sessionId());
2333 // Delegate volume control to effect in track effect chain if needed
2334 if (chain != 0) {
2335 tracksWithEffect++;
2336 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002337 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002338 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002339 }
2340 }
2341
2342
2343 int param = AudioMixer::VOLUME;
2344 if (track->mFillingUpStatus == Track::FS_FILLED) {
2345 // no ramp for the first volume setting
2346 track->mFillingUpStatus = Track::FS_ACTIVE;
2347 if (track->mState == TrackBase::RESUMING) {
2348 track->mState = TrackBase::ACTIVE;
2349 param = AudioMixer::RAMP_VOLUME;
2350 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002351 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002352 } else if (cblk->server != 0) {
2353 // If the track is stopped before the first frame was mixed,
2354 // do not apply ramp
2355 param = AudioMixer::RAMP_VOLUME;
2356 }
2357
2358 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002359 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002360 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002361 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002362 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002363 if (track->isPausing()) {
2364 track->setPaused();
2365 }
2366 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002367
Mathias Agopian65ab4712010-07-14 17:59:35 -07002368 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002369 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002370 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002371 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002372 vl = vlr & 0xFFFF;
2373 vr = vlr >> 16;
2374 // track volumes come from shared memory, so can't be trusted and must be clamped
2375 if (vl > MAX_GAIN_INT) {
2376 ALOGV("Track left volume out of range: %04X", vl);
2377 vl = MAX_GAIN_INT;
2378 }
2379 if (vr > MAX_GAIN_INT) {
2380 ALOGV("Track right volume out of range: %04X", vr);
2381 vr = MAX_GAIN_INT;
2382 }
2383 // now apply the master volume and stream type volume
2384 vl = (uint32_t)(v * vl) << 12;
2385 vr = (uint32_t)(v * vr) << 12;
2386 // assuming master volume and stream type volume each go up to 1.0,
2387 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002388
Glenn Kasten05632a52012-01-03 14:22:33 -08002389 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2390 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002391 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002392 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002393 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002394 }
2395 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002396 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002397 // Delegate volume control to effect in track effect chain if needed
2398 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2399 // Do not ramp volume if volume is controlled by effect
2400 param = AudioMixer::VOLUME;
2401 track->mHasVolumeController = true;
2402 } else {
2403 // force no volume ramp when volume controller was just disabled or removed
2404 // from effect chain to avoid volume spike
2405 if (track->mHasVolumeController) {
2406 param = AudioMixer::VOLUME;
2407 }
2408 track->mHasVolumeController = false;
2409 }
2410
2411 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002412 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002413 vl = (vl + (1 << 11)) >> 12;
2414 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2415 vr = (vr + (1 << 11)) >> 12;
2416 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002417
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002418 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 -07002419
Mathias Agopian65ab4712010-07-14 17:59:35 -07002420 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002421 mAudioMixer->setBufferProvider(name, track);
2422 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002423
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002424 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2425 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2426 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002427 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002428 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002429 AudioMixer::TRACK,
2430 AudioMixer::FORMAT, (void *)track->format());
2431 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002432 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002433 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002434 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002435 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002436 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002437 AudioMixer::RESAMPLE,
2438 AudioMixer::SAMPLE_RATE,
2439 (void *)(cblk->sampleRate));
2440 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002441 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002442 AudioMixer::TRACK,
2443 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2444 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002445 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002446 AudioMixer::TRACK,
2447 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2448
2449 // reset retry count
2450 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002451 // If one track is ready, set the mixer ready if:
2452 // - the mixer was not ready during previous round OR
2453 // - no other track is not ready
2454 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2455 mixerStatus != MIXER_TRACKS_ENABLED) {
2456 mixerStatus = MIXER_TRACKS_READY;
2457 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002458 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002459 //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 -07002460 if (track->isStopped()) {
2461 track->reset();
2462 }
2463 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2464 // We have consumed all the buffers of this track.
2465 // Remove it from the list of active tracks.
2466 tracksToRemove->add(track);
2467 } else {
2468 // No buffers for this track. Give it a few chances to
2469 // fill a buffer, then remove it from active list.
2470 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002471 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002472 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002473 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002474 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002475 // If one track is not ready, mark the mixer also not ready if:
2476 // - the mixer was ready during previous round OR
2477 // - no other track is ready
2478 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2479 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002480 mixerStatus = MIXER_TRACKS_ENABLED;
2481 }
2482 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002483 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002484 }
2485 }
2486
2487 // remove all the tracks that need to be...
2488 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002489 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002490 for (size_t i=0 ; i<count ; i++) {
2491 const sp<Track>& track = tracksToRemove->itemAt(i);
2492 mActiveTracks.remove(track);
2493 if (track->mainBuffer() != mMixBuffer) {
2494 chain = getEffectChain_l(track->sessionId());
2495 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002496 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002497 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002498 }
2499 }
2500 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002501 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002502 }
2503 }
2504 }
2505
2506 // mix buffer must be cleared if all tracks are connected to an
2507 // effect chain as in this case the mixer will not write to
2508 // mix buffer and track effects will accumulate into it
2509 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2510 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2511 }
2512
2513 return mixerStatus;
2514}
2515
Glenn Kasten66fcab92012-02-24 14:59:21 -08002516/*
2517The derived values that are cached:
2518 - mixBufferSize from frame count * frame size
2519 - activeSleepTime from activeSleepTimeUs()
2520 - idleSleepTime from idleSleepTimeUs()
2521 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2522 - maxPeriod from frame count and sample rate (MIXER only)
2523
2524The parameters that affect these derived values are:
2525 - frame count
2526 - frame size
2527 - sample rate
2528 - device type: A2DP or not
2529 - device latency
2530 - format: PCM or not
2531 - active sleep time
2532 - idle sleep time
2533*/
2534
2535void AudioFlinger::PlaybackThread::cacheParameters_l()
2536{
2537 mixBufferSize = mFrameCount * mFrameSize;
2538 activeSleepTime = activeSleepTimeUs();
2539 idleSleepTime = idleSleepTimeUs();
2540}
2541
Glenn Kastenfff6d712012-01-12 16:38:12 -08002542void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002543{
Steve Block3856b092011-10-20 11:56:00 +01002544 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002545 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002546 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002547
Mathias Agopian65ab4712010-07-14 17:59:35 -07002548 size_t size = mTracks.size();
2549 for (size_t i = 0; i < size; i++) {
2550 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08002551 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002552 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002553 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002554 }
2555 }
2556}
2557
Glenn Kastenfff6d712012-01-12 16:38:12 -08002558void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002559{
Steve Block3856b092011-10-20 11:56:00 +01002560 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002561 this, streamType, valid);
2562 Mutex::Autolock _l(mLock);
2563
2564 mStreamTypes[streamType].valid = valid;
2565}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002566
2567// getTrackName_l() must be called with ThreadBase::mLock held
2568int AudioFlinger::MixerThread::getTrackName_l()
2569{
2570 return mAudioMixer->getTrackName();
2571}
2572
2573// deleteTrackName_l() must be called with ThreadBase::mLock held
2574void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2575{
Steve Block3856b092011-10-20 11:56:00 +01002576 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002577 mAudioMixer->deleteTrackName(name);
2578}
2579
2580// checkForNewParameters_l() must be called with ThreadBase::mLock held
2581bool AudioFlinger::MixerThread::checkForNewParameters_l()
2582{
2583 bool reconfig = false;
2584
2585 while (!mNewParameters.isEmpty()) {
2586 status_t status = NO_ERROR;
2587 String8 keyValuePair = mNewParameters[0];
2588 AudioParameter param = AudioParameter(keyValuePair);
2589 int value;
2590
2591 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2592 reconfig = true;
2593 }
2594 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002595 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002596 status = BAD_VALUE;
2597 } else {
2598 reconfig = true;
2599 }
2600 }
2601 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002602 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002603 status = BAD_VALUE;
2604 } else {
2605 reconfig = true;
2606 }
2607 }
2608 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2609 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002610 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002611 // if frame count is changed after track creation
2612 if (!mTracks.isEmpty()) {
2613 status = INVALID_OPERATION;
2614 } else {
2615 reconfig = true;
2616 }
2617 }
2618 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002619 // when changing the audio output device, call addBatteryData to notify
2620 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002621 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002622 uint32_t params = 0;
2623 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002624 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002625 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2626 }
2627
2628 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002629 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002630 // check if any other device (except speaker) is on
2631 if (value & deviceWithoutSpeaker ) {
2632 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2633 }
2634
2635 if (params != 0) {
2636 addBatteryData(params);
2637 }
2638 }
2639
Mathias Agopian65ab4712010-07-14 17:59:35 -07002640 // forward device change to effects that have requested to be
2641 // aware of attached audio device.
2642 mDevice = (uint32_t)value;
2643 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002644 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002645 }
2646 }
2647
2648 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002649 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002650 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002651 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002652 mOutput->stream->common.standby(&mOutput->stream->common);
2653 mStandby = true;
2654 mBytesWritten = 0;
2655 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002656 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002657 }
2658 if (status == NO_ERROR && reconfig) {
2659 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002660 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2661 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002662 readOutputParameters();
2663 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2664 for (size_t i = 0; i < mTracks.size() ; i++) {
2665 int name = getTrackName_l();
2666 if (name < 0) break;
2667 mTracks[i]->mName = name;
2668 // limit track sample rate to 2 x new output sample rate
2669 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2670 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2671 }
2672 }
2673 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2674 }
2675 }
2676
2677 mNewParameters.removeAt(0);
2678
2679 mParamStatus = status;
2680 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002681 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2682 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002683 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002684 }
2685 return reconfig;
2686}
2687
2688status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2689{
2690 const size_t SIZE = 256;
2691 char buffer[SIZE];
2692 String8 result;
2693
2694 PlaybackThread::dumpInternals(fd, args);
2695
2696 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2697 result.append(buffer);
2698 write(fd, result.string(), result.size());
2699 return NO_ERROR;
2700}
2701
Mathias Agopian65ab4712010-07-14 17:59:35 -07002702uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2703{
Eric Laurent60e18242010-07-29 06:50:24 -07002704 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002705}
2706
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002707uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2708{
2709 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2710}
2711
Glenn Kasten66fcab92012-02-24 14:59:21 -08002712void AudioFlinger::MixerThread::cacheParameters_l()
2713{
2714 PlaybackThread::cacheParameters_l();
2715
2716 // FIXME: Relaxed timing because of a certain device that can't meet latency
2717 // Should be reduced to 2x after the vendor fixes the driver issue
2718 // increase threshold again due to low power audio mode. The way this warning
2719 // threshold is calculated and its usefulness should be reconsidered anyway.
2720 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
2721}
2722
Mathias Agopian65ab4712010-07-14 17:59:35 -07002723// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002724AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2725 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002726 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002727 // mLeftVolFloat, mRightVolFloat
2728 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002729{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002730}
2731
2732AudioFlinger::DirectOutputThread::~DirectOutputThread()
2733{
2734}
2735
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002736AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
2737 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08002738)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002739{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002740 sp<Track> trackToRemove;
2741
Glenn Kastenfec279f2012-03-08 07:47:15 -08002742 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002743
Glenn Kasten952eeb22012-03-06 11:30:57 -08002744 // find out which tracks need to be processed
2745 if (mActiveTracks.size() != 0) {
2746 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08002747 // The track died recently
2748 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002749
Glenn Kasten952eeb22012-03-06 11:30:57 -08002750 Track* const track = t.get();
2751 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002752
Glenn Kasten952eeb22012-03-06 11:30:57 -08002753 // The first time a track is added we wait
2754 // for all its buffers to be filled before processing it
2755 if (cblk->framesReady() && track->isReady() &&
2756 !track->isPaused() && !track->isTerminated())
2757 {
2758 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002759
Glenn Kasten952eeb22012-03-06 11:30:57 -08002760 if (track->mFillingUpStatus == Track::FS_FILLED) {
2761 track->mFillingUpStatus = Track::FS_ACTIVE;
2762 mLeftVolFloat = mRightVolFloat = 0;
2763 mLeftVolShort = mRightVolShort = 0;
2764 if (track->mState == TrackBase::RESUMING) {
2765 track->mState = TrackBase::ACTIVE;
2766 rampVolume = true;
2767 }
2768 } else if (cblk->server != 0) {
2769 // If the track is stopped before the first frame was mixed,
2770 // do not apply ramp
2771 rampVolume = true;
2772 }
2773 // compute volume for this track
2774 float left, right;
2775 if (track->isMuted() || mMasterMute || track->isPausing() ||
2776 mStreamTypes[track->streamType()].mute) {
2777 left = right = 0;
2778 if (track->isPausing()) {
2779 track->setPaused();
2780 }
2781 } else {
2782 float typeVolume = mStreamTypes[track->streamType()].volume;
2783 float v = mMasterVolume * typeVolume;
2784 uint32_t vlr = cblk->getVolumeLR();
2785 float v_clamped = v * (vlr & 0xFFFF);
2786 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2787 left = v_clamped/MAX_GAIN;
2788 v_clamped = v * (vlr >> 16);
2789 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2790 right = v_clamped/MAX_GAIN;
2791 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002792
Glenn Kasten952eeb22012-03-06 11:30:57 -08002793 if (left != mLeftVolFloat || right != mRightVolFloat) {
2794 mLeftVolFloat = left;
2795 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002796
Glenn Kasten952eeb22012-03-06 11:30:57 -08002797 // If audio HAL implements volume control,
2798 // force software volume to nominal value
2799 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
2800 left = 1.0f;
2801 right = 1.0f;
2802 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002803
Glenn Kasten952eeb22012-03-06 11:30:57 -08002804 // Convert volumes from float to 8.24
2805 uint32_t vl = (uint32_t)(left * (1 << 24));
2806 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002807
Glenn Kasten952eeb22012-03-06 11:30:57 -08002808 // Delegate volume control to effect in track effect chain if needed
2809 // only one effect chain can be present on DirectOutputThread, so if
2810 // there is one, the track is connected to it
2811 if (!mEffectChains.isEmpty()) {
2812 // Do not ramp volume if volume is controlled by effect
2813 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002814 rampVolume = false;
2815 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002816 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002817
Glenn Kasten952eeb22012-03-06 11:30:57 -08002818 // Convert volumes from 8.24 to 4.12 format
2819 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2820 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2821 leftVol = (uint16_t)v_clamped;
2822 v_clamped = (vr + (1 << 11)) >> 12;
2823 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2824 rightVol = (uint16_t)v_clamped;
2825 } else {
2826 leftVol = mLeftVolShort;
2827 rightVol = mRightVolShort;
2828 rampVolume = false;
2829 }
2830
2831 // reset retry count
2832 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002833 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002834 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002835 } else {
2836 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2837 if (track->isStopped()) {
2838 track->reset();
2839 }
2840 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2841 // We have consumed all the buffers of this track.
2842 // Remove it from the list of active tracks.
2843 trackToRemove = track;
2844 } else {
2845 // No buffers for this track. Give it a few chances to
2846 // fill a buffer, then remove it from active list.
2847 if (--(track->mRetryCount) <= 0) {
2848 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2849 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002850 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002851 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002852 }
2853 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002854 }
2855 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002856
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002857 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08002858 // remove all the tracks that need to be...
2859 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002860 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002861 mActiveTracks.remove(trackToRemove);
2862 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002863 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08002864 trackToRemove->sessionId());
2865 mEffectChains[0]->decActiveTrackCnt();
2866 }
2867 if (trackToRemove->isTerminated()) {
2868 removeTrack_l(trackToRemove);
2869 }
2870 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002871
Glenn Kastenfec279f2012-03-08 07:47:15 -08002872 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002873}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002874
Glenn Kasten000f0e32012-03-01 17:10:56 -08002875void AudioFlinger::DirectOutputThread::threadLoop_mix()
2876{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002877 AudioBufferProvider::Buffer buffer;
2878 size_t frameCount = mFrameCount;
2879 int8_t *curBuf = (int8_t *)mMixBuffer;
2880 // output audio to hardware
2881 while (frameCount) {
2882 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002883 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002884 if (CC_UNLIKELY(buffer.raw == NULL)) {
2885 memset(curBuf, 0, frameCount * mFrameSize);
2886 break;
2887 }
2888 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2889 frameCount -= buffer.frameCount;
2890 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002891 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002892 }
2893 sleepTime = 0;
2894 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002895 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08002896
2897 // apply volume
2898
2899 // Do not apply volume on compressed audio
2900 if (!audio_is_linear_pcm(mFormat)) {
2901 return;
2902 }
2903
2904 // convert to signed 16 bit before volume calculation
2905 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
2906 size_t count = mFrameCount * mChannelCount;
2907 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2908 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002909 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08002910 *dst-- = (int16_t)(*src--^0x80) << 8;
2911 }
2912 }
2913
2914 frameCount = mFrameCount;
2915 int16_t *out = mMixBuffer;
2916 if (rampVolume) {
2917 if (mChannelCount == 1) {
2918 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2919 int32_t vlInc = d / (int32_t)frameCount;
2920 int32_t vl = ((int32_t)mLeftVolShort << 16);
2921 do {
2922 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2923 out++;
2924 vl += vlInc;
2925 } while (--frameCount);
2926
2927 } else {
2928 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2929 int32_t vlInc = d / (int32_t)frameCount;
2930 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2931 int32_t vrInc = d / (int32_t)frameCount;
2932 int32_t vl = ((int32_t)mLeftVolShort << 16);
2933 int32_t vr = ((int32_t)mRightVolShort << 16);
2934 do {
2935 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2936 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2937 out += 2;
2938 vl += vlInc;
2939 vr += vrInc;
2940 } while (--frameCount);
2941 }
2942 } else {
2943 if (mChannelCount == 1) {
2944 do {
2945 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2946 out++;
2947 } while (--frameCount);
2948 } else {
2949 do {
2950 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2951 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2952 out += 2;
2953 } while (--frameCount);
2954 }
2955 }
2956
2957 // convert back to unsigned 8 bit after volume calculation
2958 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
2959 size_t count = mFrameCount * mChannelCount;
2960 int16_t *src = mMixBuffer;
2961 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002962 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08002963 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2964 }
2965 }
2966
2967 mLeftVolShort = leftVol;
2968 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002969}
2970
2971void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
2972{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002973 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002974 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002975 sleepTime = activeSleepTime;
2976 } else {
2977 sleepTime = idleSleepTime;
2978 }
2979 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
2980 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2981 sleepTime = 0;
2982 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002983}
2984
2985// getTrackName_l() must be called with ThreadBase::mLock held
2986int AudioFlinger::DirectOutputThread::getTrackName_l()
2987{
2988 return 0;
2989}
2990
2991// deleteTrackName_l() must be called with ThreadBase::mLock held
2992void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2993{
2994}
2995
2996// checkForNewParameters_l() must be called with ThreadBase::mLock held
2997bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2998{
2999 bool reconfig = false;
3000
3001 while (!mNewParameters.isEmpty()) {
3002 status_t status = NO_ERROR;
3003 String8 keyValuePair = mNewParameters[0];
3004 AudioParameter param = AudioParameter(keyValuePair);
3005 int value;
3006
3007 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3008 // do not accept frame count changes if tracks are open as the track buffer
3009 // size depends on frame count and correct behavior would not be garantied
3010 // if frame count is changed after track creation
3011 if (!mTracks.isEmpty()) {
3012 status = INVALID_OPERATION;
3013 } else {
3014 reconfig = true;
3015 }
3016 }
3017 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003018 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003019 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003020 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003021 mOutput->stream->common.standby(&mOutput->stream->common);
3022 mStandby = true;
3023 mBytesWritten = 0;
3024 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003025 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003026 }
3027 if (status == NO_ERROR && reconfig) {
3028 readOutputParameters();
3029 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3030 }
3031 }
3032
3033 mNewParameters.removeAt(0);
3034
3035 mParamStatus = status;
3036 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003037 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3038 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003039 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003040 }
3041 return reconfig;
3042}
3043
3044uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
3045{
3046 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003047 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003048 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003049 } else {
3050 time = 10000;
3051 }
3052 return time;
3053}
3054
3055uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
3056{
3057 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003058 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003059 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003060 } else {
3061 time = 10000;
3062 }
3063 return time;
3064}
3065
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003066uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
3067{
3068 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003069 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003070 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3071 } else {
3072 time = 10000;
3073 }
3074 return time;
3075}
3076
Glenn Kasten66fcab92012-02-24 14:59:21 -08003077void AudioFlinger::DirectOutputThread::cacheParameters_l()
3078{
3079 PlaybackThread::cacheParameters_l();
3080
3081 // use shorter standby delay as on normal output to release
3082 // hardware resources as soon as possible
3083 standbyDelay = microseconds(activeSleepTime*2);
3084}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003085
Mathias Agopian65ab4712010-07-14 17:59:35 -07003086// ----------------------------------------------------------------------------
3087
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003088AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003089 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003090 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3091 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003092{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003093 addOutputTrack(mainThread);
3094}
3095
3096AudioFlinger::DuplicatingThread::~DuplicatingThread()
3097{
3098 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3099 mOutputTracks[i]->destroy();
3100 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003101}
3102
Glenn Kasten000f0e32012-03-01 17:10:56 -08003103void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003104{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003105 // mix buffers...
3106 if (outputsReady(outputTracks)) {
3107 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3108 } else {
3109 memset(mMixBuffer, 0, mixBufferSize);
3110 }
3111 sleepTime = 0;
3112 writeFrames = mFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003113}
3114
3115void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3116{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003117 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003118 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003119 sleepTime = activeSleepTime;
3120 } else {
3121 sleepTime = idleSleepTime;
3122 }
3123 } else if (mBytesWritten != 0) {
3124 // flush remaining overflow buffers in output tracks
3125 for (size_t i = 0; i < outputTracks.size(); i++) {
3126 if (outputTracks[i]->isActive()) {
3127 sleepTime = 0;
3128 writeFrames = 0;
3129 memset(mMixBuffer, 0, mixBufferSize);
3130 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003131 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003132 }
3133 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003134}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003135
Glenn Kasten000f0e32012-03-01 17:10:56 -08003136void AudioFlinger::DuplicatingThread::threadLoop_write()
3137{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003138 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003139 for (size_t i = 0; i < outputTracks.size(); i++) {
3140 outputTracks[i]->write(mMixBuffer, writeFrames);
3141 }
3142 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003143}
Glenn Kasten688a6402012-02-29 07:57:06 -08003144
Glenn Kasten000f0e32012-03-01 17:10:56 -08003145void AudioFlinger::DuplicatingThread::threadLoop_standby()
3146{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003147 // DuplicatingThread implements standby by stopping all tracks
3148 for (size_t i = 0; i < outputTracks.size(); i++) {
3149 outputTracks[i]->stop();
3150 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003151}
3152
Glenn Kastenfa26a852012-03-06 11:28:04 -08003153void AudioFlinger::DuplicatingThread::saveOutputTracks()
3154{
3155 outputTracks = mOutputTracks;
3156}
3157
3158void AudioFlinger::DuplicatingThread::clearOutputTracks()
3159{
3160 outputTracks.clear();
3161}
3162
Mathias Agopian65ab4712010-07-14 17:59:35 -07003163void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3164{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003165 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003166 // FIXME explain this formula
Mathias Agopian65ab4712010-07-14 17:59:35 -07003167 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003168 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003169 this,
3170 mSampleRate,
3171 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003172 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003173 frameCount);
3174 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003175 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003176 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003177 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003178 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003179 }
3180}
3181
3182void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3183{
3184 Mutex::Autolock _l(mLock);
3185 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003186 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003187 mOutputTracks[i]->destroy();
3188 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003189 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003190 return;
3191 }
3192 }
Steve Block3856b092011-10-20 11:56:00 +01003193 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003194}
3195
Glenn Kasten438b0362012-03-06 11:24:48 -08003196// caller must hold mLock
3197void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003198{
3199 mWaitTimeMs = UINT_MAX;
3200 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3201 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003202 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003203 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3204 if (waitTimeMs < mWaitTimeMs) {
3205 mWaitTimeMs = waitTimeMs;
3206 }
3207 }
3208 }
3209}
3210
3211
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003212bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003213{
3214 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003215 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003216 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003217 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003218 return false;
3219 }
3220 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3221 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003222 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003223 return false;
3224 }
3225 }
3226 return true;
3227}
3228
3229uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3230{
3231 return (mWaitTimeMs * 1000) / 2;
3232}
3233
Glenn Kasten66fcab92012-02-24 14:59:21 -08003234void AudioFlinger::DuplicatingThread::cacheParameters_l()
3235{
3236 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3237 updateWaitTime_l();
3238
3239 MixerThread::cacheParameters_l();
3240}
3241
Mathias Agopian65ab4712010-07-14 17:59:35 -07003242// ----------------------------------------------------------------------------
3243
3244// TrackBase constructor must be called with AudioFlinger::mLock held
3245AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003246 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003247 const sp<Client>& client,
3248 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003249 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003250 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003251 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003252 const sp<IMemory>& sharedBuffer,
3253 int sessionId)
3254 : RefBase(),
3255 mThread(thread),
3256 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003257 mCblk(NULL),
3258 // mBuffer
3259 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003260 mFrameCount(0),
3261 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003262 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003263 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003264 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003265 // mChannelCount
3266 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003267{
Steve Block3856b092011-10-20 11:56:00 +01003268 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003269
Steve Blockb8a80522011-12-20 16:23:08 +00003270 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003271 size_t size = sizeof(audio_track_cblk_t);
3272 uint8_t channelCount = popcount(channelMask);
3273 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3274 if (sharedBuffer == 0) {
3275 size += bufferSize;
3276 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003277
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003278 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003279 mCblkMemory = client->heap()->allocate(size);
3280 if (mCblkMemory != 0) {
3281 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003282 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003283 new(mCblk) audio_track_cblk_t();
3284 // clear all buffers
3285 mCblk->frameCount = frameCount;
3286 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003287 mChannelCount = channelCount;
3288 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003289 if (sharedBuffer == 0) {
3290 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3291 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3292 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003293 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003294 mCblk->flags = CBLK_UNDERRUN_ON;
3295 } else {
3296 mBuffer = sharedBuffer->pointer();
3297 }
3298 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3299 }
3300 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003301 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003302 client->heap()->dump("AudioTrack");
3303 return;
3304 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003305 } else {
3306 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3307 // construct the shared structure in-place.
3308 new(mCblk) audio_track_cblk_t();
3309 // clear all buffers
3310 mCblk->frameCount = frameCount;
3311 mCblk->sampleRate = sampleRate;
3312 mChannelCount = channelCount;
3313 mChannelMask = channelMask;
3314 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3315 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3316 // Force underrun condition to avoid false underrun callback until first data is
3317 // written to buffer (other flags are cleared)
3318 mCblk->flags = CBLK_UNDERRUN_ON;
3319 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3320 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003321}
3322
3323AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3324{
Glenn Kastena0d68332012-01-27 16:47:15 -08003325 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003326 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003327 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003328 } else {
3329 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003330 }
3331 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003332 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003333 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003334 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003335 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003336 // If the client's reference count drops to zero, the associated destructor
3337 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3338 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003339 mClient.clear();
3340 }
3341}
3342
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003343// AudioBufferProvider interface
3344// getNextBuffer() = 0;
3345// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07003346void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3347{
Glenn Kastene0feee32011-12-13 11:53:26 -08003348 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003349 mFrameCount = buffer->frameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003350 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003351 buffer->frameCount = 0;
3352}
3353
3354bool AudioFlinger::ThreadBase::TrackBase::step() {
3355 bool result;
3356 audio_track_cblk_t* cblk = this->cblk();
3357
3358 result = cblk->stepServer(mFrameCount);
3359 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003360 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003361 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003362 }
3363 return result;
3364}
3365
3366void AudioFlinger::ThreadBase::TrackBase::reset() {
3367 audio_track_cblk_t* cblk = this->cblk();
3368
3369 cblk->user = 0;
3370 cblk->server = 0;
3371 cblk->userBase = 0;
3372 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003373 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01003374 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003375}
3376
Mathias Agopian65ab4712010-07-14 17:59:35 -07003377int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3378 return (int)mCblk->sampleRate;
3379}
3380
Mathias Agopian65ab4712010-07-14 17:59:35 -07003381void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3382 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003383 size_t frameSize = cblk->frameSize;
3384 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3385 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003386
3387 // Check validity of returned pointer in case the track control block would have been corrupted.
3388 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003389 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003390 ALOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003391 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003392 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003393 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003394 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003395 }
3396
3397 return bufferStart;
3398}
3399
3400// ----------------------------------------------------------------------------
3401
3402// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3403AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003404 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003405 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003406 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003407 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003408 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003409 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003410 int frameCount,
3411 const sp<IMemory>& sharedBuffer,
3412 int sessionId)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003413 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003414 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3415 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003416{
3417 if (mCblk != NULL) {
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003418 if (thread != NULL) {
3419 mName = thread->getTrackName_l();
3420 mMainBuffer = thread->mixBuffer();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003421 }
Glenn Kasten23d82a92012-02-03 11:10:00 -08003422 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003423 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003424 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003425 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003426 mStreamType = streamType;
3427 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3428 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003429 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003430 }
3431}
3432
3433AudioFlinger::PlaybackThread::Track::~Track()
3434{
Steve Block3856b092011-10-20 11:56:00 +01003435 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003436 sp<ThreadBase> thread = mThread.promote();
3437 if (thread != 0) {
3438 Mutex::Autolock _l(thread->mLock);
3439 mState = TERMINATED;
3440 }
3441}
3442
3443void AudioFlinger::PlaybackThread::Track::destroy()
3444{
3445 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3446 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08003447 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003448 // we must acquire a strong reference on this Track before locking mLock
3449 // here so that the destructor is called only when exiting this function.
3450 // On the other hand, as long as Track::destroy() is only called by
3451 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3452 // this Track with its member mTrack.
3453 sp<Track> keep(this);
3454 { // scope for mLock
3455 sp<ThreadBase> thread = mThread.promote();
3456 if (thread != 0) {
3457 if (!isOutputTrack()) {
3458 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08003459 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003460
3461 // to track the speaker usage
3462 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003463 }
3464 AudioSystem::releaseOutput(thread->id());
3465 }
3466 Mutex::Autolock _l(thread->mLock);
3467 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3468 playbackThread->destroyTrack_l(this);
3469 }
3470 }
3471}
3472
3473void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3474{
Glenn Kasten83d86532012-01-17 14:39:34 -08003475 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003476 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 -07003477 mName - AudioMixer::TRACK0,
Glenn Kasten44deb052012-02-05 18:09:08 -08003478 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003479 mStreamType,
3480 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003481 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003482 mSessionId,
3483 mFrameCount,
3484 mState,
3485 mMute,
3486 mFillingUpStatus,
3487 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003488 vlr & 0xFFFF,
3489 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003490 mCblk->server,
3491 mCblk->user,
3492 (int)mMainBuffer,
3493 (int)mAuxBuffer);
3494}
3495
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003496// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08003497status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003498 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003499{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003500 audio_track_cblk_t* cblk = this->cblk();
3501 uint32_t framesReady;
3502 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003503
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003504 // Check if last stepServer failed, try to step now
3505 if (mStepServerFailed) {
3506 if (!step()) goto getNextBuffer_exit;
3507 ALOGV("stepServer recovered");
3508 mStepServerFailed = false;
3509 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003510
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003511 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003512
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003513 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003514 uint32_t s = cblk->server;
3515 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3516
3517 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3518 if (framesReq > framesReady) {
3519 framesReq = framesReady;
3520 }
3521 if (s + framesReq > bufferEnd) {
3522 framesReq = bufferEnd - s;
3523 }
3524
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003525 buffer->raw = getBuffer(s, framesReq);
3526 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003527
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003528 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003529 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003530 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003531
3532getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003533 buffer->raw = NULL;
3534 buffer->frameCount = 0;
3535 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3536 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003537}
3538
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003539uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08003540 return mCblk->framesReady();
3541}
3542
Mathias Agopian65ab4712010-07-14 17:59:35 -07003543bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003544 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003545
John Grossman4ff14ba2012-02-08 16:37:41 -08003546 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003547 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3548 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003549 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003550 return true;
3551 }
3552 return false;
3553}
3554
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003555status_t AudioFlinger::PlaybackThread::Track::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003556{
3557 status_t status = NO_ERROR;
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003558 ALOGV("start(%d), calling pid %d session %d tid %d",
3559 mName, IPCThreadState::self()->getCallingPid(), mSessionId, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003560 sp<ThreadBase> thread = mThread.promote();
3561 if (thread != 0) {
3562 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003563 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003564 // here the track could be either new, or restarted
3565 // in both cases "unstop" the track
3566 if (mState == PAUSED) {
3567 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003568 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003569 } else {
3570 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003571 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003572 }
3573
3574 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3575 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003576 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003577 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003578
3579 // to track the speaker usage
3580 if (status == NO_ERROR) {
3581 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3582 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003583 }
3584 if (status == NO_ERROR) {
3585 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3586 playbackThread->addTrack_l(this);
3587 } else {
3588 mState = state;
3589 }
3590 } else {
3591 status = BAD_VALUE;
3592 }
3593 return status;
3594}
3595
3596void AudioFlinger::PlaybackThread::Track::stop()
3597{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003598 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003599 sp<ThreadBase> thread = mThread.promote();
3600 if (thread != 0) {
3601 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003602 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003603 if (mState > STOPPED) {
3604 mState = STOPPED;
3605 // If the track is not active (PAUSED and buffers full), flush buffers
3606 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3607 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3608 reset();
3609 }
Steve Block3856b092011-10-20 11:56:00 +01003610 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003611 }
3612 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3613 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003614 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003615 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003616
3617 // to track the speaker usage
3618 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003619 }
3620 }
3621}
3622
3623void AudioFlinger::PlaybackThread::Track::pause()
3624{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003625 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003626 sp<ThreadBase> thread = mThread.promote();
3627 if (thread != 0) {
3628 Mutex::Autolock _l(thread->mLock);
3629 if (mState == ACTIVE || mState == RESUMING) {
3630 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003631 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003632 if (!isOutputTrack()) {
3633 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003634 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003635 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003636
3637 // to track the speaker usage
3638 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003639 }
3640 }
3641 }
3642}
3643
3644void AudioFlinger::PlaybackThread::Track::flush()
3645{
Steve Block3856b092011-10-20 11:56:00 +01003646 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003647 sp<ThreadBase> thread = mThread.promote();
3648 if (thread != 0) {
3649 Mutex::Autolock _l(thread->mLock);
3650 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3651 return;
3652 }
3653 // No point remaining in PAUSED state after a flush => go to
3654 // STOPPED state
3655 mState = STOPPED;
3656
Eric Laurent38ccae22011-03-28 18:37:07 -07003657 // do not reset the track if it is still in the process of being stopped or paused.
3658 // this will be done by prepareTracks_l() when the track is stopped.
3659 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3660 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3661 reset();
3662 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003663 }
3664}
3665
3666void AudioFlinger::PlaybackThread::Track::reset()
3667{
3668 // Do not reset twice to avoid discarding data written just after a flush and before
3669 // the audioflinger thread detects the track is stopped.
3670 if (!mResetDone) {
3671 TrackBase::reset();
3672 // Force underrun condition to avoid false underrun callback until first data is
3673 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003674 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3675 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003676 mFillingUpStatus = FS_FILLING;
3677 mResetDone = true;
3678 }
3679}
3680
3681void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3682{
3683 mMute = muted;
3684}
3685
Mathias Agopian65ab4712010-07-14 17:59:35 -07003686status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3687{
3688 status_t status = DEAD_OBJECT;
3689 sp<ThreadBase> thread = mThread.promote();
3690 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003691 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3692 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003693 }
3694 return status;
3695}
3696
3697void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3698{
3699 mAuxEffectId = EffectId;
3700 mAuxBuffer = buffer;
3701}
3702
John Grossman4ff14ba2012-02-08 16:37:41 -08003703// timed audio tracks
3704
3705sp<AudioFlinger::PlaybackThread::TimedTrack>
3706AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003707 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003708 const sp<Client>& client,
3709 audio_stream_type_t streamType,
3710 uint32_t sampleRate,
3711 audio_format_t format,
3712 uint32_t channelMask,
3713 int frameCount,
3714 const sp<IMemory>& sharedBuffer,
3715 int sessionId) {
3716 if (!client->reserveTimedTrack())
3717 return NULL;
3718
3719 sp<TimedTrack> track = new TimedTrack(
3720 thread, client, streamType, sampleRate, format, channelMask, frameCount,
3721 sharedBuffer, sessionId);
3722
3723 if (track == NULL) {
3724 client->releaseTimedTrack();
3725 return NULL;
3726 }
3727
3728 return track;
3729}
3730
3731AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003732 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003733 const sp<Client>& client,
3734 audio_stream_type_t streamType,
3735 uint32_t sampleRate,
3736 audio_format_t format,
3737 uint32_t channelMask,
3738 int frameCount,
3739 const sp<IMemory>& sharedBuffer,
3740 int sessionId)
3741 : Track(thread, client, streamType, sampleRate, format, channelMask,
3742 frameCount, sharedBuffer, sessionId),
3743 mTimedSilenceBuffer(NULL),
3744 mTimedSilenceBufferSize(0),
3745 mTimedAudioOutputOnTime(false),
3746 mMediaTimeTransformValid(false)
3747{
3748 LocalClock lc;
3749 mLocalTimeFreq = lc.getLocalFreq();
3750
3751 mLocalTimeToSampleTransform.a_zero = 0;
3752 mLocalTimeToSampleTransform.b_zero = 0;
3753 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3754 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3755 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3756 &mLocalTimeToSampleTransform.a_to_b_denom);
3757}
3758
3759AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3760 mClient->releaseTimedTrack();
3761 delete [] mTimedSilenceBuffer;
3762}
3763
3764status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3765 size_t size, sp<IMemory>* buffer) {
3766
3767 Mutex::Autolock _l(mTimedBufferQueueLock);
3768
3769 trimTimedBufferQueue_l();
3770
3771 // lazily initialize the shared memory heap for timed buffers
3772 if (mTimedMemoryDealer == NULL) {
3773 const int kTimedBufferHeapSize = 512 << 10;
3774
3775 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3776 "AudioFlingerTimed");
3777 if (mTimedMemoryDealer == NULL)
3778 return NO_MEMORY;
3779 }
3780
3781 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3782 if (newBuffer == NULL) {
3783 newBuffer = mTimedMemoryDealer->allocate(size);
3784 if (newBuffer == NULL)
3785 return NO_MEMORY;
3786 }
3787
3788 *buffer = newBuffer;
3789 return NO_ERROR;
3790}
3791
3792// caller must hold mTimedBufferQueueLock
3793void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
3794 int64_t mediaTimeNow;
3795 {
3796 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3797 if (!mMediaTimeTransformValid)
3798 return;
3799
3800 int64_t targetTimeNow;
3801 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
3802 ? mCCHelper.getCommonTime(&targetTimeNow)
3803 : mCCHelper.getLocalTime(&targetTimeNow);
3804
3805 if (OK != res)
3806 return;
3807
3808 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
3809 &mediaTimeNow)) {
3810 return;
3811 }
3812 }
3813
3814 size_t trimIndex;
3815 for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
3816 if (mTimedBufferQueue[trimIndex].pts() > mediaTimeNow)
3817 break;
3818 }
3819
3820 if (trimIndex) {
3821 mTimedBufferQueue.removeItemsAt(0, trimIndex);
3822 }
3823}
3824
3825status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
3826 const sp<IMemory>& buffer, int64_t pts) {
3827
3828 {
3829 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3830 if (!mMediaTimeTransformValid)
3831 return INVALID_OPERATION;
3832 }
3833
3834 Mutex::Autolock _l(mTimedBufferQueueLock);
3835
3836 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
3837
3838 return NO_ERROR;
3839}
3840
3841status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
3842 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
3843
3844 ALOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
3845 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
3846 target);
3847
3848 if (!(target == TimedAudioTrack::LOCAL_TIME ||
3849 target == TimedAudioTrack::COMMON_TIME)) {
3850 return BAD_VALUE;
3851 }
3852
3853 Mutex::Autolock lock(mMediaTimeTransformLock);
3854 mMediaTimeTransform = xform;
3855 mMediaTimeTransformTarget = target;
3856 mMediaTimeTransformValid = true;
3857
3858 return NO_ERROR;
3859}
3860
3861#define min(a, b) ((a) < (b) ? (a) : (b))
3862
3863// implementation of getNextBuffer for tracks whose buffers have timestamps
3864status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
3865 AudioBufferProvider::Buffer* buffer, int64_t pts)
3866{
3867 if (pts == AudioBufferProvider::kInvalidPTS) {
3868 buffer->raw = 0;
3869 buffer->frameCount = 0;
3870 return INVALID_OPERATION;
3871 }
3872
John Grossman4ff14ba2012-02-08 16:37:41 -08003873 Mutex::Autolock _l(mTimedBufferQueueLock);
3874
3875 while (true) {
3876
3877 // if we have no timed buffers, then fail
3878 if (mTimedBufferQueue.isEmpty()) {
3879 buffer->raw = 0;
3880 buffer->frameCount = 0;
3881 return NOT_ENOUGH_DATA;
3882 }
3883
3884 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
3885
3886 // calculate the PTS of the head of the timed buffer queue expressed in
3887 // local time
3888 int64_t headLocalPTS;
3889 {
3890 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3891
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003892 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08003893
3894 if (mMediaTimeTransform.a_to_b_denom == 0) {
3895 // the transform represents a pause, so yield silence
3896 timedYieldSilence(buffer->frameCount, buffer);
3897 return NO_ERROR;
3898 }
3899
3900 int64_t transformedPTS;
3901 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
3902 &transformedPTS)) {
3903 // the transform failed. this shouldn't happen, but if it does
3904 // then just drop this buffer
3905 ALOGW("timedGetNextBuffer transform failed");
3906 buffer->raw = 0;
3907 buffer->frameCount = 0;
3908 mTimedBufferQueue.removeAt(0);
3909 return NO_ERROR;
3910 }
3911
3912 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
3913 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
3914 &headLocalPTS)) {
3915 buffer->raw = 0;
3916 buffer->frameCount = 0;
3917 return INVALID_OPERATION;
3918 }
3919 } else {
3920 headLocalPTS = transformedPTS;
3921 }
3922 }
3923
3924 // adjust the head buffer's PTS to reflect the portion of the head buffer
3925 // that has already been consumed
3926 int64_t effectivePTS = headLocalPTS +
3927 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
3928
3929 // Calculate the delta in samples between the head of the input buffer
3930 // queue and the start of the next output buffer that will be written.
3931 // If the transformation fails because of over or underflow, it means
3932 // that the sample's position in the output stream is so far out of
3933 // whack that it should just be dropped.
3934 int64_t sampleDelta;
3935 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
3936 ALOGV("*** head buffer is too far from PTS: dropped buffer");
3937 mTimedBufferQueue.removeAt(0);
3938 continue;
3939 }
3940 if (!mLocalTimeToSampleTransform.doForwardTransform(
3941 (effectivePTS - pts) << 32, &sampleDelta)) {
3942 ALOGV("*** too late during sample rate transform: dropped buffer");
3943 mTimedBufferQueue.removeAt(0);
3944 continue;
3945 }
3946
3947 ALOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
3948 __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
3949 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
3950 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
3951
3952 // if the delta between the ideal placement for the next input sample and
3953 // the current output position is within this threshold, then we will
3954 // concatenate the next input samples to the previous output
3955 const int64_t kSampleContinuityThreshold =
3956 (static_cast<int64_t>(sampleRate()) << 32) / 10;
3957
3958 // if this is the first buffer of audio that we're emitting from this track
3959 // then it should be almost exactly on time.
3960 const int64_t kSampleStartupThreshold = 1LL << 32;
3961
3962 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
3963 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
3964 // the next input is close enough to being on time, so concatenate it
3965 // with the last output
3966 timedYieldSamples(buffer);
3967
3968 ALOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
3969 return NO_ERROR;
3970 } else if (sampleDelta > 0) {
3971 // the gap between the current output position and the proper start of
3972 // the next input sample is too big, so fill it with silence
3973 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
3974
3975 timedYieldSilence(framesUntilNextInput, buffer);
3976 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
3977 return NO_ERROR;
3978 } else {
3979 // the next input sample is late
3980 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
3981 size_t onTimeSamplePosition =
3982 head.position() + lateFrames * mCblk->frameSize;
3983
3984 if (onTimeSamplePosition > head.buffer()->size()) {
3985 // all the remaining samples in the head are too late, so
3986 // drop it and move on
3987 ALOGV("*** too late: dropped buffer");
3988 mTimedBufferQueue.removeAt(0);
3989 continue;
3990 } else {
3991 // skip over the late samples
3992 head.setPosition(onTimeSamplePosition);
3993
3994 // yield the available samples
3995 timedYieldSamples(buffer);
3996
3997 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
3998 return NO_ERROR;
3999 }
4000 }
4001 }
4002}
4003
4004// Yield samples from the timed buffer queue head up to the given output
4005// buffer's capacity.
4006//
4007// Caller must hold mTimedBufferQueueLock
4008void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples(
4009 AudioBufferProvider::Buffer* buffer) {
4010
4011 const TimedBuffer& head = mTimedBufferQueue[0];
4012
4013 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4014 head.position());
4015
4016 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4017 mCblk->frameSize);
4018 size_t framesRequested = buffer->frameCount;
4019 buffer->frameCount = min(framesLeftInHead, framesRequested);
4020
4021 mTimedAudioOutputOnTime = true;
4022}
4023
4024// Yield samples of silence up to the given output buffer's capacity
4025//
4026// Caller must hold mTimedBufferQueueLock
4027void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence(
4028 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4029
4030 // lazily allocate a buffer filled with silence
4031 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4032 delete [] mTimedSilenceBuffer;
4033 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4034 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4035 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4036 }
4037
4038 buffer->raw = mTimedSilenceBuffer;
4039 size_t framesRequested = buffer->frameCount;
4040 buffer->frameCount = min(numFrames, framesRequested);
4041
4042 mTimedAudioOutputOnTime = false;
4043}
4044
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004045// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004046void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4047 AudioBufferProvider::Buffer* buffer) {
4048
4049 Mutex::Autolock _l(mTimedBufferQueueLock);
4050
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004051 // If the buffer which was just released is part of the buffer at the head
4052 // of the queue, be sure to update the amt of the buffer which has been
4053 // consumed. If the buffer being returned is not part of the head of the
4054 // queue, its either because the buffer is part of the silence buffer, or
4055 // because the head of the timed queue was trimmed after the mixer called
4056 // getNextBuffer but before the mixer called releaseBuffer.
4057 if ((buffer->raw != mTimedSilenceBuffer) && mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004058 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004059
4060 void* start = head.buffer()->pointer();
Glenn Kastenf063b492012-02-17 16:24:10 -08004061 void* end = (char *) head.buffer()->pointer() + head.buffer()->size();
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004062
4063 if ((buffer->raw >= start) && (buffer->raw <= end)) {
4064 head.setPosition(head.position() +
4065 (buffer->frameCount * mCblk->frameSize));
4066 if (static_cast<size_t>(head.position()) >= head.buffer()->size()) {
4067 mTimedBufferQueue.removeAt(0);
4068 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004069 }
4070 }
4071
4072 buffer->raw = 0;
4073 buffer->frameCount = 0;
4074}
4075
4076uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4077 Mutex::Autolock _l(mTimedBufferQueueLock);
4078
4079 uint32_t frames = 0;
4080 for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4081 const TimedBuffer& tb = mTimedBufferQueue[i];
4082 frames += (tb.buffer()->size() - tb.position()) / mCblk->frameSize;
4083 }
4084
4085 return frames;
4086}
4087
4088AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4089 : mPTS(0), mPosition(0) {}
4090
4091AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4092 const sp<IMemory>& buffer, int64_t pts)
4093 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4094
Mathias Agopian65ab4712010-07-14 17:59:35 -07004095// ----------------------------------------------------------------------------
4096
4097// RecordTrack constructor must be called with AudioFlinger::mLock held
4098AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004099 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004100 const sp<Client>& client,
4101 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004102 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004103 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004104 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004105 int sessionId)
4106 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004107 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004108 mOverflow(false)
4109{
4110 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004111 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
4112 if (format == AUDIO_FORMAT_PCM_16_BIT) {
4113 mCblk->frameSize = mChannelCount * sizeof(int16_t);
4114 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
4115 mCblk->frameSize = mChannelCount * sizeof(int8_t);
4116 } else {
4117 mCblk->frameSize = sizeof(int8_t);
4118 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004119 }
4120}
4121
4122AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4123{
4124 sp<ThreadBase> thread = mThread.promote();
4125 if (thread != 0) {
4126 AudioSystem::releaseInput(thread->id());
4127 }
4128}
4129
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004130// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004131status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004132{
4133 audio_track_cblk_t* cblk = this->cblk();
4134 uint32_t framesAvail;
4135 uint32_t framesReq = buffer->frameCount;
4136
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004137 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004138 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004139 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004140 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004141 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004142 }
4143
4144 framesAvail = cblk->framesAvailable_l();
4145
Glenn Kastenf6b16782011-12-15 09:51:17 -08004146 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004147 uint32_t s = cblk->server;
4148 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4149
4150 if (framesReq > framesAvail) {
4151 framesReq = framesAvail;
4152 }
4153 if (s + framesReq > bufferEnd) {
4154 framesReq = bufferEnd - s;
4155 }
4156
4157 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004158 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004159
4160 buffer->frameCount = framesReq;
4161 return NO_ERROR;
4162 }
4163
4164getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004165 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004166 buffer->frameCount = 0;
4167 return NOT_ENOUGH_DATA;
4168}
4169
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004170status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004171{
4172 sp<ThreadBase> thread = mThread.promote();
4173 if (thread != 0) {
4174 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004175 return recordThread->start(this, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004176 } else {
4177 return BAD_VALUE;
4178 }
4179}
4180
4181void AudioFlinger::RecordThread::RecordTrack::stop()
4182{
4183 sp<ThreadBase> thread = mThread.promote();
4184 if (thread != 0) {
4185 RecordThread *recordThread = (RecordThread *)thread.get();
4186 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004187 TrackBase::reset();
4188 // Force overerrun condition to avoid false overrun callback until first data is
4189 // read from buffer
4190 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004191 }
4192}
4193
4194void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4195{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004196 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004197 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004198 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004199 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004200 mSessionId,
4201 mFrameCount,
4202 mState,
4203 mCblk->sampleRate,
4204 mCblk->server,
4205 mCblk->user);
4206}
4207
4208
4209// ----------------------------------------------------------------------------
4210
4211AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004212 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004213 DuplicatingThread *sourceThread,
4214 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004215 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004216 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004217 int frameCount)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004218 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004219 mActive(false), mSourceThread(sourceThread)
4220{
4221
Mathias Agopian65ab4712010-07-14 17:59:35 -07004222 if (mCblk != NULL) {
4223 mCblk->flags |= CBLK_DIRECTION_OUT;
4224 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004225 mOutBuffer.frameCount = 0;
4226 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01004227 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004228 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4229 mCblk, mBuffer, mCblk->buffers,
4230 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004231 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004232 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004233 }
4234}
4235
4236AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4237{
4238 clearBufferQueue();
4239}
4240
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004241status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004242{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004243 status_t status = Track::start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004244 if (status != NO_ERROR) {
4245 return status;
4246 }
4247
4248 mActive = true;
4249 mRetryCount = 127;
4250 return status;
4251}
4252
4253void AudioFlinger::PlaybackThread::OutputTrack::stop()
4254{
4255 Track::stop();
4256 clearBufferQueue();
4257 mOutBuffer.frameCount = 0;
4258 mActive = false;
4259}
4260
4261bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4262{
4263 Buffer *pInBuffer;
4264 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004265 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004266 bool outputBufferFull = false;
4267 inBuffer.frameCount = frames;
4268 inBuffer.i16 = data;
4269
4270 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4271
4272 if (!mActive && frames != 0) {
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004273 start(0);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004274 sp<ThreadBase> thread = mThread.promote();
4275 if (thread != 0) {
4276 MixerThread *mixerThread = (MixerThread *)thread.get();
4277 if (mCblk->frameCount > frames){
4278 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4279 uint32_t startFrames = (mCblk->frameCount - frames);
4280 pInBuffer = new Buffer;
4281 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4282 pInBuffer->frameCount = startFrames;
4283 pInBuffer->i16 = pInBuffer->mBuffer;
4284 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4285 mBufferQueue.add(pInBuffer);
4286 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004287 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004288 }
4289 }
4290 }
4291 }
4292
4293 while (waitTimeLeftMs) {
4294 // First write pending buffers, then new data
4295 if (mBufferQueue.size()) {
4296 pInBuffer = mBufferQueue.itemAt(0);
4297 } else {
4298 pInBuffer = &inBuffer;
4299 }
4300
4301 if (pInBuffer->frameCount == 0) {
4302 break;
4303 }
4304
4305 if (mOutBuffer.frameCount == 0) {
4306 mOutBuffer.frameCount = pInBuffer->frameCount;
4307 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08004308 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01004309 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004310 outputBufferFull = true;
4311 break;
4312 }
4313 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4314 if (waitTimeLeftMs >= waitTimeMs) {
4315 waitTimeLeftMs -= waitTimeMs;
4316 } else {
4317 waitTimeLeftMs = 0;
4318 }
4319 }
4320
4321 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4322 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4323 mCblk->stepUser(outFrames);
4324 pInBuffer->frameCount -= outFrames;
4325 pInBuffer->i16 += outFrames * channelCount;
4326 mOutBuffer.frameCount -= outFrames;
4327 mOutBuffer.i16 += outFrames * channelCount;
4328
4329 if (pInBuffer->frameCount == 0) {
4330 if (mBufferQueue.size()) {
4331 mBufferQueue.removeAt(0);
4332 delete [] pInBuffer->mBuffer;
4333 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01004334 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004335 } else {
4336 break;
4337 }
4338 }
4339 }
4340
4341 // If we could not write all frames, allocate a buffer and queue it for next time.
4342 if (inBuffer.frameCount) {
4343 sp<ThreadBase> thread = mThread.promote();
4344 if (thread != 0 && !thread->standby()) {
4345 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4346 pInBuffer = new Buffer;
4347 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4348 pInBuffer->frameCount = inBuffer.frameCount;
4349 pInBuffer->i16 = pInBuffer->mBuffer;
4350 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4351 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01004352 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004353 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004354 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004355 }
4356 }
4357 }
4358
4359 // Calling write() with a 0 length buffer, means that no more data will be written:
4360 // If no more buffers are pending, fill output track buffer to make sure it is started
4361 // by output mixer.
4362 if (frames == 0 && mBufferQueue.size() == 0) {
4363 if (mCblk->user < mCblk->frameCount) {
4364 frames = mCblk->frameCount - mCblk->user;
4365 pInBuffer = new Buffer;
4366 pInBuffer->mBuffer = new int16_t[frames * channelCount];
4367 pInBuffer->frameCount = frames;
4368 pInBuffer->i16 = pInBuffer->mBuffer;
4369 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4370 mBufferQueue.add(pInBuffer);
4371 } else if (mActive) {
4372 stop();
4373 }
4374 }
4375
4376 return outputBufferFull;
4377}
4378
4379status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4380{
4381 int active;
4382 status_t result;
4383 audio_track_cblk_t* cblk = mCblk;
4384 uint32_t framesReq = buffer->frameCount;
4385
Steve Block3856b092011-10-20 11:56:00 +01004386// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004387 buffer->frameCount = 0;
4388
4389 uint32_t framesAvail = cblk->framesAvailable();
4390
4391
4392 if (framesAvail == 0) {
4393 Mutex::Autolock _l(cblk->lock);
4394 goto start_loop_here;
4395 while (framesAvail == 0) {
4396 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004397 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004398 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004399 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004400 }
4401 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4402 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004403 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004404 }
4405 // read the server count again
4406 start_loop_here:
4407 framesAvail = cblk->framesAvailable_l();
4408 }
4409 }
4410
4411// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004412// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004413// }
4414
4415 if (framesReq > framesAvail) {
4416 framesReq = framesAvail;
4417 }
4418
4419 uint32_t u = cblk->user;
4420 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4421
4422 if (u + framesReq > bufferEnd) {
4423 framesReq = bufferEnd - u;
4424 }
4425
4426 buffer->frameCount = framesReq;
4427 buffer->raw = (void *)cblk->buffer(u);
4428 return NO_ERROR;
4429}
4430
4431
4432void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4433{
4434 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004435
4436 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004437 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004438 delete [] pBuffer->mBuffer;
4439 delete pBuffer;
4440 }
4441 mBufferQueue.clear();
4442}
4443
4444// ----------------------------------------------------------------------------
4445
4446AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4447 : RefBase(),
4448 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08004449 // 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 -07004450 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08004451 mPid(pid),
4452 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004453{
4454 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4455}
4456
4457// Client destructor must be called with AudioFlinger::mLock held
4458AudioFlinger::Client::~Client()
4459{
4460 mAudioFlinger->removeClient_l(mPid);
4461}
4462
Glenn Kasten435dbe62012-01-30 10:15:48 -08004463sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004464{
4465 return mMemoryDealer;
4466}
4467
John Grossman4ff14ba2012-02-08 16:37:41 -08004468// Reserve one of the limited slots for a timed audio track associated
4469// with this client
4470bool AudioFlinger::Client::reserveTimedTrack()
4471{
4472 const int kMaxTimedTracksPerClient = 4;
4473
4474 Mutex::Autolock _l(mTimedTrackLock);
4475
4476 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4477 ALOGW("can not create timed track - pid %d has exceeded the limit",
4478 mPid);
4479 return false;
4480 }
4481
4482 mTimedTrackCount++;
4483 return true;
4484}
4485
4486// Release a slot for a timed audio track
4487void AudioFlinger::Client::releaseTimedTrack()
4488{
4489 Mutex::Autolock _l(mTimedTrackLock);
4490 mTimedTrackCount--;
4491}
4492
Mathias Agopian65ab4712010-07-14 17:59:35 -07004493// ----------------------------------------------------------------------------
4494
4495AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4496 const sp<IAudioFlingerClient>& client,
4497 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004498 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004499{
4500}
4501
4502AudioFlinger::NotificationClient::~NotificationClient()
4503{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004504}
4505
4506void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4507{
4508 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08004509 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004510}
4511
4512// ----------------------------------------------------------------------------
4513
4514AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4515 : BnAudioTrack(),
4516 mTrack(track)
4517{
4518}
4519
4520AudioFlinger::TrackHandle::~TrackHandle() {
4521 // just stop the track on deletion, associated resources
4522 // will be freed from the main thread once all pending buffers have
4523 // been played. Unless it's not in the active track list, in which
4524 // case we free everything now...
4525 mTrack->destroy();
4526}
4527
Glenn Kasten90716c52012-01-26 13:40:12 -08004528sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4529 return mTrack->getCblk();
4530}
4531
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004532status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4533 return mTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004534}
4535
4536void AudioFlinger::TrackHandle::stop() {
4537 mTrack->stop();
4538}
4539
4540void AudioFlinger::TrackHandle::flush() {
4541 mTrack->flush();
4542}
4543
4544void AudioFlinger::TrackHandle::mute(bool e) {
4545 mTrack->mute(e);
4546}
4547
4548void AudioFlinger::TrackHandle::pause() {
4549 mTrack->pause();
4550}
4551
Mathias Agopian65ab4712010-07-14 17:59:35 -07004552status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4553{
4554 return mTrack->attachAuxEffect(EffectId);
4555}
4556
John Grossman4ff14ba2012-02-08 16:37:41 -08004557status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4558 sp<IMemory>* buffer) {
4559 if (!mTrack->isTimedTrack())
4560 return INVALID_OPERATION;
4561
4562 PlaybackThread::TimedTrack* tt =
4563 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4564 return tt->allocateTimedBuffer(size, buffer);
4565}
4566
4567status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4568 int64_t pts) {
4569 if (!mTrack->isTimedTrack())
4570 return INVALID_OPERATION;
4571
4572 PlaybackThread::TimedTrack* tt =
4573 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4574 return tt->queueTimedBuffer(buffer, pts);
4575}
4576
4577status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4578 const LinearTransform& xform, int target) {
4579
4580 if (!mTrack->isTimedTrack())
4581 return INVALID_OPERATION;
4582
4583 PlaybackThread::TimedTrack* tt =
4584 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4585 return tt->setMediaTimeTransform(
4586 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4587}
4588
Mathias Agopian65ab4712010-07-14 17:59:35 -07004589status_t AudioFlinger::TrackHandle::onTransact(
4590 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4591{
4592 return BnAudioTrack::onTransact(code, data, reply, flags);
4593}
4594
4595// ----------------------------------------------------------------------------
4596
4597sp<IAudioRecord> AudioFlinger::openRecord(
4598 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004599 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004600 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004601 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004602 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004603 int frameCount,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004604 // FIXME dead, remove from IAudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -07004605 uint32_t flags,
4606 int *sessionId,
4607 status_t *status)
4608{
4609 sp<RecordThread::RecordTrack> recordTrack;
4610 sp<RecordHandle> recordHandle;
4611 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004612 status_t lStatus;
4613 RecordThread *thread;
4614 size_t inFrameCount;
4615 int lSessionId;
4616
4617 // check calling permissions
4618 if (!recordingAllowed()) {
4619 lStatus = PERMISSION_DENIED;
4620 goto Exit;
4621 }
4622
4623 // add client to list
4624 { // scope for mLock
4625 Mutex::Autolock _l(mLock);
4626 thread = checkRecordThread_l(input);
4627 if (thread == NULL) {
4628 lStatus = BAD_VALUE;
4629 goto Exit;
4630 }
4631
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004632 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004633
4634 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004635 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004636 lSessionId = *sessionId;
4637 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004638 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004639 if (sessionId != NULL) {
4640 *sessionId = lSessionId;
4641 }
4642 }
4643 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004644 recordTrack = thread->createRecordTrack_l(client,
4645 sampleRate,
4646 format,
4647 channelMask,
4648 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004649 lSessionId,
4650 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004651 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004652 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004653 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4654 // destructor is called by the TrackBase destructor with mLock held
4655 client.clear();
4656 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004657 goto Exit;
4658 }
4659
4660 // return to handle to client
4661 recordHandle = new RecordHandle(recordTrack);
4662 lStatus = NO_ERROR;
4663
4664Exit:
4665 if (status) {
4666 *status = lStatus;
4667 }
4668 return recordHandle;
4669}
4670
4671// ----------------------------------------------------------------------------
4672
4673AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4674 : BnAudioRecord(),
4675 mRecordTrack(recordTrack)
4676{
4677}
4678
4679AudioFlinger::RecordHandle::~RecordHandle() {
4680 stop();
4681}
4682
Glenn Kasten90716c52012-01-26 13:40:12 -08004683sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4684 return mRecordTrack->getCblk();
4685}
4686
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004687status_t AudioFlinger::RecordHandle::start(pid_t tid) {
Steve Block3856b092011-10-20 11:56:00 +01004688 ALOGV("RecordHandle::start()");
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004689 return mRecordTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004690}
4691
4692void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004693 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004694 mRecordTrack->stop();
4695}
4696
Mathias Agopian65ab4712010-07-14 17:59:35 -07004697status_t AudioFlinger::RecordHandle::onTransact(
4698 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4699{
4700 return BnAudioRecord::onTransact(code, data, reply, flags);
4701}
4702
4703// ----------------------------------------------------------------------------
4704
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004705AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4706 AudioStreamIn *input,
4707 uint32_t sampleRate,
4708 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004709 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004710 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004711 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004712 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4713 // mRsmpInIndex and mInputBytes set by readInputParameters()
4714 mReqChannelCount(popcount(channels)),
4715 mReqSampleRate(sampleRate)
4716 // mBytesRead is only meaningful while active, and so is cleared in start()
4717 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004718{
Glenn Kasten480b4682012-02-28 12:30:08 -08004719 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07004720
Mathias Agopian65ab4712010-07-14 17:59:35 -07004721 readInputParameters();
4722}
4723
4724
4725AudioFlinger::RecordThread::~RecordThread()
4726{
4727 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004728 delete mResampler;
4729 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004730}
4731
4732void AudioFlinger::RecordThread::onFirstRef()
4733{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004734 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004735}
4736
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004737status_t AudioFlinger::RecordThread::readyToRun()
4738{
4739 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004740 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004741 return status;
4742}
4743
Mathias Agopian65ab4712010-07-14 17:59:35 -07004744bool AudioFlinger::RecordThread::threadLoop()
4745{
4746 AudioBufferProvider::Buffer buffer;
4747 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004748 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004749
Eric Laurent44d98482010-09-30 16:12:31 -07004750 nsecs_t lastWarning = 0;
4751
Eric Laurentfeb0db62011-07-22 09:04:31 -07004752 acquireWakeLock();
4753
Mathias Agopian65ab4712010-07-14 17:59:35 -07004754 // start recording
4755 while (!exitPending()) {
4756
4757 processConfigEvents();
4758
4759 { // scope for mLock
4760 Mutex::Autolock _l(mLock);
4761 checkForNewParameters_l();
4762 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4763 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004764 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004765 mStandby = true;
4766 }
4767
4768 if (exitPending()) break;
4769
Eric Laurentfeb0db62011-07-22 09:04:31 -07004770 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004771 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004772 // go to sleep
4773 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004774 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004775 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004776 continue;
4777 }
4778 if (mActiveTrack != 0) {
4779 if (mActiveTrack->mState == TrackBase::PAUSING) {
4780 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004781 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004782 mStandby = true;
4783 }
4784 mActiveTrack.clear();
4785 mStartStopCond.broadcast();
4786 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4787 if (mReqChannelCount != mActiveTrack->channelCount()) {
4788 mActiveTrack.clear();
4789 mStartStopCond.broadcast();
4790 } else if (mBytesRead != 0) {
4791 // record start succeeds only if first read from audio input
4792 // succeeds
4793 if (mBytesRead > 0) {
4794 mActiveTrack->mState = TrackBase::ACTIVE;
4795 } else {
4796 mActiveTrack.clear();
4797 }
4798 mStartStopCond.broadcast();
4799 }
4800 mStandby = false;
4801 }
4802 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004803 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004804 }
4805
4806 if (mActiveTrack != 0) {
4807 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4808 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004809 unlockEffectChains(effectChains);
4810 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004811 continue;
4812 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004813 for (size_t i = 0; i < effectChains.size(); i ++) {
4814 effectChains[i]->process_l();
4815 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004816
Mathias Agopian65ab4712010-07-14 17:59:35 -07004817 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004818 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004819 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004820 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004821 // no resampling
4822 while (framesOut) {
4823 size_t framesIn = mFrameCount - mRsmpInIndex;
4824 if (framesIn) {
4825 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4826 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4827 if (framesIn > framesOut)
4828 framesIn = framesOut;
4829 mRsmpInIndex += framesIn;
4830 framesOut -= framesIn;
4831 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004832 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004833 memcpy(dst, src, framesIn * mFrameSize);
4834 } else {
4835 int16_t *src16 = (int16_t *)src;
4836 int16_t *dst16 = (int16_t *)dst;
4837 if (mChannelCount == 1) {
4838 while (framesIn--) {
4839 *dst16++ = *src16;
4840 *dst16++ = *src16++;
4841 }
4842 } else {
4843 while (framesIn--) {
4844 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4845 src16 += 2;
4846 }
4847 }
4848 }
4849 }
4850 if (framesOut && mFrameCount == mRsmpInIndex) {
4851 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004852 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004853 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004854 framesOut = 0;
4855 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004856 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004857 mRsmpInIndex = 0;
4858 }
4859 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004860 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004861 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4862 // Force input into standby so that it tries to
4863 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004864 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004865 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004866 }
4867 mRsmpInIndex = mFrameCount;
4868 framesOut = 0;
4869 buffer.frameCount = 0;
4870 }
4871 }
4872 }
4873 } else {
4874 // resampling
4875
4876 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4877 // alter output frame count as if we were expecting stereo samples
4878 if (mChannelCount == 1 && mReqChannelCount == 1) {
4879 framesOut >>= 1;
4880 }
4881 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4882 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4883 // are 32 bit aligned which should be always true.
4884 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004885 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004886 // the resampler always outputs stereo samples: do post stereo to mono conversion
4887 int16_t *src = (int16_t *)mRsmpOutBuffer;
4888 int16_t *dst = buffer.i16;
4889 while (framesOut--) {
4890 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4891 src += 2;
4892 }
4893 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004894 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004895 }
4896
4897 }
4898 mActiveTrack->releaseBuffer(&buffer);
4899 mActiveTrack->overflow();
4900 }
4901 // client isn't retrieving buffers fast enough
4902 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004903 if (!mActiveTrack->setOverflow()) {
4904 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004905 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004906 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004907 lastWarning = now;
4908 }
4909 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004910 // Release the processor for a while before asking for a new buffer.
4911 // This will give the application more chance to read from the buffer and
4912 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004913 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004914 }
4915 }
Eric Laurentec437d82011-07-26 20:54:46 -07004916 // enable changes in effect chain
4917 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004918 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004919 }
4920
4921 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004922 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004923 }
4924 mActiveTrack.clear();
4925
4926 mStartStopCond.broadcast();
4927
Eric Laurentfeb0db62011-07-22 09:04:31 -07004928 releaseWakeLock();
4929
Steve Block3856b092011-10-20 11:56:00 +01004930 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004931 return false;
4932}
4933
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004934
4935sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4936 const sp<AudioFlinger::Client>& client,
4937 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004938 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004939 int channelMask,
4940 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004941 int sessionId,
4942 status_t *status)
4943{
4944 sp<RecordTrack> track;
4945 status_t lStatus;
4946
4947 lStatus = initCheck();
4948 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004949 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004950 goto Exit;
4951 }
4952
4953 { // scope for mLock
4954 Mutex::Autolock _l(mLock);
4955
4956 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004957 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004958
Glenn Kasten7378ca52012-01-20 13:44:40 -08004959 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004960 lStatus = NO_MEMORY;
4961 goto Exit;
4962 }
4963
4964 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004965 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4966 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004967 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004968 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4969 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004970 }
4971 lStatus = NO_ERROR;
4972
4973Exit:
4974 if (status) {
4975 *status = lStatus;
4976 }
4977 return track;
4978}
4979
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004980status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004981{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004982 ALOGV("RecordThread::start tid=%d", tid);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004983 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004984 status_t status = NO_ERROR;
4985 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004986 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004987 if (mActiveTrack != 0) {
4988 if (recordTrack != mActiveTrack.get()) {
4989 status = -EBUSY;
4990 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4991 mActiveTrack->mState = TrackBase::ACTIVE;
4992 }
4993 return status;
4994 }
4995
4996 recordTrack->mState = TrackBase::IDLE;
4997 mActiveTrack = recordTrack;
4998 mLock.unlock();
4999 status_t status = AudioSystem::startInput(mId);
5000 mLock.lock();
5001 if (status != NO_ERROR) {
5002 mActiveTrack.clear();
5003 return status;
5004 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005005 mRsmpInIndex = mFrameCount;
5006 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005007 if (mResampler != NULL) {
5008 mResampler->reset();
5009 }
5010 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005011 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005012 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005013 mWaitWorkCV.signal();
5014 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005015 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005016 mActiveTrack.clear();
5017 status = INVALID_OPERATION;
5018 goto startError;
5019 }
5020 mStartStopCond.wait(mLock);
5021 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005022 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005023 status = BAD_VALUE;
5024 goto startError;
5025 }
Steve Block3856b092011-10-20 11:56:00 +01005026 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005027 return status;
5028 }
5029startError:
5030 AudioSystem::stopInput(mId);
5031 return status;
5032}
5033
5034void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005035 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005036 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005037 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005038 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005039 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5040 mActiveTrack->mState = TrackBase::PAUSING;
5041 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005042 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005043 return;
5044 }
5045 mStartStopCond.wait(mLock);
5046 // if we have been restarted, recordTrack == mActiveTrack.get() here
5047 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5048 mLock.unlock();
5049 AudioSystem::stopInput(mId);
5050 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005051 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005052 }
5053 }
5054 }
5055}
5056
5057status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5058{
5059 const size_t SIZE = 256;
5060 char buffer[SIZE];
5061 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005062
5063 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5064 result.append(buffer);
5065
5066 if (mActiveTrack != 0) {
5067 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005068 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005069 mActiveTrack->dump(buffer, SIZE);
5070 result.append(buffer);
5071
5072 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5073 result.append(buffer);
5074 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5075 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005076 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005077 result.append(buffer);
5078 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5079 result.append(buffer);
5080 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5081 result.append(buffer);
5082
5083
5084 } else {
5085 result.append("No record client\n");
5086 }
5087 write(fd, result.string(), result.size());
5088
5089 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005090 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005091
5092 return NO_ERROR;
5093}
5094
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005095// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005096status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005097{
5098 size_t framesReq = buffer->frameCount;
5099 size_t framesReady = mFrameCount - mRsmpInIndex;
5100 int channelCount;
5101
5102 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005103 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005104 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005105 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005106 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5107 // Force input into standby so that it tries to
5108 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005109 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005110 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005111 }
Glenn Kastene0feee32011-12-13 11:53:26 -08005112 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005113 buffer->frameCount = 0;
5114 return NOT_ENOUGH_DATA;
5115 }
5116 mRsmpInIndex = 0;
5117 framesReady = mFrameCount;
5118 }
5119
5120 if (framesReq > framesReady) {
5121 framesReq = framesReady;
5122 }
5123
5124 if (mChannelCount == 1 && mReqChannelCount == 2) {
5125 channelCount = 1;
5126 } else {
5127 channelCount = 2;
5128 }
5129 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5130 buffer->frameCount = framesReq;
5131 return NO_ERROR;
5132}
5133
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005134// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07005135void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5136{
5137 mRsmpInIndex += buffer->frameCount;
5138 buffer->frameCount = 0;
5139}
5140
5141bool AudioFlinger::RecordThread::checkForNewParameters_l()
5142{
5143 bool reconfig = false;
5144
5145 while (!mNewParameters.isEmpty()) {
5146 status_t status = NO_ERROR;
5147 String8 keyValuePair = mNewParameters[0];
5148 AudioParameter param = AudioParameter(keyValuePair);
5149 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08005150 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005151 int reqSamplingRate = mReqSampleRate;
5152 int reqChannelCount = mReqChannelCount;
5153
5154 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5155 reqSamplingRate = value;
5156 reconfig = true;
5157 }
5158 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08005159 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005160 reconfig = true;
5161 }
5162 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005163 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005164 reconfig = true;
5165 }
5166 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5167 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08005168 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005169 // if frame count is changed after track creation
5170 if (mActiveTrack != 0) {
5171 status = INVALID_OPERATION;
5172 } else {
5173 reconfig = true;
5174 }
5175 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005176 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5177 // forward device change to effects that have requested to be
5178 // aware of attached audio device.
5179 for (size_t i = 0; i < mEffectChains.size(); i++) {
5180 mEffectChains[i]->setDevice_l(value);
5181 }
5182 // store input device and output device but do not forward output device to audio HAL.
5183 // Note that status is ignored by the caller for output device
5184 // (see AudioFlinger::setParameters()
5185 if (value & AUDIO_DEVICE_OUT_ALL) {
5186 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5187 status = BAD_VALUE;
5188 } else {
5189 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07005190 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5191 if (mTrack != NULL) {
5192 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005193 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005194 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5195 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5196 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005197 }
5198 mDevice |= (uint32_t)value;
5199 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005200 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005201 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005202 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005203 mInput->stream->common.standby(&mInput->stream->common);
5204 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5205 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005206 }
5207 if (reconfig) {
5208 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005209 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005210 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005211 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08005212 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
5213 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005214 status = NO_ERROR;
5215 }
5216 if (status == NO_ERROR) {
5217 readInputParameters();
5218 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5219 }
5220 }
5221 }
5222
5223 mNewParameters.removeAt(0);
5224
5225 mParamStatus = status;
5226 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07005227 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5228 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08005229 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005230 }
5231 return reconfig;
5232}
5233
5234String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5235{
Dima Zavinfce7a472011-04-19 22:30:36 -07005236 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005237 String8 out_s8 = String8();
5238
5239 Mutex::Autolock _l(mLock);
5240 if (initCheck() != NO_ERROR) {
5241 return out_s8;
5242 }
Dima Zavinfce7a472011-04-19 22:30:36 -07005243
Dima Zavin799a70e2011-04-18 16:57:27 -07005244 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07005245 out_s8 = String8(s);
5246 free(s);
5247 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005248}
5249
5250void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5251 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08005252 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005253
5254 switch (event) {
5255 case AudioSystem::INPUT_OPENED:
5256 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005257 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005258 desc.samplingRate = mSampleRate;
5259 desc.format = mFormat;
5260 desc.frameCount = mFrameCount;
5261 desc.latency = 0;
5262 param2 = &desc;
5263 break;
5264
5265 case AudioSystem::INPUT_CLOSED:
5266 default:
5267 break;
5268 }
5269 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5270}
5271
5272void AudioFlinger::RecordThread::readInputParameters()
5273{
Glenn Kastene9dd0172012-01-27 18:08:45 -08005274 delete mRsmpInBuffer;
5275 // mRsmpInBuffer is always assigned a new[] below
5276 delete mRsmpOutBuffer;
5277 mRsmpOutBuffer = NULL;
5278 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08005279 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005280
Dima Zavin799a70e2011-04-18 16:57:27 -07005281 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005282 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5283 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07005284 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08005285 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07005286 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005287 mFrameCount = mInputBytes / mFrameSize;
5288 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5289
Glenn Kasten53d76db2012-03-08 12:32:47 -08005290 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005291 {
5292 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005293 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5294 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005295 if (mChannelCount == 1 && mReqChannelCount == 2) {
5296 channelCount = 1;
5297 } else {
5298 channelCount = 2;
5299 }
5300 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5301 mResampler->setSampleRate(mSampleRate);
5302 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5303 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5304
5305 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5306 if (mChannelCount == 1 && mReqChannelCount == 1) {
5307 mFrameCount >>= 1;
5308 }
5309
5310 }
5311 mRsmpInIndex = mFrameCount;
5312}
5313
5314unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5315{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005316 Mutex::Autolock _l(mLock);
5317 if (initCheck() != NO_ERROR) {
5318 return 0;
5319 }
5320
Dima Zavin799a70e2011-04-18 16:57:27 -07005321 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005322}
5323
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005324uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5325{
5326 Mutex::Autolock _l(mLock);
5327 uint32_t result = 0;
5328 if (getEffectChain_l(sessionId) != 0) {
5329 result = EFFECT_SESSION;
5330 }
5331
5332 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5333 result |= TRACK_SESSION;
5334 }
5335
5336 return result;
5337}
5338
Eric Laurent59bd0da2011-08-01 09:52:20 -07005339AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5340{
5341 Mutex::Autolock _l(mLock);
5342 return mTrack;
5343}
5344
Glenn Kastenaed850d2012-01-26 09:46:34 -08005345AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005346{
5347 Mutex::Autolock _l(mLock);
5348 return mInput;
5349}
5350
5351AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5352{
5353 Mutex::Autolock _l(mLock);
5354 AudioStreamIn *input = mInput;
5355 mInput = NULL;
5356 return input;
5357}
5358
5359// this method must always be called either with ThreadBase mLock held or inside the thread loop
5360audio_stream_t* AudioFlinger::RecordThread::stream()
5361{
5362 if (mInput == NULL) {
5363 return NULL;
5364 }
5365 return &mInput->stream->common;
5366}
5367
5368
Mathias Agopian65ab4712010-07-14 17:59:35 -07005369// ----------------------------------------------------------------------------
5370
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005371audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005372 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005373 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005374 uint32_t *pChannels,
5375 uint32_t *pLatencyMs,
Glenn Kasten18868c52012-03-07 09:15:37 -08005376 audio_policy_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005377{
5378 status_t status;
5379 PlaybackThread *thread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005380 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005381 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005382 uint32_t channels = pChannels ? *pChannels : 0;
5383 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07005384 audio_stream_out_t *outStream;
5385 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005386
Steve Block3856b092011-10-20 11:56:00 +01005387 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07005388 pDevices ? *pDevices : 0,
5389 samplingRate,
5390 format,
5391 channels,
5392 flags);
5393
5394 if (pDevices == NULL || *pDevices == 0) {
5395 return 0;
5396 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005397
Mathias Agopian65ab4712010-07-14 17:59:35 -07005398 Mutex::Autolock _l(mLock);
5399
Dima Zavin799a70e2011-04-18 16:57:27 -07005400 outHwDev = findSuitableHwDev_l(*pDevices);
5401 if (outHwDev == NULL)
5402 return 0;
5403
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005404 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Glenn Kasten58f30212012-01-12 12:27:51 -08005405 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005406 &channels, &samplingRate, &outStream);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005407 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01005408 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005409 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005410 samplingRate,
5411 format,
5412 channels,
5413 status);
5414
Dima Zavin799a70e2011-04-18 16:57:27 -07005415 if (outStream != NULL) {
5416 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005417 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07005418
Dima Zavinfce7a472011-04-19 22:30:36 -07005419 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5420 (format != AUDIO_FORMAT_PCM_16_BIT) ||
5421 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005422 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005423 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005424 } else {
5425 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005426 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005427 }
5428 mPlaybackThreads.add(id, thread);
5429
Glenn Kastena0d68332012-01-27 16:47:15 -08005430 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5431 if (pFormat != NULL) *pFormat = format;
5432 if (pChannels != NULL) *pChannels = channels;
5433 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005434
5435 // notify client processes of the new output creation
5436 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5437 return id;
5438 }
5439
5440 return 0;
5441}
5442
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005443audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
5444 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005445{
5446 Mutex::Autolock _l(mLock);
5447 MixerThread *thread1 = checkMixerThread_l(output1);
5448 MixerThread *thread2 = checkMixerThread_l(output2);
5449
5450 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005451 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005452 return 0;
5453 }
5454
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005455 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005456 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5457 thread->addOutputTrack(thread2);
5458 mPlaybackThreads.add(id, thread);
5459 // notify client processes of the new output creation
5460 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5461 return id;
5462}
5463
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005464status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005465{
5466 // keep strong reference on the playback thread so that
5467 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005468 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005469 {
5470 Mutex::Autolock _l(mLock);
5471 thread = checkPlaybackThread_l(output);
5472 if (thread == NULL) {
5473 return BAD_VALUE;
5474 }
5475
Steve Block3856b092011-10-20 11:56:00 +01005476 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005477
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005478 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005479 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005480 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005481 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5482 dupThread->removeOutputTrack((MixerThread *)thread.get());
5483 }
5484 }
5485 }
Glenn Kastena1117922012-01-26 10:53:32 -08005486 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005487 mPlaybackThreads.removeItem(output);
5488 }
5489 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005490 // The thread entity (active unit of execution) is no longer running here,
5491 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005492
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005493 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005494 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005495 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005496 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005497 out->hwDev->close_output_stream(out->hwDev, out->stream);
5498 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005499 }
5500 return NO_ERROR;
5501}
5502
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005503status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005504{
5505 Mutex::Autolock _l(mLock);
5506 PlaybackThread *thread = checkPlaybackThread_l(output);
5507
5508 if (thread == NULL) {
5509 return BAD_VALUE;
5510 }
5511
Steve Block3856b092011-10-20 11:56:00 +01005512 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005513 thread->suspend();
5514
5515 return NO_ERROR;
5516}
5517
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005518status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005519{
5520 Mutex::Autolock _l(mLock);
5521 PlaybackThread *thread = checkPlaybackThread_l(output);
5522
5523 if (thread == NULL) {
5524 return BAD_VALUE;
5525 }
5526
Steve Block3856b092011-10-20 11:56:00 +01005527 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005528
5529 thread->restore();
5530
5531 return NO_ERROR;
5532}
5533
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005534audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005535 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005536 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005537 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005538 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005539{
5540 status_t status;
5541 RecordThread *thread = NULL;
5542 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005543 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005544 uint32_t channels = pChannels ? *pChannels : 0;
5545 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005546 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005547 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005548 audio_stream_in_t *inStream;
5549 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005550
5551 if (pDevices == NULL || *pDevices == 0) {
5552 return 0;
5553 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005554
Mathias Agopian65ab4712010-07-14 17:59:35 -07005555 Mutex::Autolock _l(mLock);
5556
Dima Zavin799a70e2011-04-18 16:57:27 -07005557 inHwDev = findSuitableHwDev_l(*pDevices);
5558 if (inHwDev == NULL)
5559 return 0;
5560
Glenn Kasten58f30212012-01-12 12:27:51 -08005561 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005562 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005563 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005564 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005565 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005566 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005567 samplingRate,
5568 format,
5569 channels,
5570 acoustics,
5571 status);
5572
5573 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5574 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5575 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005576 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005577 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005578 (samplingRate <= 2 * reqSamplingRate) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08005579 (popcount(channels) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01005580 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005581 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005582 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005583 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005584 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005585 }
5586
Dima Zavin799a70e2011-04-18 16:57:27 -07005587 if (inStream != NULL) {
5588 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5589
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005590 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005591 // Start record thread
5592 // RecorThread require both input and output device indication to forward to audio
5593 // pre processing modules
5594 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5595 thread = new RecordThread(this,
5596 input,
5597 reqSamplingRate,
5598 reqChannels,
5599 id,
5600 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005601 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005602 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005603 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5604 if (pFormat != NULL) *pFormat = format;
5605 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005606
Dima Zavin799a70e2011-04-18 16:57:27 -07005607 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005608
5609 // notify client processes of the new input creation
5610 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5611 return id;
5612 }
5613
5614 return 0;
5615}
5616
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005617status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005618{
5619 // keep strong reference on the record thread so that
5620 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005621 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005622 {
5623 Mutex::Autolock _l(mLock);
5624 thread = checkRecordThread_l(input);
5625 if (thread == NULL) {
5626 return BAD_VALUE;
5627 }
5628
Steve Block3856b092011-10-20 11:56:00 +01005629 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08005630 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005631 mRecordThreads.removeItem(input);
5632 }
5633 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005634 // The thread entity (active unit of execution) is no longer running here,
5635 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005636
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005637 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005638 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005639 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005640 in->hwDev->close_input_stream(in->hwDev, in->stream);
5641 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005642
5643 return NO_ERROR;
5644}
5645
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005646status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005647{
5648 Mutex::Autolock _l(mLock);
5649 MixerThread *dstThread = checkMixerThread_l(output);
5650 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005651 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005652 return BAD_VALUE;
5653 }
5654
Steve Block3856b092011-10-20 11:56:00 +01005655 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005656 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5657
Eric Laurent9f6530f2011-08-30 10:18:54 -07005658 dstThread->setStreamValid(stream, true);
5659
Mathias Agopian65ab4712010-07-14 17:59:35 -07005660 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5661 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08005662 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005663 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005664 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005665 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005666 }
Eric Laurentde070132010-07-13 04:45:46 -07005667 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005668
5669 return NO_ERROR;
5670}
5671
5672
5673int AudioFlinger::newAudioSessionId()
5674{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005675 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005676}
5677
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005678void AudioFlinger::acquireAudioSessionId(int audioSession)
5679{
5680 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005681 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005682 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005683 size_t num = mAudioSessionRefs.size();
5684 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005685 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005686 if (ref->mSessionid == audioSession && ref->mPid == caller) {
5687 ref->mCnt++;
5688 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005689 return;
5690 }
5691 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005692 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5693 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005694}
5695
5696void AudioFlinger::releaseAudioSessionId(int audioSession)
5697{
5698 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005699 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005700 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005701 size_t num = mAudioSessionRefs.size();
5702 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005703 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005704 if (ref->mSessionid == audioSession && ref->mPid == caller) {
5705 ref->mCnt--;
5706 ALOGV(" decremented refcount to %d", ref->mCnt);
5707 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005708 mAudioSessionRefs.removeAt(i);
5709 delete ref;
5710 purgeStaleEffects_l();
5711 }
5712 return;
5713 }
5714 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005715 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005716}
5717
5718void AudioFlinger::purgeStaleEffects_l() {
5719
Steve Block3856b092011-10-20 11:56:00 +01005720 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005721
5722 Vector< sp<EffectChain> > chains;
5723
5724 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5725 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5726 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5727 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005728 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5729 chains.push(ec);
5730 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005731 }
5732 }
5733 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5734 sp<RecordThread> t = mRecordThreads.valueAt(i);
5735 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5736 sp<EffectChain> ec = t->mEffectChains[j];
5737 chains.push(ec);
5738 }
5739 }
5740
5741 for (size_t i = 0; i < chains.size(); i++) {
5742 sp<EffectChain> ec = chains[i];
5743 int sessionid = ec->sessionId();
5744 sp<ThreadBase> t = ec->mThread.promote();
5745 if (t == 0) {
5746 continue;
5747 }
5748 size_t numsessionrefs = mAudioSessionRefs.size();
5749 bool found = false;
5750 for (size_t k = 0; k < numsessionrefs; k++) {
5751 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005752 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005753 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005754 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005755 found = true;
5756 break;
5757 }
5758 }
5759 if (!found) {
5760 // remove all effects from the chain
5761 while (ec->mEffects.size()) {
5762 sp<EffectModule> effect = ec->mEffects[0];
5763 effect->unPin();
5764 Mutex::Autolock _l (t->mLock);
5765 t->removeEffect_l(effect);
5766 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5767 sp<EffectHandle> handle = effect->mHandles[j].promote();
5768 if (handle != 0) {
5769 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005770 if (handle->mHasControl && handle->mEnabled) {
5771 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5772 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005773 }
5774 }
5775 AudioSystem::unregisterEffect(effect->id());
5776 }
5777 }
5778 }
5779 return;
5780}
5781
Mathias Agopian65ab4712010-07-14 17:59:35 -07005782// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005783AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005784{
Glenn Kastena1117922012-01-26 10:53:32 -08005785 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005786}
5787
5788// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005789AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005790{
5791 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08005792 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005793}
5794
5795// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005796AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005797{
Glenn Kastena1117922012-01-26 10:53:32 -08005798 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005799}
5800
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005801uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005802{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005803 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005804}
5805
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08005806AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005807{
5808 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5809 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005810 AudioStreamOut *output = thread->getOutput();
5811 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005812 return thread;
5813 }
5814 }
5815 return NULL;
5816}
5817
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08005818uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005819{
5820 PlaybackThread *thread = primaryPlaybackThread_l();
5821
5822 if (thread == NULL) {
5823 return 0;
5824 }
5825
5826 return thread->device();
5827}
5828
5829
Mathias Agopian65ab4712010-07-14 17:59:35 -07005830// ----------------------------------------------------------------------------
5831// Effect management
5832// ----------------------------------------------------------------------------
5833
5834
Glenn Kastenf587ba52012-01-26 16:25:10 -08005835status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005836{
5837 Mutex::Autolock _l(mLock);
5838 return EffectQueryNumberEffects(numEffects);
5839}
5840
Glenn Kastenf587ba52012-01-26 16:25:10 -08005841status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005842{
5843 Mutex::Autolock _l(mLock);
5844 return EffectQueryEffect(index, descriptor);
5845}
5846
Glenn Kasten5e92a782012-01-30 07:40:52 -08005847status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08005848 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005849{
5850 Mutex::Autolock _l(mLock);
5851 return EffectGetDescriptor(pUuid, descriptor);
5852}
5853
5854
Mathias Agopian65ab4712010-07-14 17:59:35 -07005855sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5856 effect_descriptor_t *pDesc,
5857 const sp<IEffectClient>& effectClient,
5858 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005859 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005860 int sessionId,
5861 status_t *status,
5862 int *id,
5863 int *enabled)
5864{
5865 status_t lStatus = NO_ERROR;
5866 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005867 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005868
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005869 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005870 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005871
5872 if (pDesc == NULL) {
5873 lStatus = BAD_VALUE;
5874 goto Exit;
5875 }
5876
Eric Laurent84e9a102010-09-23 16:10:16 -07005877 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005878 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005879 lStatus = PERMISSION_DENIED;
5880 goto Exit;
5881 }
5882
Dima Zavinfce7a472011-04-19 22:30:36 -07005883 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005884 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08005885 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005886 lStatus = PERMISSION_DENIED;
5887 goto Exit;
5888 }
5889
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005890 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005891 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005892 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005893 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005894 lStatus = BAD_VALUE;
5895 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005896 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005897 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005898 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005899 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005900 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005901 }
5902 }
5903
Mathias Agopian65ab4712010-07-14 17:59:35 -07005904 {
5905 Mutex::Autolock _l(mLock);
5906
Mathias Agopian65ab4712010-07-14 17:59:35 -07005907
5908 if (!EffectIsNullUuid(&pDesc->uuid)) {
5909 // if uuid is specified, request effect descriptor
5910 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5911 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005912 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005913 goto Exit;
5914 }
5915 } else {
5916 // if uuid is not specified, look for an available implementation
5917 // of the required type in effect factory
5918 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005919 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005920 lStatus = BAD_VALUE;
5921 goto Exit;
5922 }
5923 uint32_t numEffects = 0;
5924 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005925 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005926 bool found = false;
5927
5928 lStatus = EffectQueryNumberEffects(&numEffects);
5929 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005930 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005931 goto Exit;
5932 }
5933 for (uint32_t i = 0; i < numEffects; i++) {
5934 lStatus = EffectQueryEffect(i, &desc);
5935 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005936 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005937 continue;
5938 }
5939 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5940 // If matching type found save effect descriptor. If the session is
5941 // 0 and the effect is not auxiliary, continue enumeration in case
5942 // an auxiliary version of this effect type is available
5943 found = true;
5944 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005945 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005946 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5947 break;
5948 }
5949 }
5950 }
5951 if (!found) {
5952 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00005953 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005954 goto Exit;
5955 }
5956 // For same effect type, chose auxiliary version over insert version if
5957 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005958 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005959 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5960 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5961 }
5962 }
5963
5964 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005965 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005966 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5967 lStatus = INVALID_OPERATION;
5968 goto Exit;
5969 }
5970
Eric Laurent59255e42011-07-27 19:49:51 -07005971 // check recording permission for visualizer
5972 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5973 !recordingAllowed()) {
5974 lStatus = PERMISSION_DENIED;
5975 goto Exit;
5976 }
5977
Mathias Agopian65ab4712010-07-14 17:59:35 -07005978 // return effect descriptor
5979 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5980
5981 // If output is not specified try to find a matching audio session ID in one of the
5982 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005983 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5984 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005985 // Note: io is never 0 when creating an effect on an input
5986 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005987 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07005988 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5989 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005990 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005991 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005992 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005993 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005994 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005995 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5996 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5997 io = mRecordThreads.keyAt(i);
5998 break;
5999 }
6000 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006001 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006002 // If no output thread contains the requested session ID, default to
6003 // first output. The effect chain will be moved to the correct output
6004 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006005 if (io == 0 && mPlaybackThreads.size()) {
6006 io = mPlaybackThreads.keyAt(0);
6007 }
Steve Block3856b092011-10-20 11:56:00 +01006008 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006009 }
6010 ThreadBase *thread = checkRecordThread_l(io);
6011 if (thread == NULL) {
6012 thread = checkPlaybackThread_l(io);
6013 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00006014 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006015 lStatus = BAD_VALUE;
6016 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07006017 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006018 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006019
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006020 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006021
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006022 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07006023 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6024 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006025 if (handle != 0 && id != NULL) {
6026 *id = handle->id();
6027 }
6028 }
6029
6030Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006031 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006032 *status = lStatus;
6033 }
6034 return handle;
6035}
6036
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006037status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
6038 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07006039{
Steve Block3856b092011-10-20 11:56:00 +01006040 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07006041 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006042 Mutex::Autolock _l(mLock);
6043 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006044 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006045 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006046 }
Eric Laurentde070132010-07-13 04:45:46 -07006047 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6048 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006049 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006050 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006051 }
Eric Laurentde070132010-07-13 04:45:46 -07006052 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6053 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006054 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006055 return BAD_VALUE;
6056 }
6057
6058 Mutex::Autolock _dl(dstThread->mLock);
6059 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07006060 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07006061
Mathias Agopian65ab4712010-07-14 17:59:35 -07006062 return NO_ERROR;
6063}
6064
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006065// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07006066status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07006067 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07006068 AudioFlinger::PlaybackThread *dstThread,
6069 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07006070{
Steve Block3856b092011-10-20 11:56:00 +01006071 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006072 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07006073
Eric Laurent59255e42011-07-27 19:49:51 -07006074 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006075 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006076 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006077 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07006078 return INVALID_OPERATION;
6079 }
6080
Eric Laurent39e94f82010-07-28 01:32:47 -07006081 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07006082 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07006083 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07006084 // removed.
6085 srcThread->removeEffectChain_l(chain);
6086
6087 // transfer all effects one by one so that new effect chain is created on new thread with
6088 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006089 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07006090 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006091 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07006092 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6093 while (effect != 0) {
6094 srcThread->removeEffect_l(effect);
6095 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07006096 // removeEffect_l() has stopped the effect if it was active so it must be restarted
6097 if (effect->state() == EffectModule::ACTIVE ||
6098 effect->state() == EffectModule::STOPPING) {
6099 effect->start();
6100 }
Eric Laurent39e94f82010-07-28 01:32:47 -07006101 // if the move request is not received from audio policy manager, the effect must be
6102 // re-registered with the new strategy and output
6103 if (dstChain == 0) {
6104 dstChain = effect->chain().promote();
6105 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006106 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07006107 srcThread->addEffect_l(effect);
6108 return NO_INIT;
6109 }
6110 strategy = dstChain->strategy();
6111 }
6112 if (reRegister) {
6113 AudioSystem::unregisterEffect(effect->id());
6114 AudioSystem::registerEffect(&effect->desc(),
6115 dstOutput,
6116 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07006117 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07006118 effect->id());
6119 }
Eric Laurentde070132010-07-13 04:45:46 -07006120 effect = chain->getEffectFromId_l(0);
6121 }
6122
6123 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006124}
6125
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006126
Mathias Agopian65ab4712010-07-14 17:59:35 -07006127// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006128sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07006129 const sp<AudioFlinger::Client>& client,
6130 const sp<IEffectClient>& effectClient,
6131 int32_t priority,
6132 int sessionId,
6133 effect_descriptor_t *desc,
6134 int *enabled,
6135 status_t *status
6136 )
6137{
6138 sp<EffectModule> effect;
6139 sp<EffectHandle> handle;
6140 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006141 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07006142 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006143 bool effectCreated = false;
6144 bool effectRegistered = false;
6145
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006146 lStatus = initCheck();
6147 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006148 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006149 goto Exit;
6150 }
6151
6152 // Do not allow effects with session ID 0 on direct output or duplicating threads
6153 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07006154 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006155 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07006156 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006157 lStatus = BAD_VALUE;
6158 goto Exit;
6159 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006160 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08006161 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006162 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006163 desc->name, desc->flags, mType);
6164 lStatus = BAD_VALUE;
6165 goto Exit;
6166 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006167
Steve Block3856b092011-10-20 11:56:00 +01006168 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006169
6170 { // scope for mLock
6171 Mutex::Autolock _l(mLock);
6172
6173 // check for existing effect chain with the requested audio session
6174 chain = getEffectChain_l(sessionId);
6175 if (chain == 0) {
6176 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006177 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006178 chain = new EffectChain(this, sessionId);
6179 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07006180 chain->setStrategy(getStrategyForSession_l(sessionId));
6181 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006182 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07006183 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006184 }
6185
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08006186 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006187
6188 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006189 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006190 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07006191 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006192 if (lStatus != NO_ERROR) {
6193 goto Exit;
6194 }
6195 effectRegistered = true;
6196 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07006197 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006198 lStatus = effect->status();
6199 if (lStatus != NO_ERROR) {
6200 goto Exit;
6201 }
Eric Laurentcab11242010-07-15 12:50:15 -07006202 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006203 if (lStatus != NO_ERROR) {
6204 goto Exit;
6205 }
6206 effectCreated = true;
6207
6208 effect->setDevice(mDevice);
6209 effect->setMode(mAudioFlinger->getMode());
6210 }
6211 // create effect handle and connect it to effect module
6212 handle = new EffectHandle(effect, client, effectClient, priority);
6213 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08006214 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006215 *enabled = (int)effect->isEnabled();
6216 }
6217 }
6218
6219Exit:
6220 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07006221 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006222 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07006223 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006224 }
6225 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07006226 AudioSystem::unregisterEffect(effect->id());
6227 }
6228 if (chainCreated) {
6229 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006230 }
6231 handle.clear();
6232 }
6233
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006234 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006235 *status = lStatus;
6236 }
6237 return handle;
6238}
6239
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006240sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6241{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006242 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08006243 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006244}
6245
Eric Laurentde070132010-07-13 04:45:46 -07006246// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6247// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006248status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07006249{
6250 // check for existing effect chain with the requested audio session
6251 int sessionId = effect->sessionId();
6252 sp<EffectChain> chain = getEffectChain_l(sessionId);
6253 bool chainCreated = false;
6254
6255 if (chain == 0) {
6256 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006257 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006258 chain = new EffectChain(this, sessionId);
6259 addEffectChain_l(chain);
6260 chain->setStrategy(getStrategyForSession_l(sessionId));
6261 chainCreated = true;
6262 }
Steve Block3856b092011-10-20 11:56:00 +01006263 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006264
6265 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006266 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07006267 this, effect->desc().name, chain.get());
6268 return BAD_VALUE;
6269 }
6270
6271 status_t status = chain->addEffect_l(effect);
6272 if (status != NO_ERROR) {
6273 if (chainCreated) {
6274 removeEffectChain_l(chain);
6275 }
6276 return status;
6277 }
6278
6279 effect->setDevice(mDevice);
6280 effect->setMode(mAudioFlinger->getMode());
6281 return NO_ERROR;
6282}
6283
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006284void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07006285
Steve Block3856b092011-10-20 11:56:00 +01006286 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006287 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07006288 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6289 detachAuxEffect_l(effect->id());
6290 }
6291
6292 sp<EffectChain> chain = effect->chain().promote();
6293 if (chain != 0) {
6294 // remove effect chain if removing last effect
6295 if (chain->removeEffect_l(effect) == 0) {
6296 removeEffectChain_l(chain);
6297 }
6298 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00006299 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006300 }
6301}
6302
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006303void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006304 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006305{
6306 effectChains = mEffectChains;
6307 for (size_t i = 0; i < mEffectChains.size(); i++) {
6308 mEffectChains[i]->lock();
6309 }
6310}
6311
6312void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006313 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006314{
6315 for (size_t i = 0; i < effectChains.size(); i++) {
6316 effectChains[i]->unlock();
6317 }
6318}
6319
6320sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6321{
6322 Mutex::Autolock _l(mLock);
6323 return getEffectChain_l(sessionId);
6324}
6325
6326sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6327{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006328 size_t size = mEffectChains.size();
6329 for (size_t i = 0; i < size; i++) {
6330 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08006331 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006332 }
6333 }
Glenn Kasten090f0192012-01-30 13:00:02 -08006334 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006335}
6336
Glenn Kastenf78aee72012-01-04 11:00:47 -08006337void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006338{
6339 Mutex::Autolock _l(mLock);
6340 size_t size = mEffectChains.size();
6341 for (size_t i = 0; i < size; i++) {
6342 mEffectChains[i]->setMode_l(mode);
6343 }
6344}
6345
6346void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006347 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08006348 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07006349
Mathias Agopian65ab4712010-07-14 17:59:35 -07006350 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006351 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006352 // delete the effect module if removing last handle on it
6353 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006354 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006355 removeEffect_l(effect);
6356 AudioSystem::unregisterEffect(effect->id());
6357 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006358 }
6359}
6360
6361status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6362{
6363 int session = chain->sessionId();
6364 int16_t *buffer = mMixBuffer;
6365 bool ownsBuffer = false;
6366
Steve Block3856b092011-10-20 11:56:00 +01006367 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006368 if (session > 0) {
6369 // Only one effect chain can be present in direct output thread and it uses
6370 // the mix buffer as input
6371 if (mType != DIRECT) {
6372 size_t numSamples = mFrameCount * mChannelCount;
6373 buffer = new int16_t[numSamples];
6374 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01006375 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006376 ownsBuffer = true;
6377 }
6378
6379 // Attach all tracks with same session ID to this chain.
6380 for (size_t i = 0; i < mTracks.size(); ++i) {
6381 sp<Track> track = mTracks[i];
6382 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006383 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006384 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006385 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006386 }
6387 }
6388
6389 // indicate all active tracks in the chain
6390 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6391 sp<Track> track = mActiveTracks[i].promote();
6392 if (track == 0) continue;
6393 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006394 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07006395 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006396 }
6397 }
6398 }
6399
6400 chain->setInBuffer(buffer, ownsBuffer);
6401 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006402 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006403 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006404 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6405 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006406 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006407 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6408 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006409 // Effect chain for other sessions are inserted at beginning of effect
6410 // chains list to be processed before output mix effects. Relative order between other
6411 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006412 size_t size = mEffectChains.size();
6413 size_t i = 0;
6414 for (i = 0; i < size; i++) {
6415 if (mEffectChains[i]->sessionId() < session) break;
6416 }
6417 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006418 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006419
6420 return NO_ERROR;
6421}
6422
6423size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6424{
6425 int session = chain->sessionId();
6426
Steve Block3856b092011-10-20 11:56:00 +01006427 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006428
6429 for (size_t i = 0; i < mEffectChains.size(); i++) {
6430 if (chain == mEffectChains[i]) {
6431 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006432 // detach all active tracks from the chain
6433 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6434 sp<Track> track = mActiveTracks[i].promote();
6435 if (track == 0) continue;
6436 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006437 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006438 chain.get(), session);
6439 chain->decActiveTrackCnt();
6440 }
6441 }
6442
Mathias Agopian65ab4712010-07-14 17:59:35 -07006443 // detach all tracks with same session ID from this chain
6444 for (size_t i = 0; i < mTracks.size(); ++i) {
6445 sp<Track> track = mTracks[i];
6446 if (session == track->sessionId()) {
6447 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006448 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006449 }
6450 }
Eric Laurentde070132010-07-13 04:45:46 -07006451 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006452 }
6453 }
6454 return mEffectChains.size();
6455}
6456
Eric Laurentde070132010-07-13 04:45:46 -07006457status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6458 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006459{
6460 Mutex::Autolock _l(mLock);
6461 return attachAuxEffect_l(track, EffectId);
6462}
6463
Eric Laurentde070132010-07-13 04:45:46 -07006464status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6465 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006466{
6467 status_t status = NO_ERROR;
6468
6469 if (EffectId == 0) {
6470 track->setAuxBuffer(0, NULL);
6471 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006472 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6473 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006474 if (effect != 0) {
6475 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6476 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6477 } else {
6478 status = INVALID_OPERATION;
6479 }
6480 } else {
6481 status = BAD_VALUE;
6482 }
6483 }
6484 return status;
6485}
6486
6487void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6488{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006489 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006490 sp<Track> track = mTracks[i];
6491 if (track->auxEffectId() == effectId) {
6492 attachAuxEffect_l(track, 0);
6493 }
6494 }
6495}
6496
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006497status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6498{
6499 // only one chain per input thread
6500 if (mEffectChains.size() != 0) {
6501 return INVALID_OPERATION;
6502 }
Steve Block3856b092011-10-20 11:56:00 +01006503 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006504
6505 chain->setInBuffer(NULL);
6506 chain->setOutBuffer(NULL);
6507
Eric Laurent59255e42011-07-27 19:49:51 -07006508 checkSuspendOnAddEffectChain_l(chain);
6509
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006510 mEffectChains.add(chain);
6511
6512 return NO_ERROR;
6513}
6514
6515size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6516{
Steve Block3856b092011-10-20 11:56:00 +01006517 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006518 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006519 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6520 chain.get(), mEffectChains.size(), this);
6521 if (mEffectChains.size() == 1) {
6522 mEffectChains.removeAt(0);
6523 }
6524 return 0;
6525}
6526
Mathias Agopian65ab4712010-07-14 17:59:35 -07006527// ----------------------------------------------------------------------------
6528// EffectModule implementation
6529// ----------------------------------------------------------------------------
6530
6531#undef LOG_TAG
6532#define LOG_TAG "AudioFlinger::EffectModule"
6533
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006534AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006535 const wp<AudioFlinger::EffectChain>& chain,
6536 effect_descriptor_t *desc,
6537 int id,
6538 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006539 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006540 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006541{
Steve Block3856b092011-10-20 11:56:00 +01006542 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006543 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006544 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006545 return;
6546 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006547
6548 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6549
6550 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006551 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006552
6553 if (mStatus != NO_ERROR) {
6554 return;
6555 }
6556 lStatus = init();
6557 if (lStatus < 0) {
6558 mStatus = lStatus;
6559 goto Error;
6560 }
6561
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006562 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6563 mPinned = true;
6564 }
Steve Block3856b092011-10-20 11:56:00 +01006565 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006566 return;
6567Error:
6568 EffectRelease(mEffectInterface);
6569 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006570 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006571}
6572
6573AudioFlinger::EffectModule::~EffectModule()
6574{
Steve Block3856b092011-10-20 11:56:00 +01006575 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006576 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006577 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6578 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6579 sp<ThreadBase> thread = mThread.promote();
6580 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006581 audio_stream_t *stream = thread->stream();
6582 if (stream != NULL) {
6583 stream->remove_audio_effect(stream, mEffectInterface);
6584 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006585 }
6586 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006587 // release effect engine
6588 EffectRelease(mEffectInterface);
6589 }
6590}
6591
Glenn Kasten435dbe62012-01-30 10:15:48 -08006592status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006593{
6594 status_t status;
6595
6596 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006597 int priority = handle->priority();
6598 size_t size = mHandles.size();
6599 sp<EffectHandle> h;
6600 size_t i;
6601 for (i = 0; i < size; i++) {
6602 h = mHandles[i].promote();
6603 if (h == 0) continue;
6604 if (h->priority() <= priority) break;
6605 }
6606 // if inserted in first place, move effect control from previous owner to this handle
6607 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006608 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006609 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006610 enabled = h->enabled();
6611 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006612 }
Eric Laurent59255e42011-07-27 19:49:51 -07006613 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006614 status = NO_ERROR;
6615 } else {
6616 status = ALREADY_EXISTS;
6617 }
Steve Block3856b092011-10-20 11:56:00 +01006618 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006619 mHandles.insertAt(handle, i);
6620 return status;
6621}
6622
6623size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6624{
6625 Mutex::Autolock _l(mLock);
6626 size_t size = mHandles.size();
6627 size_t i;
6628 for (i = 0; i < size; i++) {
6629 if (mHandles[i] == handle) break;
6630 }
6631 if (i == size) {
6632 return size;
6633 }
Steve Block3856b092011-10-20 11:56:00 +01006634 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006635
6636 bool enabled = false;
6637 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006638 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006639 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006640 enabled = hdl->enabled();
6641 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006642 mHandles.removeAt(i);
6643 size = mHandles.size();
6644 // if removed from first place, move effect control from this handle to next in line
6645 if (i == 0 && size != 0) {
6646 sp<EffectHandle> h = mHandles[0].promote();
6647 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006648 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006649 }
6650 }
6651
Eric Laurentec437d82011-07-26 20:54:46 -07006652 // Prevent calls to process() and other functions on effect interface from now on.
6653 // The effect engine will be released by the destructor when the last strong reference on
6654 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006655 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006656 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006657 }
6658
Mathias Agopian65ab4712010-07-14 17:59:35 -07006659 return size;
6660}
6661
Eric Laurent59255e42011-07-27 19:49:51 -07006662sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6663{
6664 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08006665 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07006666}
6667
Glenn Kasten58123c32012-02-03 10:32:24 -08006668void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006669{
Glenn Kasten90bebef2012-01-27 15:24:38 -08006670 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006671 // keep a strong reference on this EffectModule to avoid calling the
6672 // destructor before we exit
6673 sp<EffectModule> keep(this);
6674 {
6675 sp<ThreadBase> thread = mThread.promote();
6676 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006677 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006678 }
6679 }
6680}
6681
6682void AudioFlinger::EffectModule::updateState() {
6683 Mutex::Autolock _l(mLock);
6684
6685 switch (mState) {
6686 case RESTART:
6687 reset_l();
6688 // FALL THROUGH
6689
6690 case STARTING:
6691 // clear auxiliary effect input buffer for next accumulation
6692 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6693 memset(mConfig.inputCfg.buffer.raw,
6694 0,
6695 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6696 }
6697 start_l();
6698 mState = ACTIVE;
6699 break;
6700 case STOPPING:
6701 stop_l();
6702 mDisableWaitCnt = mMaxDisableWaitCnt;
6703 mState = STOPPED;
6704 break;
6705 case STOPPED:
6706 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6707 // turn off sequence.
6708 if (--mDisableWaitCnt == 0) {
6709 reset_l();
6710 mState = IDLE;
6711 }
6712 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006713 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006714 break;
6715 }
6716}
6717
6718void AudioFlinger::EffectModule::process()
6719{
6720 Mutex::Autolock _l(mLock);
6721
Eric Laurentec437d82011-07-26 20:54:46 -07006722 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006723 mConfig.inputCfg.buffer.raw == NULL ||
6724 mConfig.outputCfg.buffer.raw == NULL) {
6725 return;
6726 }
6727
Eric Laurent8f45bd72010-08-31 13:50:07 -07006728 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006729 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6730 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006731 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006732 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006733 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006734 }
6735
6736 // do the actual processing in the effect engine
6737 int ret = (*mEffectInterface)->process(mEffectInterface,
6738 &mConfig.inputCfg.buffer,
6739 &mConfig.outputCfg.buffer);
6740
6741 // force transition to IDLE state when engine is ready
6742 if (mState == STOPPED && ret == -ENODATA) {
6743 mDisableWaitCnt = 1;
6744 }
6745
6746 // clear auxiliary effect input buffer for next accumulation
6747 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006748 memset(mConfig.inputCfg.buffer.raw, 0,
6749 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006750 }
6751 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006752 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6753 // If an insert effect is idle and input buffer is different from output buffer,
6754 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006755 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006756 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006757 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6758 int16_t *in = mConfig.inputCfg.buffer.s16;
6759 int16_t *out = mConfig.outputCfg.buffer.s16;
6760 for (size_t i = 0; i < frameCnt; i++) {
6761 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006762 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006763 }
6764 }
6765}
6766
6767void AudioFlinger::EffectModule::reset_l()
6768{
6769 if (mEffectInterface == NULL) {
6770 return;
6771 }
6772 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6773}
6774
6775status_t AudioFlinger::EffectModule::configure()
6776{
6777 uint32_t channels;
6778 if (mEffectInterface == NULL) {
6779 return NO_INIT;
6780 }
6781
6782 sp<ThreadBase> thread = mThread.promote();
6783 if (thread == 0) {
6784 return DEAD_OBJECT;
6785 }
6786
6787 // TODO: handle configuration of effects replacing track process
6788 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006789 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006790 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006791 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006792 }
6793
6794 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006795 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006796 } else {
6797 mConfig.inputCfg.channels = channels;
6798 }
6799 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006800 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6801 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006802 mConfig.inputCfg.samplingRate = thread->sampleRate();
6803 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6804 mConfig.inputCfg.bufferProvider.cookie = NULL;
6805 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6806 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6807 mConfig.outputCfg.bufferProvider.cookie = NULL;
6808 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6809 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6810 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6811 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006812 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006813 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006814 // - in other sessions:
6815 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6816 // other effect: overwrites output buffer: input buffer == output buffer
6817 // Auxiliary effect:
6818 // accumulates in output buffer: input buffer != output buffer
6819 // Therefore: accumulate <=> input buffer != output buffer
6820 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6821 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6822 } else {
6823 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6824 }
6825 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6826 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6827 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6828 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6829
Steve Block3856b092011-10-20 11:56:00 +01006830 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006831 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6832
Mathias Agopian65ab4712010-07-14 17:59:35 -07006833 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006834 uint32_t size = sizeof(int);
6835 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006836 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006837 sizeof(effect_config_t),
6838 &mConfig,
6839 &size,
6840 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006841 if (status == 0) {
6842 status = cmdStatus;
6843 }
6844
6845 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6846 (1000 * mConfig.outputCfg.buffer.frameCount);
6847
6848 return status;
6849}
6850
6851status_t AudioFlinger::EffectModule::init()
6852{
6853 Mutex::Autolock _l(mLock);
6854 if (mEffectInterface == NULL) {
6855 return NO_INIT;
6856 }
6857 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006858 uint32_t size = sizeof(status_t);
6859 status_t status = (*mEffectInterface)->command(mEffectInterface,
6860 EFFECT_CMD_INIT,
6861 0,
6862 NULL,
6863 &size,
6864 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006865 if (status == 0) {
6866 status = cmdStatus;
6867 }
6868 return status;
6869}
6870
Eric Laurentec35a142011-10-05 17:42:25 -07006871status_t AudioFlinger::EffectModule::start()
6872{
6873 Mutex::Autolock _l(mLock);
6874 return start_l();
6875}
6876
Mathias Agopian65ab4712010-07-14 17:59:35 -07006877status_t AudioFlinger::EffectModule::start_l()
6878{
6879 if (mEffectInterface == NULL) {
6880 return NO_INIT;
6881 }
6882 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006883 uint32_t size = sizeof(status_t);
6884 status_t status = (*mEffectInterface)->command(mEffectInterface,
6885 EFFECT_CMD_ENABLE,
6886 0,
6887 NULL,
6888 &size,
6889 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006890 if (status == 0) {
6891 status = cmdStatus;
6892 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006893 if (status == 0 &&
6894 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6895 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6896 sp<ThreadBase> thread = mThread.promote();
6897 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006898 audio_stream_t *stream = thread->stream();
6899 if (stream != NULL) {
6900 stream->add_audio_effect(stream, mEffectInterface);
6901 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006902 }
6903 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006904 return status;
6905}
6906
Eric Laurentec437d82011-07-26 20:54:46 -07006907status_t AudioFlinger::EffectModule::stop()
6908{
6909 Mutex::Autolock _l(mLock);
6910 return stop_l();
6911}
6912
Mathias Agopian65ab4712010-07-14 17:59:35 -07006913status_t AudioFlinger::EffectModule::stop_l()
6914{
6915 if (mEffectInterface == NULL) {
6916 return NO_INIT;
6917 }
6918 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006919 uint32_t size = sizeof(status_t);
6920 status_t status = (*mEffectInterface)->command(mEffectInterface,
6921 EFFECT_CMD_DISABLE,
6922 0,
6923 NULL,
6924 &size,
6925 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006926 if (status == 0) {
6927 status = cmdStatus;
6928 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006929 if (status == 0 &&
6930 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6931 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6932 sp<ThreadBase> thread = mThread.promote();
6933 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006934 audio_stream_t *stream = thread->stream();
6935 if (stream != NULL) {
6936 stream->remove_audio_effect(stream, mEffectInterface);
6937 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006938 }
6939 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006940 return status;
6941}
6942
Eric Laurent25f43952010-07-28 05:40:18 -07006943status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6944 uint32_t cmdSize,
6945 void *pCmdData,
6946 uint32_t *replySize,
6947 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006948{
6949 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006950// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006951
Eric Laurentec437d82011-07-26 20:54:46 -07006952 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006953 return NO_INIT;
6954 }
Eric Laurent25f43952010-07-28 05:40:18 -07006955 status_t status = (*mEffectInterface)->command(mEffectInterface,
6956 cmdCode,
6957 cmdSize,
6958 pCmdData,
6959 replySize,
6960 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006961 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006962 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006963 for (size_t i = 1; i < mHandles.size(); i++) {
6964 sp<EffectHandle> h = mHandles[i].promote();
6965 if (h != 0) {
6966 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6967 }
6968 }
6969 }
6970 return status;
6971}
6972
6973status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6974{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006975
Mathias Agopian65ab4712010-07-14 17:59:35 -07006976 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006977 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006978
6979 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006980 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6981 if (enabled && status != NO_ERROR) {
6982 return status;
6983 }
6984
Mathias Agopian65ab4712010-07-14 17:59:35 -07006985 switch (mState) {
6986 // going from disabled to enabled
6987 case IDLE:
6988 mState = STARTING;
6989 break;
6990 case STOPPED:
6991 mState = RESTART;
6992 break;
6993 case STOPPING:
6994 mState = ACTIVE;
6995 break;
6996
6997 // going from enabled to disabled
6998 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006999 mState = STOPPED;
7000 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007001 case STARTING:
7002 mState = IDLE;
7003 break;
7004 case ACTIVE:
7005 mState = STOPPING;
7006 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007007 case DESTROYED:
7008 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007009 }
7010 for (size_t i = 1; i < mHandles.size(); i++) {
7011 sp<EffectHandle> h = mHandles[i].promote();
7012 if (h != 0) {
7013 h->setEnabled(enabled);
7014 }
7015 }
7016 }
7017 return NO_ERROR;
7018}
7019
Glenn Kastenc59c0042012-02-02 14:06:11 -08007020bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007021{
7022 switch (mState) {
7023 case RESTART:
7024 case STARTING:
7025 case ACTIVE:
7026 return true;
7027 case IDLE:
7028 case STOPPING:
7029 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07007030 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07007031 default:
7032 return false;
7033 }
7034}
7035
Glenn Kastenc59c0042012-02-02 14:06:11 -08007036bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07007037{
7038 switch (mState) {
7039 case RESTART:
7040 case ACTIVE:
7041 case STOPPING:
7042 case STOPPED:
7043 return true;
7044 case IDLE:
7045 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07007046 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007047 default:
7048 return false;
7049 }
7050}
7051
Mathias Agopian65ab4712010-07-14 17:59:35 -07007052status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7053{
7054 Mutex::Autolock _l(mLock);
7055 status_t status = NO_ERROR;
7056
7057 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7058 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07007059 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07007060 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7061 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007062 status_t cmdStatus;
7063 uint32_t volume[2];
7064 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07007065 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007066 volume[0] = *left;
7067 volume[1] = *right;
7068 if (controller) {
7069 pVolume = volume;
7070 }
Eric Laurent25f43952010-07-28 05:40:18 -07007071 status = (*mEffectInterface)->command(mEffectInterface,
7072 EFFECT_CMD_SET_VOLUME,
7073 size,
7074 volume,
7075 &size,
7076 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007077 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7078 *left = volume[0];
7079 *right = volume[1];
7080 }
7081 }
7082 return status;
7083}
7084
7085status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7086{
7087 Mutex::Autolock _l(mLock);
7088 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007089 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7090 // audio pre processing modules on RecordThread can receive both output and
7091 // input device indication in the same call
7092 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7093 if (dev) {
7094 status_t cmdStatus;
7095 uint32_t size = sizeof(status_t);
7096
7097 status = (*mEffectInterface)->command(mEffectInterface,
7098 EFFECT_CMD_SET_DEVICE,
7099 sizeof(uint32_t),
7100 &dev,
7101 &size,
7102 &cmdStatus);
7103 if (status == NO_ERROR) {
7104 status = cmdStatus;
7105 }
7106 }
7107 dev = device & AUDIO_DEVICE_IN_ALL;
7108 if (dev) {
7109 status_t cmdStatus;
7110 uint32_t size = sizeof(status_t);
7111
7112 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7113 EFFECT_CMD_SET_INPUT_DEVICE,
7114 sizeof(uint32_t),
7115 &dev,
7116 &size,
7117 &cmdStatus);
7118 if (status2 == NO_ERROR) {
7119 status2 = cmdStatus;
7120 }
7121 if (status == NO_ERROR) {
7122 status = status2;
7123 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007124 }
7125 }
7126 return status;
7127}
7128
Glenn Kastenf78aee72012-01-04 11:00:47 -08007129status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007130{
7131 Mutex::Autolock _l(mLock);
7132 status_t status = NO_ERROR;
7133 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007134 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007135 uint32_t size = sizeof(status_t);
7136 status = (*mEffectInterface)->command(mEffectInterface,
7137 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08007138 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07007139 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07007140 &size,
7141 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007142 if (status == NO_ERROR) {
7143 status = cmdStatus;
7144 }
7145 }
7146 return status;
7147}
7148
Eric Laurent59255e42011-07-27 19:49:51 -07007149void AudioFlinger::EffectModule::setSuspended(bool suspended)
7150{
7151 Mutex::Autolock _l(mLock);
7152 mSuspended = suspended;
7153}
Glenn Kastena3a85482012-01-04 11:01:11 -08007154
7155bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07007156{
7157 Mutex::Autolock _l(mLock);
7158 return mSuspended;
7159}
7160
Mathias Agopian65ab4712010-07-14 17:59:35 -07007161status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7162{
7163 const size_t SIZE = 256;
7164 char buffer[SIZE];
7165 String8 result;
7166
7167 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7168 result.append(buffer);
7169
7170 bool locked = tryLock(mLock);
7171 // failed to lock - AudioFlinger is probably deadlocked
7172 if (!locked) {
7173 result.append("\t\tCould not lock Fx mutex:\n");
7174 }
7175
7176 result.append("\t\tSession Status State Engine:\n");
7177 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7178 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7179 result.append(buffer);
7180
7181 result.append("\t\tDescriptor:\n");
7182 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7183 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7184 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7185 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7186 result.append(buffer);
7187 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7188 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7189 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7190 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7191 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07007192 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007193 mDescriptor.apiVersion,
7194 mDescriptor.flags);
7195 result.append(buffer);
7196 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7197 mDescriptor.name);
7198 result.append(buffer);
7199 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7200 mDescriptor.implementor);
7201 result.append(buffer);
7202
7203 result.append("\t\t- Input configuration:\n");
7204 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7205 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7206 (uint32_t)mConfig.inputCfg.buffer.raw,
7207 mConfig.inputCfg.buffer.frameCount,
7208 mConfig.inputCfg.samplingRate,
7209 mConfig.inputCfg.channels,
7210 mConfig.inputCfg.format);
7211 result.append(buffer);
7212
7213 result.append("\t\t- Output configuration:\n");
7214 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7215 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7216 (uint32_t)mConfig.outputCfg.buffer.raw,
7217 mConfig.outputCfg.buffer.frameCount,
7218 mConfig.outputCfg.samplingRate,
7219 mConfig.outputCfg.channels,
7220 mConfig.outputCfg.format);
7221 result.append(buffer);
7222
7223 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7224 result.append(buffer);
7225 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7226 for (size_t i = 0; i < mHandles.size(); ++i) {
7227 sp<EffectHandle> handle = mHandles[i].promote();
7228 if (handle != 0) {
7229 handle->dump(buffer, SIZE);
7230 result.append(buffer);
7231 }
7232 }
7233
7234 result.append("\n");
7235
7236 write(fd, result.string(), result.length());
7237
7238 if (locked) {
7239 mLock.unlock();
7240 }
7241
7242 return NO_ERROR;
7243}
7244
7245// ----------------------------------------------------------------------------
7246// EffectHandle implementation
7247// ----------------------------------------------------------------------------
7248
7249#undef LOG_TAG
7250#define LOG_TAG "AudioFlinger::EffectHandle"
7251
7252AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7253 const sp<AudioFlinger::Client>& client,
7254 const sp<IEffectClient>& effectClient,
7255 int32_t priority)
7256 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007257 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007258 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007259{
Steve Block3856b092011-10-20 11:56:00 +01007260 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007261
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007262 if (client == 0) {
7263 return;
7264 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007265 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7266 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7267 if (mCblkMemory != 0) {
7268 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7269
Glenn Kastena0d68332012-01-27 16:47:15 -08007270 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007271 new(mCblk) effect_param_cblk_t();
7272 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007273 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007274 } else {
Steve Block29357bc2012-01-06 19:20:56 +00007275 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007276 return;
7277 }
7278}
7279
7280AudioFlinger::EffectHandle::~EffectHandle()
7281{
Steve Block3856b092011-10-20 11:56:00 +01007282 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007283 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01007284 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007285}
7286
7287status_t AudioFlinger::EffectHandle::enable()
7288{
Steve Block3856b092011-10-20 11:56:00 +01007289 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007290 if (!mHasControl) return INVALID_OPERATION;
7291 if (mEffect == 0) return DEAD_OBJECT;
7292
Eric Laurentdb7c0792011-08-10 10:37:50 -07007293 if (mEnabled) {
7294 return NO_ERROR;
7295 }
7296
Eric Laurent59255e42011-07-27 19:49:51 -07007297 mEnabled = true;
7298
7299 sp<ThreadBase> thread = mEffect->thread().promote();
7300 if (thread != 0) {
7301 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7302 }
7303
7304 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7305 if (mEffect->suspended()) {
7306 return NO_ERROR;
7307 }
7308
Eric Laurentdb7c0792011-08-10 10:37:50 -07007309 status_t status = mEffect->setEnabled(true);
7310 if (status != NO_ERROR) {
7311 if (thread != 0) {
7312 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7313 }
7314 mEnabled = false;
7315 }
7316 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007317}
7318
7319status_t AudioFlinger::EffectHandle::disable()
7320{
Steve Block3856b092011-10-20 11:56:00 +01007321 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007322 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07007323 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007324
Eric Laurentdb7c0792011-08-10 10:37:50 -07007325 if (!mEnabled) {
7326 return NO_ERROR;
7327 }
Eric Laurent59255e42011-07-27 19:49:51 -07007328 mEnabled = false;
7329
7330 if (mEffect->suspended()) {
7331 return NO_ERROR;
7332 }
7333
7334 status_t status = mEffect->setEnabled(false);
7335
7336 sp<ThreadBase> thread = mEffect->thread().promote();
7337 if (thread != 0) {
7338 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7339 }
7340
7341 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007342}
7343
7344void AudioFlinger::EffectHandle::disconnect()
7345{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007346 disconnect(true);
7347}
7348
Glenn Kasten58123c32012-02-03 10:32:24 -08007349void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007350{
Glenn Kasten58123c32012-02-03 10:32:24 -08007351 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007352 if (mEffect == 0) {
7353 return;
7354 }
Glenn Kasten58123c32012-02-03 10:32:24 -08007355 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07007356
Eric Laurenta85a74a2011-10-19 11:44:54 -07007357 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007358 sp<ThreadBase> thread = mEffect->thread().promote();
7359 if (thread != 0) {
7360 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7361 }
Eric Laurent59255e42011-07-27 19:49:51 -07007362 }
7363
Mathias Agopian65ab4712010-07-14 17:59:35 -07007364 // release sp on module => module destructor can be called now
7365 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007366 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08007367 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08007368 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007369 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7370 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08007371 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007372 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07007373 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7374 mClient.clear();
7375 }
7376}
7377
Eric Laurent25f43952010-07-28 05:40:18 -07007378status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7379 uint32_t cmdSize,
7380 void *pCmdData,
7381 uint32_t *replySize,
7382 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007383{
Steve Block3856b092011-10-20 11:56:00 +01007384// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07007385// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007386
7387 // only get parameter command is permitted for applications not controlling the effect
7388 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7389 return INVALID_OPERATION;
7390 }
7391 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007392 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007393
7394 // handle commands that are not forwarded transparently to effect engine
7395 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7396 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7397 // no risk to block the whole media server process or mixer threads is we are stuck here
7398 Mutex::Autolock _l(mCblk->lock);
7399 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7400 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7401 mCblk->serverIndex = 0;
7402 mCblk->clientIndex = 0;
7403 return BAD_VALUE;
7404 }
7405 status_t status = NO_ERROR;
7406 while (mCblk->serverIndex < mCblk->clientIndex) {
7407 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007408 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007409 int *p = (int *)(mBuffer + mCblk->serverIndex);
7410 int size = *p++;
7411 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007412 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007413 break;
7414 }
7415 effect_param_t *param = (effect_param_t *)p;
7416 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007417 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007418 mCblk->serverIndex += size;
7419 continue;
7420 }
Eric Laurent25f43952010-07-28 05:40:18 -07007421 uint32_t psize = sizeof(effect_param_t) +
7422 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7423 param->vsize;
7424 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7425 psize,
7426 p,
7427 &rsize,
7428 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007429 // stop at first error encountered
7430 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007431 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007432 *(int *)pReplyData = reply;
7433 break;
7434 } else if (reply != NO_ERROR) {
7435 *(int *)pReplyData = reply;
7436 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007437 }
7438 mCblk->serverIndex += size;
7439 }
7440 mCblk->serverIndex = 0;
7441 mCblk->clientIndex = 0;
7442 return status;
7443 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007444 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007445 return enable();
7446 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007447 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007448 return disable();
7449 }
7450
7451 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7452}
7453
Eric Laurent59255e42011-07-27 19:49:51 -07007454void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007455{
Steve Block3856b092011-10-20 11:56:00 +01007456 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007457
7458 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007459 mEnabled = enabled;
7460
Mathias Agopian65ab4712010-07-14 17:59:35 -07007461 if (signal && mEffectClient != 0) {
7462 mEffectClient->controlStatusChanged(hasControl);
7463 }
7464}
7465
Eric Laurent25f43952010-07-28 05:40:18 -07007466void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7467 uint32_t cmdSize,
7468 void *pCmdData,
7469 uint32_t replySize,
7470 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007471{
7472 if (mEffectClient != 0) {
7473 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7474 }
7475}
7476
7477
7478
7479void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7480{
7481 if (mEffectClient != 0) {
7482 mEffectClient->enableStatusChanged(enabled);
7483 }
7484}
7485
7486status_t AudioFlinger::EffectHandle::onTransact(
7487 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7488{
7489 return BnEffect::onTransact(code, data, reply, flags);
7490}
7491
7492
7493void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7494{
Glenn Kastena0d68332012-01-27 16:47:15 -08007495 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007496
7497 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08007498 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007499 mPriority,
7500 mHasControl,
7501 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007502 mCblk ? mCblk->clientIndex : 0,
7503 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007504 );
7505
7506 if (locked) {
7507 mCblk->lock.unlock();
7508 }
7509}
7510
7511#undef LOG_TAG
7512#define LOG_TAG "AudioFlinger::EffectChain"
7513
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007514AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007515 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007516 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007517 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7518 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007519{
Dima Zavinfce7a472011-04-19 22:30:36 -07007520 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007521 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007522 return;
7523 }
7524 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7525 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007526}
7527
7528AudioFlinger::EffectChain::~EffectChain()
7529{
7530 if (mOwnInBuffer) {
7531 delete mInBuffer;
7532 }
7533
7534}
7535
Eric Laurent59255e42011-07-27 19:49:51 -07007536// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007537sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007538{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007539 size_t size = mEffects.size();
7540
7541 for (size_t i = 0; i < size; i++) {
7542 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007543 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007544 }
7545 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007546 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007547}
7548
Eric Laurent59255e42011-07-27 19:49:51 -07007549// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007550sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007551{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007552 size_t size = mEffects.size();
7553
7554 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007555 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7556 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007557 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007558 }
7559 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007560 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007561}
7562
Eric Laurent59255e42011-07-27 19:49:51 -07007563// getEffectFromType_l() must be called with ThreadBase::mLock held
7564sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7565 const effect_uuid_t *type)
7566{
Eric Laurent59255e42011-07-27 19:49:51 -07007567 size_t size = mEffects.size();
7568
7569 for (size_t i = 0; i < size; i++) {
7570 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007571 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007572 }
7573 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007574 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007575}
7576
Mathias Agopian65ab4712010-07-14 17:59:35 -07007577// Must be called with EffectChain::mLock locked
7578void AudioFlinger::EffectChain::process_l()
7579{
Eric Laurentdac69112010-09-28 14:09:57 -07007580 sp<ThreadBase> thread = mThread.promote();
7581 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007582 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007583 return;
7584 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007585 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7586 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007587 // always process effects unless no more tracks are on the session and the effect tail
7588 // has been rendered
7589 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007590 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007591 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007592
Eric Laurent544fe9b2011-11-11 15:42:52 -08007593 if (!tracksOnSession && mTailBufferCount == 0) {
7594 doProcess = false;
7595 }
7596
7597 if (activeTrackCnt() == 0) {
7598 // if no track is active and the effect tail has not been rendered,
7599 // the input buffer must be cleared here as the mixer process will not do it
7600 if (tracksOnSession || mTailBufferCount > 0) {
7601 size_t numSamples = thread->frameCount() * thread->channelCount();
7602 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7603 if (mTailBufferCount > 0) {
7604 mTailBufferCount--;
7605 }
7606 }
7607 }
Eric Laurentdac69112010-09-28 14:09:57 -07007608 }
7609
Mathias Agopian65ab4712010-07-14 17:59:35 -07007610 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007611 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007612 for (size_t i = 0; i < size; i++) {
7613 mEffects[i]->process();
7614 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007615 }
7616 for (size_t i = 0; i < size; i++) {
7617 mEffects[i]->updateState();
7618 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007619}
7620
Eric Laurentcab11242010-07-15 12:50:15 -07007621// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007622status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007623{
7624 effect_descriptor_t desc = effect->desc();
7625 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7626
7627 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007628 effect->setChain(this);
7629 sp<ThreadBase> thread = mThread.promote();
7630 if (thread == 0) {
7631 return NO_INIT;
7632 }
7633 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007634
7635 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7636 // Auxiliary effects are inserted at the beginning of mEffects vector as
7637 // they are processed first and accumulated in chain input buffer
7638 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007639
Mathias Agopian65ab4712010-07-14 17:59:35 -07007640 // the input buffer for auxiliary effect contains mono samples in
7641 // 32 bit format. This is to avoid saturation in AudoMixer
7642 // accumulation stage. Saturation is done in EffectModule::process() before
7643 // calling the process in effect engine
7644 size_t numSamples = thread->frameCount();
7645 int32_t *buffer = new int32_t[numSamples];
7646 memset(buffer, 0, numSamples * sizeof(int32_t));
7647 effect->setInBuffer((int16_t *)buffer);
7648 // auxiliary effects output samples to chain input buffer for further processing
7649 // by insert effects
7650 effect->setOutBuffer(mInBuffer);
7651 } else {
7652 // Insert effects are inserted at the end of mEffects vector as they are processed
7653 // after track and auxiliary effects.
7654 // Insert effect order as a function of indicated preference:
7655 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7656 // another effect is present
7657 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7658 // last effect claiming first position
7659 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7660 // first effect claiming last position
7661 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7662 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7663 // already present
7664
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007665 size_t size = mEffects.size();
7666 size_t idx_insert = size;
7667 ssize_t idx_insert_first = -1;
7668 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007669
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007670 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007671 effect_descriptor_t d = mEffects[i]->desc();
7672 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7673 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7674 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7675 // check invalid effect chaining combinations
7676 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7677 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007678 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007679 return INVALID_OPERATION;
7680 }
7681 // remember position of first insert effect and by default
7682 // select this as insert position for new effect
7683 if (idx_insert == size) {
7684 idx_insert = i;
7685 }
7686 // remember position of last insert effect claiming
7687 // first position
7688 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7689 idx_insert_first = i;
7690 }
7691 // remember position of first insert effect claiming
7692 // last position
7693 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7694 idx_insert_last == -1) {
7695 idx_insert_last = i;
7696 }
7697 }
7698 }
7699
7700 // modify idx_insert from first position if needed
7701 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7702 if (idx_insert_last != -1) {
7703 idx_insert = idx_insert_last;
7704 } else {
7705 idx_insert = size;
7706 }
7707 } else {
7708 if (idx_insert_first != -1) {
7709 idx_insert = idx_insert_first + 1;
7710 }
7711 }
7712
7713 // always read samples from chain input buffer
7714 effect->setInBuffer(mInBuffer);
7715
7716 // if last effect in the chain, output samples to chain
7717 // output buffer, otherwise to chain input buffer
7718 if (idx_insert == size) {
7719 if (idx_insert != 0) {
7720 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7721 mEffects[idx_insert-1]->configure();
7722 }
7723 effect->setOutBuffer(mOutBuffer);
7724 } else {
7725 effect->setOutBuffer(mInBuffer);
7726 }
7727 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007728
Steve Block3856b092011-10-20 11:56:00 +01007729 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007730 }
7731 effect->configure();
7732 return NO_ERROR;
7733}
7734
Eric Laurentcab11242010-07-15 12:50:15 -07007735// removeEffect_l() must be called with PlaybackThread::mLock held
7736size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007737{
7738 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007739 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007740 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7741
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007742 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007743 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007744 // calling stop here will remove pre-processing effect from the audio HAL.
7745 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7746 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007747 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7748 mEffects[i]->state() == EffectModule::STOPPING) {
7749 mEffects[i]->stop();
7750 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007751 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7752 delete[] effect->inBuffer();
7753 } else {
7754 if (i == size - 1 && i != 0) {
7755 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7756 mEffects[i - 1]->configure();
7757 }
7758 }
7759 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007760 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007761 break;
7762 }
7763 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007764
7765 return mEffects.size();
7766}
7767
Eric Laurentcab11242010-07-15 12:50:15 -07007768// setDevice_l() must be called with PlaybackThread::mLock held
7769void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007770{
7771 size_t size = mEffects.size();
7772 for (size_t i = 0; i < size; i++) {
7773 mEffects[i]->setDevice(device);
7774 }
7775}
7776
Eric Laurentcab11242010-07-15 12:50:15 -07007777// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007778void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007779{
7780 size_t size = mEffects.size();
7781 for (size_t i = 0; i < size; i++) {
7782 mEffects[i]->setMode(mode);
7783 }
7784}
7785
Eric Laurentcab11242010-07-15 12:50:15 -07007786// setVolume_l() must be called with PlaybackThread::mLock held
7787bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007788{
7789 uint32_t newLeft = *left;
7790 uint32_t newRight = *right;
7791 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007792 int ctrlIdx = -1;
7793 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007794
Eric Laurentcab11242010-07-15 12:50:15 -07007795 // first update volume controller
7796 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007797 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007798 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7799 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007800 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007801 break;
7802 }
7803 }
7804
7805 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007806 if (hasControl) {
7807 *left = mNewLeftVolume;
7808 *right = mNewRightVolume;
7809 }
7810 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007811 }
7812
7813 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007814 mLeftVolume = newLeft;
7815 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007816
7817 // second get volume update from volume controller
7818 if (ctrlIdx >= 0) {
7819 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007820 mNewLeftVolume = newLeft;
7821 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007822 }
7823 // then indicate volume to all other effects in chain.
7824 // Pass altered volume to effects before volume controller
7825 // and requested volume to effects after controller
7826 uint32_t lVol = newLeft;
7827 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007828
Mathias Agopian65ab4712010-07-14 17:59:35 -07007829 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007830 if ((int)i == ctrlIdx) continue;
7831 // this also works for ctrlIdx == -1 when there is no volume controller
7832 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007833 lVol = *left;
7834 rVol = *right;
7835 }
7836 mEffects[i]->setVolume(&lVol, &rVol, false);
7837 }
7838 *left = newLeft;
7839 *right = newRight;
7840
7841 return hasControl;
7842}
7843
Mathias Agopian65ab4712010-07-14 17:59:35 -07007844status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7845{
7846 const size_t SIZE = 256;
7847 char buffer[SIZE];
7848 String8 result;
7849
7850 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7851 result.append(buffer);
7852
7853 bool locked = tryLock(mLock);
7854 // failed to lock - AudioFlinger is probably deadlocked
7855 if (!locked) {
7856 result.append("\tCould not lock mutex:\n");
7857 }
7858
Eric Laurentcab11242010-07-15 12:50:15 -07007859 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7860 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007861 mEffects.size(),
7862 (uint32_t)mInBuffer,
7863 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007864 mActiveTrackCnt);
7865 result.append(buffer);
7866 write(fd, result.string(), result.size());
7867
7868 for (size_t i = 0; i < mEffects.size(); ++i) {
7869 sp<EffectModule> effect = mEffects[i];
7870 if (effect != 0) {
7871 effect->dump(fd, args);
7872 }
7873 }
7874
7875 if (locked) {
7876 mLock.unlock();
7877 }
7878
7879 return NO_ERROR;
7880}
7881
Eric Laurent59255e42011-07-27 19:49:51 -07007882// must be called with ThreadBase::mLock held
7883void AudioFlinger::EffectChain::setEffectSuspended_l(
7884 const effect_uuid_t *type, bool suspend)
7885{
7886 sp<SuspendedEffectDesc> desc;
7887 // use effect type UUID timelow as key as there is no real risk of identical
7888 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007889 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007890 if (suspend) {
7891 if (index >= 0) {
7892 desc = mSuspendedEffects.valueAt(index);
7893 } else {
7894 desc = new SuspendedEffectDesc();
7895 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7896 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007897 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007898 }
7899 if (desc->mRefCount++ == 0) {
7900 sp<EffectModule> effect = getEffectIfEnabled(type);
7901 if (effect != 0) {
7902 desc->mEffect = effect;
7903 effect->setSuspended(true);
7904 effect->setEnabled(false);
7905 }
7906 }
7907 } else {
7908 if (index < 0) {
7909 return;
7910 }
7911 desc = mSuspendedEffects.valueAt(index);
7912 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007913 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007914 desc->mRefCount = 1;
7915 }
7916 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007917 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007918 if (desc->mEffect != 0) {
7919 sp<EffectModule> effect = desc->mEffect.promote();
7920 if (effect != 0) {
7921 effect->setSuspended(false);
7922 sp<EffectHandle> handle = effect->controlHandle();
7923 if (handle != 0) {
7924 effect->setEnabled(handle->enabled());
7925 }
7926 }
7927 desc->mEffect.clear();
7928 }
7929 mSuspendedEffects.removeItemsAt(index);
7930 }
7931 }
7932}
7933
7934// must be called with ThreadBase::mLock held
7935void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7936{
7937 sp<SuspendedEffectDesc> desc;
7938
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007939 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07007940 if (suspend) {
7941 if (index >= 0) {
7942 desc = mSuspendedEffects.valueAt(index);
7943 } else {
7944 desc = new SuspendedEffectDesc();
7945 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007946 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007947 }
7948 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08007949 Vector< sp<EffectModule> > effects;
7950 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07007951 for (size_t i = 0; i < effects.size(); i++) {
7952 setEffectSuspended_l(&effects[i]->desc().type, true);
7953 }
7954 }
7955 } else {
7956 if (index < 0) {
7957 return;
7958 }
7959 desc = mSuspendedEffects.valueAt(index);
7960 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007961 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007962 desc->mRefCount = 1;
7963 }
7964 if (--desc->mRefCount == 0) {
7965 Vector<const effect_uuid_t *> types;
7966 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7967 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7968 continue;
7969 }
7970 types.add(&mSuspendedEffects.valueAt(i)->mType);
7971 }
7972 for (size_t i = 0; i < types.size(); i++) {
7973 setEffectSuspended_l(types[i], false);
7974 }
Steve Block3856b092011-10-20 11:56:00 +01007975 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007976 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7977 }
7978 }
7979}
7980
Eric Laurent6bffdb82011-09-23 08:40:41 -07007981
7982// The volume effect is used for automated tests only
7983#ifndef OPENSL_ES_H_
7984static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7985 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7986const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7987#endif //OPENSL_ES_H_
7988
Eric Laurentdb7c0792011-08-10 10:37:50 -07007989bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7990{
7991 // auxiliary effects and visualizer are never suspended on output mix
7992 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7993 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007994 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7995 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007996 return false;
7997 }
7998 return true;
7999}
8000
Glenn Kastend0539712012-01-30 12:56:03 -08008001void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07008002{
Glenn Kastend0539712012-01-30 12:56:03 -08008003 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07008004 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08008005 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8006 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07008007 }
Eric Laurent59255e42011-07-27 19:49:51 -07008008 }
Eric Laurent59255e42011-07-27 19:49:51 -07008009}
8010
8011sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8012 const effect_uuid_t *type)
8013{
Glenn Kasten090f0192012-01-30 13:00:02 -08008014 sp<EffectModule> effect = getEffectFromType_l(type);
8015 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008016}
8017
8018void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8019 bool enabled)
8020{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008021 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008022 if (enabled) {
8023 if (index < 0) {
8024 // if the effect is not suspend check if all effects are suspended
8025 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8026 if (index < 0) {
8027 return;
8028 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07008029 if (!isEffectEligibleForSuspend(effect->desc())) {
8030 return;
8031 }
Eric Laurent59255e42011-07-27 19:49:51 -07008032 setEffectSuspended_l(&effect->desc().type, enabled);
8033 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07008034 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008035 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07008036 return;
8037 }
Eric Laurent59255e42011-07-27 19:49:51 -07008038 }
Steve Block3856b092011-10-20 11:56:00 +01008039 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008040 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008041 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8042 // if effect is requested to suspended but was not yet enabled, supend it now.
8043 if (desc->mEffect == 0) {
8044 desc->mEffect = effect;
8045 effect->setEnabled(false);
8046 effect->setSuspended(true);
8047 }
8048 } else {
8049 if (index < 0) {
8050 return;
8051 }
Steve Block3856b092011-10-20 11:56:00 +01008052 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008053 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008054 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8055 desc->mEffect.clear();
8056 effect->setSuspended(false);
8057 }
8058}
8059
Mathias Agopian65ab4712010-07-14 17:59:35 -07008060#undef LOG_TAG
8061#define LOG_TAG "AudioFlinger"
8062
8063// ----------------------------------------------------------------------------
8064
8065status_t AudioFlinger::onTransact(
8066 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8067{
8068 return BnAudioFlinger::onTransact(code, data, reply, flags);
8069}
8070
Mathias Agopian65ab4712010-07-14 17:59:35 -07008071}; // namespace android