blob: ddca94171d6f951b662c4220822c067368718d03 [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],
Dima Zavin799a70e2011-04-18 16:57:27 -0700193 mod->name, mod->id);
194 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",
Dima Zavin5a61d2f2011-04-19 19:04:32 -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");
313 result.append(" session pid cnt\n");
314 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
315 AudioSessionRef *r = mAudioSessionRefs[i];
316 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
317 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:
518 if(status) {
519 *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++)
John Grossman4ff14ba2012-02-08 16:37:41 -0800613 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++)
Mathias Agopian65ab4712010-07-14 17:59:35 -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++)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700696 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
697
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;
726 assert(NULL != mPrimaryHardwareDev);
727 assert(NULL != mPrimaryHardwareDev->get_master_volume);
728
729 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
730 mHardwareStatus = AUDIO_HW_IDLE;
731 return ret_val;
732 }
733
734 return mMasterVolume;
735}
736
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800737status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
738 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700739{
740 // check calling permissions
741 if (!settingsAllowed()) {
742 return PERMISSION_DENIED;
743 }
744
Glenn Kasten263709e2012-01-06 08:40:01 -0800745 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000746 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700747 return BAD_VALUE;
748 }
749
750 AutoMutex lock(mLock);
751 PlaybackThread *thread = NULL;
752 if (output) {
753 thread = checkPlaybackThread_l(output);
754 if (thread == NULL) {
755 return BAD_VALUE;
756 }
757 }
758
759 mStreamTypes[stream].volume = value;
760
761 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800762 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700763 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
764 }
765 } else {
766 thread->setStreamVolume(stream, value);
767 }
768
769 return NO_ERROR;
770}
771
Glenn Kastenfff6d712012-01-12 16:38:12 -0800772status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700773{
774 // check calling permissions
775 if (!settingsAllowed()) {
776 return PERMISSION_DENIED;
777 }
778
Glenn Kasten263709e2012-01-06 08:40:01 -0800779 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700780 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000781 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700782 return BAD_VALUE;
783 }
784
Eric Laurent93575202011-01-18 18:39:02 -0800785 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700786 mStreamTypes[stream].mute = muted;
787 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
788 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
789
790 return NO_ERROR;
791}
792
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800793float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700794{
Glenn Kasten263709e2012-01-06 08:40:01 -0800795 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796 return 0.0f;
797 }
798
799 AutoMutex lock(mLock);
800 float volume;
801 if (output) {
802 PlaybackThread *thread = checkPlaybackThread_l(output);
803 if (thread == NULL) {
804 return 0.0f;
805 }
806 volume = thread->streamVolume(stream);
807 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800808 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700809 }
810
811 return volume;
812}
813
Glenn Kastenfff6d712012-01-12 16:38:12 -0800814bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700815{
Glenn Kasten263709e2012-01-06 08:40:01 -0800816 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700817 return true;
818 }
819
Glenn Kasten6637baa2012-01-09 09:40:36 -0800820 AutoMutex lock(mLock);
821 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700822}
823
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800824status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700825{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800826 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700827 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
828 // check calling permissions
829 if (!settingsAllowed()) {
830 return PERMISSION_DENIED;
831 }
832
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833 // ioHandle == 0 means the parameters are global to the audio hardware interface
834 if (ioHandle == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700835 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800836 {
837 AutoMutex lock(mHardwareLock);
838 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700839 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
840 audio_hw_device_t *dev = mAudioHwDevs[i];
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800841 status_t result = dev->set_parameters(dev, keyValuePairs.string());
Dima Zavin799a70e2011-04-18 16:57:27 -0700842 final_result = result ?: final_result;
843 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700844 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800845 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700846 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
847 AudioParameter param = AudioParameter(keyValuePairs);
848 String8 value;
849 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
850 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700851 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
852 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700853 for (size_t i = 0; i < mRecordThreads.size(); i++) {
854 sp<RecordThread> thread = mRecordThreads.valueAt(i);
855 RecordThread::RecordTrack *track = thread->track();
856 if (track != NULL) {
857 audio_devices_t device = (audio_devices_t)(
858 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700859 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700860 thread->setEffectSuspended(FX_IID_AEC,
861 suspend,
862 track->sessionId());
863 thread->setEffectSuspended(FX_IID_NS,
864 suspend,
865 track->sessionId());
866 }
867 }
Eric Laurentbee53372011-08-29 12:42:48 -0700868 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700869 }
870 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700871 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700872 }
873
874 // hold a strong ref on thread in case closeOutput() or closeInput() is called
875 // and the thread is exited once the lock is released
876 sp<ThreadBase> thread;
877 {
878 Mutex::Autolock _l(mLock);
879 thread = checkPlaybackThread_l(ioHandle);
880 if (thread == NULL) {
881 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800882 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700883 // indicate output device change to all input threads for pre processing
884 AudioParameter param = AudioParameter(keyValuePairs);
885 int value;
886 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
887 for (size_t i = 0; i < mRecordThreads.size(); i++) {
888 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
889 }
890 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700891 }
892 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800893 if (thread != 0) {
894 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700895 }
896 return BAD_VALUE;
897}
898
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800899String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700900{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800901// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700902// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
903
904 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700905 String8 out_s8;
906
Dima Zavin799a70e2011-04-18 16:57:27 -0700907 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800908 char *s;
909 {
910 AutoMutex lock(mHardwareLock);
911 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700912 audio_hw_device_t *dev = mAudioHwDevs[i];
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800913 s = dev->get_parameters(dev, keys.string());
914 mHardwareStatus = AUDIO_HW_IDLE;
915 }
John Grossmanef7740b2012-02-09 11:28:36 -0800916 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700917 free(s);
918 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700919 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700920 }
921
922 Mutex::Autolock _l(mLock);
923
924 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
925 if (playbackThread != NULL) {
926 return playbackThread->getParameters(keys);
927 }
928 RecordThread *recordThread = checkRecordThread_l(ioHandle);
929 if (recordThread != NULL) {
930 return recordThread->getParameters(keys);
931 }
932 return String8("");
933}
934
Glenn Kastenf587ba52012-01-26 16:25:10 -0800935size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700936{
Eric Laurenta1884f92011-08-23 08:25:03 -0700937 status_t ret = initCheck();
938 if (ret != NO_ERROR) {
939 return 0;
940 }
941
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800942 AutoMutex lock(mHardwareLock);
943 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
944 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
945 mHardwareStatus = AUDIO_HW_IDLE;
946 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700947}
948
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800949unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700950{
951 if (ioHandle == 0) {
952 return 0;
953 }
954
955 Mutex::Autolock _l(mLock);
956
957 RecordThread *recordThread = checkRecordThread_l(ioHandle);
958 if (recordThread != NULL) {
959 return recordThread->getInputFramesLost();
960 }
961 return 0;
962}
963
964status_t AudioFlinger::setVoiceVolume(float value)
965{
Eric Laurenta1884f92011-08-23 08:25:03 -0700966 status_t ret = initCheck();
967 if (ret != NO_ERROR) {
968 return ret;
969 }
970
Mathias Agopian65ab4712010-07-14 17:59:35 -0700971 // check calling permissions
972 if (!settingsAllowed()) {
973 return PERMISSION_DENIED;
974 }
975
976 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800977 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700978 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700979 mHardwareStatus = AUDIO_HW_IDLE;
980
981 return ret;
982}
983
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800984status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
985 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700986{
987 status_t status;
988
989 Mutex::Autolock _l(mLock);
990
991 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
992 if (playbackThread != NULL) {
993 return playbackThread->getRenderPosition(halFrames, dspFrames);
994 }
995
996 return BAD_VALUE;
997}
998
999void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1000{
1001
1002 Mutex::Autolock _l(mLock);
1003
Glenn Kastenbb001922012-02-03 11:10:26 -08001004 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001005 if (mNotificationClients.indexOfKey(pid) < 0) {
1006 sp<NotificationClient> notificationClient = new NotificationClient(this,
1007 client,
1008 pid);
Steve Block3856b092011-10-20 11:56:00 +01001009 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001010
1011 mNotificationClients.add(pid, notificationClient);
1012
1013 sp<IBinder> binder = client->asBinder();
1014 binder->linkToDeath(notificationClient);
1015
1016 // the config change is always sent from playback or record threads to avoid deadlock
1017 // with AudioSystem::gLock
1018 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1019 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1020 }
1021
1022 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1023 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1024 }
1025 }
1026}
1027
1028void AudioFlinger::removeNotificationClient(pid_t pid)
1029{
1030 Mutex::Autolock _l(mLock);
1031
Glenn Kastena3b09252012-01-20 09:19:01 -08001032 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001033
Steve Block3856b092011-10-20 11:56:00 +01001034 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001035 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001036 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001037 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001038 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +01001039 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001040 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +01001041 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001042 mAudioSessionRefs.removeAt(i);
1043 delete ref;
1044 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001045 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001046 } else {
1047 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001048 }
1049 }
1050 if (removed) {
1051 purgeStaleEffects_l();
1052 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001053}
1054
1055// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001056void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001057{
1058 size_t size = mNotificationClients.size();
1059 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001060 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1061 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001062 }
1063}
1064
1065// removeClient_l() must be called with AudioFlinger::mLock held
1066void AudioFlinger::removeClient_l(pid_t pid)
1067{
Steve Block3856b092011-10-20 11:56:00 +01001068 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001069 mClients.removeItem(pid);
1070}
1071
1072
1073// ----------------------------------------------------------------------------
1074
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001075AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1076 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001077 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001078 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001079 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
1080 // mChannelMask
1081 mChannelCount(0),
1082 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1083 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001084 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001085 mDevice(device),
1086 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001087{
1088}
1089
1090AudioFlinger::ThreadBase::~ThreadBase()
1091{
1092 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001093 // do not lock the mutex in destructor
1094 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001095 if (mPowerManager != 0) {
1096 sp<IBinder> binder = mPowerManager->asBinder();
1097 binder->unlinkToDeath(mDeathRecipient);
1098 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001099}
1100
1101void AudioFlinger::ThreadBase::exit()
1102{
Steve Block3856b092011-10-20 11:56:00 +01001103 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001104 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001105 // This lock prevents the following race in thread (uniprocessor for illustration):
1106 // if (!exitPending()) {
1107 // // context switch from here to exit()
1108 // // exit() calls requestExit(), what exitPending() observes
1109 // // exit() calls signal(), which is dropped since no waiters
1110 // // context switch back from exit() to here
1111 // mWaitWorkCV.wait(...);
1112 // // now thread is hung
1113 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001114 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001115 requestExit();
1116 mWaitWorkCV.signal();
1117 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001118 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1119 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001120 requestExitAndWait();
1121}
1122
Mathias Agopian65ab4712010-07-14 17:59:35 -07001123status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1124{
1125 status_t status;
1126
Steve Block3856b092011-10-20 11:56:00 +01001127 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001128 Mutex::Autolock _l(mLock);
1129
1130 mNewParameters.add(keyValuePairs);
1131 mWaitWorkCV.signal();
1132 // wait condition with timeout in case the thread loop has exited
1133 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001134 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001135 status = mParamStatus;
1136 mWaitWorkCV.signal();
1137 } else {
1138 status = TIMED_OUT;
1139 }
1140 return status;
1141}
1142
1143void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1144{
1145 Mutex::Autolock _l(mLock);
1146 sendConfigEvent_l(event, param);
1147}
1148
1149// sendConfigEvent_l() must be called with ThreadBase::mLock held
1150void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1151{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001152 ConfigEvent configEvent;
1153 configEvent.mEvent = event;
1154 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001155 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001156 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001157 mWaitWorkCV.signal();
1158}
1159
1160void AudioFlinger::ThreadBase::processConfigEvents()
1161{
1162 mLock.lock();
1163 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001164 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001165 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001166 mConfigEvents.removeAt(0);
1167 // release mLock before locking AudioFlinger mLock: lock order is always
1168 // AudioFlinger then ThreadBase to avoid cross deadlock
1169 mLock.unlock();
1170 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001171 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001172 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001173 mLock.lock();
1174 }
1175 mLock.unlock();
1176}
1177
1178status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1179{
1180 const size_t SIZE = 256;
1181 char buffer[SIZE];
1182 String8 result;
1183
1184 bool locked = tryLock(mLock);
1185 if (!locked) {
1186 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1187 write(fd, buffer, strlen(buffer));
1188 }
1189
1190 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1191 result.append(buffer);
1192 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1193 result.append(buffer);
1194 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1195 result.append(buffer);
1196 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1197 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001198 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1199 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001200 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1201 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001202 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001203 result.append(buffer);
1204
1205 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1206 result.append(buffer);
1207 result.append(" Index Command");
1208 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1209 snprintf(buffer, SIZE, "\n %02d ", i);
1210 result.append(buffer);
1211 result.append(mNewParameters[i]);
1212 }
1213
1214 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1215 result.append(buffer);
1216 snprintf(buffer, SIZE, " Index event param\n");
1217 result.append(buffer);
1218 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001219 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001220 result.append(buffer);
1221 }
1222 result.append("\n");
1223
1224 write(fd, result.string(), result.size());
1225
1226 if (locked) {
1227 mLock.unlock();
1228 }
1229 return NO_ERROR;
1230}
1231
Eric Laurent1d2bff02011-07-24 17:49:51 -07001232status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1233{
1234 const size_t SIZE = 256;
1235 char buffer[SIZE];
1236 String8 result;
1237
1238 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1239 write(fd, buffer, strlen(buffer));
1240
1241 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1242 sp<EffectChain> chain = mEffectChains[i];
1243 if (chain != 0) {
1244 chain->dump(fd, args);
1245 }
1246 }
1247 return NO_ERROR;
1248}
1249
Eric Laurentfeb0db62011-07-22 09:04:31 -07001250void AudioFlinger::ThreadBase::acquireWakeLock()
1251{
1252 Mutex::Autolock _l(mLock);
1253 acquireWakeLock_l();
1254}
1255
1256void AudioFlinger::ThreadBase::acquireWakeLock_l()
1257{
1258 if (mPowerManager == 0) {
1259 // use checkService() to avoid blocking if power service is not up yet
1260 sp<IBinder> binder =
1261 defaultServiceManager()->checkService(String16("power"));
1262 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001263 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001264 } else {
1265 mPowerManager = interface_cast<IPowerManager>(binder);
1266 binder->linkToDeath(mDeathRecipient);
1267 }
1268 }
1269 if (mPowerManager != 0) {
1270 sp<IBinder> binder = new BBinder();
1271 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1272 binder,
1273 String16(mName));
1274 if (status == NO_ERROR) {
1275 mWakeLockToken = binder;
1276 }
Steve Block3856b092011-10-20 11:56:00 +01001277 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001278 }
1279}
1280
1281void AudioFlinger::ThreadBase::releaseWakeLock()
1282{
1283 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001284 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001285}
1286
1287void AudioFlinger::ThreadBase::releaseWakeLock_l()
1288{
1289 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001290 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001291 if (mPowerManager != 0) {
1292 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1293 }
1294 mWakeLockToken.clear();
1295 }
1296}
1297
1298void AudioFlinger::ThreadBase::clearPowerManager()
1299{
1300 Mutex::Autolock _l(mLock);
1301 releaseWakeLock_l();
1302 mPowerManager.clear();
1303}
1304
1305void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1306{
1307 sp<ThreadBase> thread = mThread.promote();
1308 if (thread != 0) {
1309 thread->clearPowerManager();
1310 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001311 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001312}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001313
Eric Laurent59255e42011-07-27 19:49:51 -07001314void AudioFlinger::ThreadBase::setEffectSuspended(
1315 const effect_uuid_t *type, bool suspend, int sessionId)
1316{
1317 Mutex::Autolock _l(mLock);
1318 setEffectSuspended_l(type, suspend, sessionId);
1319}
1320
1321void AudioFlinger::ThreadBase::setEffectSuspended_l(
1322 const effect_uuid_t *type, bool suspend, int sessionId)
1323{
Glenn Kasten090f0192012-01-30 13:00:02 -08001324 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001325 if (chain != 0) {
1326 if (type != NULL) {
1327 chain->setEffectSuspended_l(type, suspend);
1328 } else {
1329 chain->setEffectSuspendedAll_l(suspend);
1330 }
1331 }
1332
1333 updateSuspendedSessions_l(type, suspend, sessionId);
1334}
1335
1336void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1337{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001338 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001339 if (index < 0) {
1340 return;
1341 }
1342
1343 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1344 mSuspendedSessions.editValueAt(index);
1345
1346 for (size_t i = 0; i < sessionEffects.size(); i++) {
1347 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1348 for (int j = 0; j < desc->mRefCount; j++) {
1349 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1350 chain->setEffectSuspendedAll_l(true);
1351 } else {
Steve Block3856b092011-10-20 11:56:00 +01001352 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001353 desc->mType.timeLow);
1354 chain->setEffectSuspended_l(&desc->mType, true);
1355 }
1356 }
1357 }
1358}
1359
Eric Laurent59255e42011-07-27 19:49:51 -07001360void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1361 bool suspend,
1362 int sessionId)
1363{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001364 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001365
1366 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1367
1368 if (suspend) {
1369 if (index >= 0) {
1370 sessionEffects = mSuspendedSessions.editValueAt(index);
1371 } else {
1372 mSuspendedSessions.add(sessionId, sessionEffects);
1373 }
1374 } else {
1375 if (index < 0) {
1376 return;
1377 }
1378 sessionEffects = mSuspendedSessions.editValueAt(index);
1379 }
1380
1381
1382 int key = EffectChain::kKeyForSuspendAll;
1383 if (type != NULL) {
1384 key = type->timeLow;
1385 }
1386 index = sessionEffects.indexOfKey(key);
1387
1388 sp <SuspendedSessionDesc> desc;
1389 if (suspend) {
1390 if (index >= 0) {
1391 desc = sessionEffects.valueAt(index);
1392 } else {
1393 desc = new SuspendedSessionDesc();
1394 if (type != NULL) {
1395 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1396 }
1397 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001398 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001399 }
1400 desc->mRefCount++;
1401 } else {
1402 if (index < 0) {
1403 return;
1404 }
1405 desc = sessionEffects.valueAt(index);
1406 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001407 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001408 sessionEffects.removeItemsAt(index);
1409 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001410 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001411 sessionId);
1412 mSuspendedSessions.removeItem(sessionId);
1413 }
1414 }
1415 }
1416 if (!sessionEffects.isEmpty()) {
1417 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1418 }
1419}
1420
1421void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1422 bool enabled,
1423 int sessionId)
1424{
1425 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001426 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1427}
Eric Laurent59255e42011-07-27 19:49:51 -07001428
Eric Laurenta85a74a2011-10-19 11:44:54 -07001429void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1430 bool enabled,
1431 int sessionId)
1432{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001433 if (mType != RECORD) {
1434 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1435 // another session. This gives the priority to well behaved effect control panels
1436 // and applications not using global effects.
1437 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1438 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1439 }
1440 }
Eric Laurent59255e42011-07-27 19:49:51 -07001441
1442 sp<EffectChain> chain = getEffectChain_l(sessionId);
1443 if (chain != 0) {
1444 chain->checkSuspendOnEffectEnabled(effect, enabled);
1445 }
1446}
1447
Mathias Agopian65ab4712010-07-14 17:59:35 -07001448// ----------------------------------------------------------------------------
1449
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001450AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1451 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001452 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001453 uint32_t device,
1454 type_t type)
1455 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001456 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1457 // Assumes constructor is called by AudioFlinger with it's mLock held,
1458 // but it would be safer to explicitly pass initial masterMute as parameter
1459 mMasterMute(audioFlinger->masterMute_l()),
1460 // mStreamTypes[] initialized in constructor body
1461 mOutput(output),
1462 // Assumes constructor is called by AudioFlinger with it's mLock held,
1463 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001464 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001465 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001466{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001467 snprintf(mName, kNameLength, "AudioOut_%d", id);
1468
Mathias Agopian65ab4712010-07-14 17:59:35 -07001469 readOutputParameters();
1470
Glenn Kasten263709e2012-01-06 08:40:01 -08001471 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001472 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1473 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1474 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001475 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1476 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001477 // initialized by stream_type_t default constructor
1478 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001479 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001480 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1481 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001482}
1483
1484AudioFlinger::PlaybackThread::~PlaybackThread()
1485{
1486 delete [] mMixBuffer;
1487}
1488
1489status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1490{
1491 dumpInternals(fd, args);
1492 dumpTracks(fd, args);
1493 dumpEffectChains(fd, args);
1494 return NO_ERROR;
1495}
1496
1497status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1498{
1499 const size_t SIZE = 256;
1500 char buffer[SIZE];
1501 String8 result;
1502
1503 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1504 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001505 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 -07001506 for (size_t i = 0; i < mTracks.size(); ++i) {
1507 sp<Track> track = mTracks[i];
1508 if (track != 0) {
1509 track->dump(buffer, SIZE);
1510 result.append(buffer);
1511 }
1512 }
1513
1514 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1515 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001516 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 -07001517 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001518 sp<Track> track = mActiveTracks[i].promote();
1519 if (track != 0) {
1520 track->dump(buffer, SIZE);
1521 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001522 }
1523 }
1524 write(fd, result.string(), result.size());
1525 return NO_ERROR;
1526}
1527
Mathias Agopian65ab4712010-07-14 17:59:35 -07001528status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1529{
1530 const size_t SIZE = 256;
1531 char buffer[SIZE];
1532 String8 result;
1533
1534 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1535 result.append(buffer);
1536 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1537 result.append(buffer);
1538 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1539 result.append(buffer);
1540 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1541 result.append(buffer);
1542 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1543 result.append(buffer);
1544 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1545 result.append(buffer);
1546 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1547 result.append(buffer);
1548 write(fd, result.string(), result.size());
1549
1550 dumpBase(fd, args);
1551
1552 return NO_ERROR;
1553}
1554
1555// Thread virtuals
1556status_t AudioFlinger::PlaybackThread::readyToRun()
1557{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001558 status_t status = initCheck();
1559 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001560 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001561 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001562 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001563 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001564 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001565}
1566
1567void AudioFlinger::PlaybackThread::onFirstRef()
1568{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001569 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001570}
1571
1572// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1573sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1574 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001575 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001576 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001577 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001578 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001579 int frameCount,
1580 const sp<IMemory>& sharedBuffer,
1581 int sessionId,
John Grossman4ff14ba2012-02-08 16:37:41 -08001582 bool isTimed,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001583 status_t *status)
1584{
1585 sp<Track> track;
1586 status_t lStatus;
1587
1588 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001589 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1590 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001591 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001592 "for output %p with format %d",
1593 sampleRate, format, channelMask, mOutput, mFormat);
1594 lStatus = BAD_VALUE;
1595 goto Exit;
1596 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001597 }
1598 } else {
1599 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1600 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001601 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001602 lStatus = BAD_VALUE;
1603 goto Exit;
1604 }
1605 }
1606
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001607 lStatus = initCheck();
1608 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001609 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610 goto Exit;
1611 }
1612
1613 { // scope for mLock
1614 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001615
1616 // all tracks in same audio session must share the same routing strategy otherwise
1617 // conflicts will happen when tracks are moved from one output to another by audio policy
1618 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001619 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001620 for (size_t i = 0; i < mTracks.size(); ++i) {
1621 sp<Track> t = mTracks[i];
1622 if (t != 0) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001623 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001624 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001625 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001626 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001627 lStatus = BAD_VALUE;
1628 goto Exit;
1629 }
1630 }
1631 }
1632
John Grossman4ff14ba2012-02-08 16:37:41 -08001633 if (!isTimed) {
1634 track = new Track(this, client, streamType, sampleRate, format,
1635 channelMask, frameCount, sharedBuffer, sessionId);
1636 } else {
1637 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1638 channelMask, frameCount, sharedBuffer, sessionId);
1639 }
1640 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001641 lStatus = NO_MEMORY;
1642 goto Exit;
1643 }
1644 mTracks.add(track);
1645
1646 sp<EffectChain> chain = getEffectChain_l(sessionId);
1647 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001648 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001649 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001650 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001651 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001652 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001653
1654 // invalidate track immediately if the stream type was moved to another thread since
1655 // createTrack() was called by the client process.
1656 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001657 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001658 this, streamType);
1659 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1660 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001661 }
1662 lStatus = NO_ERROR;
1663
1664Exit:
1665 if(status) {
1666 *status = lStatus;
1667 }
1668 return track;
1669}
1670
1671uint32_t AudioFlinger::PlaybackThread::latency() const
1672{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001673 Mutex::Autolock _l(mLock);
1674 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001675 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001676 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001677 return 0;
1678 }
1679}
1680
Glenn Kasten6637baa2012-01-09 09:40:36 -08001681void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001682{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001683 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001684 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685}
1686
Glenn Kasten6637baa2012-01-09 09:40:36 -08001687void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001688{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001689 Mutex::Autolock _l(mLock);
1690 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001691}
1692
Glenn Kasten6637baa2012-01-09 09:40:36 -08001693void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001694{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001695 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001696 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001697}
1698
Glenn Kasten6637baa2012-01-09 09:40:36 -08001699void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001700{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001701 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001702 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001703}
1704
Glenn Kastenfff6d712012-01-12 16:38:12 -08001705float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001706{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001707 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001708 return mStreamTypes[stream].volume;
1709}
1710
Mathias Agopian65ab4712010-07-14 17:59:35 -07001711// addTrack_l() must be called with ThreadBase::mLock held
1712status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1713{
1714 status_t status = ALREADY_EXISTS;
1715
1716 // set retry count for buffer fill
1717 track->mRetryCount = kMaxTrackStartupRetries;
1718 if (mActiveTracks.indexOf(track) < 0) {
1719 // the track is newly added, make sure it fills up all its
1720 // buffers before playing. This is to ensure the client will
1721 // effectively get the latency it requested.
1722 track->mFillingUpStatus = Track::FS_FILLING;
1723 track->mResetDone = false;
1724 mActiveTracks.add(track);
1725 if (track->mainBuffer() != mMixBuffer) {
1726 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1727 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001728 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001729 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001730 }
1731 }
1732
1733 status = NO_ERROR;
1734 }
1735
Steve Block3856b092011-10-20 11:56:00 +01001736 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001737 mWaitWorkCV.broadcast();
1738
1739 return status;
1740}
1741
1742// destroyTrack_l() must be called with ThreadBase::mLock held
1743void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1744{
1745 track->mState = TrackBase::TERMINATED;
1746 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001747 removeTrack_l(track);
1748 }
1749}
1750
1751void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1752{
1753 mTracks.remove(track);
1754 deleteTrackName_l(track->name());
1755 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1756 if (chain != 0) {
1757 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001758 }
1759}
1760
1761String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1762{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001763 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001764 char *s;
1765
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001766 Mutex::Autolock _l(mLock);
1767 if (initCheck() != NO_ERROR) {
1768 return out_s8;
1769 }
1770
Dima Zavin799a70e2011-04-18 16:57:27 -07001771 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001772 out_s8 = String8(s);
1773 free(s);
1774 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001775}
1776
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001777// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001778void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1779 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001780 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001781
Steve Block3856b092011-10-20 11:56:00 +01001782 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001783
1784 switch (event) {
1785 case AudioSystem::OUTPUT_OPENED:
1786 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001787 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001788 desc.samplingRate = mSampleRate;
1789 desc.format = mFormat;
1790 desc.frameCount = mFrameCount;
1791 desc.latency = latency();
1792 param2 = &desc;
1793 break;
1794
1795 case AudioSystem::STREAM_CONFIG_CHANGED:
1796 param2 = &param;
1797 case AudioSystem::OUTPUT_CLOSED:
1798 default:
1799 break;
1800 }
1801 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1802}
1803
1804void AudioFlinger::PlaybackThread::readOutputParameters()
1805{
Dima Zavin799a70e2011-04-18 16:57:27 -07001806 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001807 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1808 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001809 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001810 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001811 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001812
1813 // FIXME - Current mixer implementation only supports stereo output: Always
1814 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001815 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001816 mMixBuffer = new int16_t[mFrameCount * 2];
1817 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1818
Eric Laurentde070132010-07-13 04:45:46 -07001819 // force reconfiguration of effect chains and engines to take new buffer size and audio
1820 // parameters into account
1821 // Note that mLock is not held when readOutputParameters() is called from the constructor
1822 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1823 // matter.
1824 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1825 Vector< sp<EffectChain> > effectChains = mEffectChains;
1826 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001827 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001828 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001829}
1830
1831status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1832{
Glenn Kastena0d68332012-01-27 16:47:15 -08001833 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001834 return BAD_VALUE;
1835 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001836 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001837 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001838 return INVALID_OPERATION;
1839 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001840 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001841
Dima Zavin799a70e2011-04-18 16:57:27 -07001842 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001843}
1844
Eric Laurent39e94f82010-07-28 01:32:47 -07001845uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001846{
1847 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001848 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001849 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001850 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001851 }
1852
1853 for (size_t i = 0; i < mTracks.size(); ++i) {
1854 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001855 if (sessionId == track->sessionId() &&
1856 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001857 result |= TRACK_SESSION;
1858 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001859 }
1860 }
1861
Eric Laurent39e94f82010-07-28 01:32:47 -07001862 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001863}
1864
Eric Laurentde070132010-07-13 04:45:46 -07001865uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1866{
Dima Zavinfce7a472011-04-19 22:30:36 -07001867 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001868 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001869 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1870 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001871 }
1872 for (size_t i = 0; i < mTracks.size(); i++) {
1873 sp<Track> track = mTracks[i];
1874 if (sessionId == track->sessionId() &&
1875 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001876 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07001877 }
1878 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001879 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001880}
1881
Mathias Agopian65ab4712010-07-14 17:59:35 -07001882
Glenn Kastenaed850d2012-01-26 09:46:34 -08001883AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001884{
1885 Mutex::Autolock _l(mLock);
1886 return mOutput;
1887}
1888
1889AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1890{
1891 Mutex::Autolock _l(mLock);
1892 AudioStreamOut *output = mOutput;
1893 mOutput = NULL;
1894 return output;
1895}
1896
1897// this method must always be called either with ThreadBase mLock held or inside the thread loop
1898audio_stream_t* AudioFlinger::PlaybackThread::stream()
1899{
1900 if (mOutput == NULL) {
1901 return NULL;
1902 }
1903 return &mOutput->stream->common;
1904}
1905
Eric Laurent162b40b2011-12-05 09:47:19 -08001906uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1907{
1908 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1909 // decoding and transfer time. So sleeping for half of the latency would likely cause
1910 // underruns
1911 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1912 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1913 } else {
1914 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1915 }
1916}
1917
Mathias Agopian65ab4712010-07-14 17:59:35 -07001918// ----------------------------------------------------------------------------
1919
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001920AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001921 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001922 : PlaybackThread(audioFlinger, output, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001923 mAudioMixer(new AudioMixer(mFrameCount, mSampleRate)),
1924 mPrevMixerStatus(MIXER_IDLE)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001925{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001926 // FIXME - Current mixer implementation only supports stereo output
1927 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001928 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001929 }
1930}
1931
1932AudioFlinger::MixerThread::~MixerThread()
1933{
1934 delete mAudioMixer;
1935}
1936
Glenn Kasten83efdd02012-02-24 07:21:32 -08001937class CpuStats {
1938public:
1939 void sample();
1940#ifdef DEBUG_CPU_USAGE
1941private:
1942 ThreadCpuUsage mCpu;
1943#endif
1944};
1945
1946void CpuStats::sample() {
1947#ifdef DEBUG_CPU_USAGE
1948 const CentralTendencyStatistics& stats = mCpu.statistics();
1949 mCpu.sampleAndEnable();
1950 unsigned n = stats.n();
1951 // mCpu.elapsed() is expensive, so don't call it every loop
1952 if ((n & 127) == 1) {
1953 long long elapsed = mCpu.elapsed();
1954 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1955 double perLoop = elapsed / (double) n;
1956 double perLoop100 = perLoop * 0.01;
1957 double mean = stats.mean();
1958 double stddev = stats.stddev();
1959 double minimum = stats.minimum();
1960 double maximum = stats.maximum();
1961 mCpu.resetStatistics();
1962 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",
1963 elapsed * .000000001, n, perLoop * .000001,
1964 mean * .001,
1965 stddev * .001,
1966 minimum * .001,
1967 maximum * .001,
1968 mean / perLoop100,
1969 stddev / perLoop100,
1970 minimum / perLoop100,
1971 maximum / perLoop100);
1972 }
1973 }
1974#endif
1975};
1976
Glenn Kasten37d825e2012-02-24 07:21:48 -08001977void AudioFlinger::PlaybackThread::checkSilentMode_l()
1978{
1979 if (!mMasterMute) {
1980 char value[PROPERTY_VALUE_MAX];
1981 if (property_get("ro.audio.silent", value, "0") > 0) {
1982 char *endptr;
1983 unsigned long ul = strtoul(value, &endptr, 0);
1984 if (*endptr == '\0' && ul != 0) {
1985 ALOGD("Silence is golden");
1986 // The setprop command will not allow a property to be changed after
1987 // the first time it is set, so we don't have to worry about un-muting.
1988 setMasterMute_l(true);
1989 }
1990 }
1991 }
1992}
1993
Mathias Agopian65ab4712010-07-14 17:59:35 -07001994bool AudioFlinger::MixerThread::threadLoop()
1995{
Glenn Kasten688a6402012-02-29 07:57:06 -08001996 // DirectOutputThread has single trackToRemove instead of Vector
Mathias Agopian65ab4712010-07-14 17:59:35 -07001997 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08001998 // DirectOutputThread has activeTrack here
Mathias Agopian65ab4712010-07-14 17:59:35 -07001999 nsecs_t standbyTime = systemTime();
2000 size_t mixBufferSize = mFrameCount * mFrameSize;
Glenn Kasten688a6402012-02-29 07:57:06 -08002001
Mathias Agopian65ab4712010-07-14 17:59:35 -07002002 // FIXME: Relaxed timing because of a certain device that can't meet latency
2003 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07002004 // increase threshold again due to low power audio mode. The way this warning threshold is
2005 // calculated and its usefulness should be reconsidered anyway.
2006 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002007 nsecs_t lastWarning = 0;
2008 bool longStandbyExit = false;
Glenn Kasten688a6402012-02-29 07:57:06 -08002009
Mathias Agopian65ab4712010-07-14 17:59:35 -07002010 uint32_t activeSleepTime = activeSleepTimeUs();
2011 uint32_t idleSleepTime = idleSleepTimeUs();
2012 uint32_t sleepTime = idleSleepTime;
Glenn Kasten688a6402012-02-29 07:57:06 -08002013
Eric Laurent7cafbb32011-11-22 18:50:29 -08002014 uint32_t sleepTimeShift = 0;
Glenn Kasten83efdd02012-02-24 07:21:32 -08002015 CpuStats cpuStats;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002016
Glenn Kasten688a6402012-02-29 07:57:06 -08002017 // DirectOutputThread has shorter standbyDelay
2018
Eric Laurentfeb0db62011-07-22 09:04:31 -07002019 acquireWakeLock();
2020
Mathias Agopian65ab4712010-07-14 17:59:35 -07002021 while (!exitPending())
2022 {
Glenn Kasten83efdd02012-02-24 07:21:32 -08002023 cpuStats.sample();
Glenn Kasten688a6402012-02-29 07:57:06 -08002024
2025 // DirectOutputThread has rampVolume, leftVol, rightVol
2026
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002027 Vector< sp<EffectChain> > effectChains;
2028
Mathias Agopian65ab4712010-07-14 17:59:35 -07002029 processConfigEvents();
2030
Glenn Kasten5d4eeea2012-02-24 07:25:40 -08002031 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002032 { // scope for mLock
2033
2034 Mutex::Autolock _l(mLock);
2035
2036 if (checkForNewParameters_l()) {
2037 mixBufferSize = mFrameCount * mFrameSize;
Glenn Kasten688a6402012-02-29 07:57:06 -08002038
Mathias Agopian65ab4712010-07-14 17:59:35 -07002039 // FIXME: Relaxed timing because of a certain device that can't meet latency
2040 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07002041 // increase threshold again due to low power audio mode. The way this warning
2042 // threshold is calculated and its usefulness should be reconsidered anyway.
2043 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Glenn Kasten688a6402012-02-29 07:57:06 -08002044
Mathias Agopian65ab4712010-07-14 17:59:35 -07002045 activeSleepTime = activeSleepTimeUs();
2046 idleSleepTime = idleSleepTimeUs();
Glenn Kasten688a6402012-02-29 07:57:06 -08002047 // DirectOutputThread updates standbyDelay also
Mathias Agopian65ab4712010-07-14 17:59:35 -07002048 }
2049
2050 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2051
2052 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002053 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2054 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002055 if (!mStandby) {
Glenn Kasten90bebef2012-01-27 15:24:38 -08002056 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07002057 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002058 mStandby = true;
2059 mBytesWritten = 0;
2060 }
2061
2062 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2063 // we're about to wait, flush the binder command buffer
2064 IPCThreadState::self()->flushCommands();
2065
2066 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 Kasten37d825e2012-02-24 07:21:48 -08002076 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002077
John Grossman4ff14ba2012-02-08 16:37:41 -08002078 standbyTime = systemTime() + mStandbyTimeInNsecs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002079 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08002080 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002081 continue;
2082 }
2083 }
2084
2085 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
2086
2087 // prevent any changes in effect chain list and in each effect chain
2088 // during mixing and effect process as the audio buffers could be deleted
2089 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002090 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002091 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002092
Glenn Kastenf6b16782011-12-15 09:51:17 -08002093 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08002094 // obtain the presentation timestamp of the next output buffer
2095 int64_t pts;
2096 status_t status = INVALID_OPERATION;
2097
2098 if (NULL != mOutput->stream->get_next_write_timestamp) {
2099 status = mOutput->stream->get_next_write_timestamp(
2100 mOutput->stream, &pts);
2101 }
2102
2103 if (status != NO_ERROR) {
2104 pts = AudioBufferProvider::kInvalidPTS;
2105 }
2106
Mathias Agopian65ab4712010-07-14 17:59:35 -07002107 // mix buffers...
John Grossman4ff14ba2012-02-08 16:37:41 -08002108 mAudioMixer->process(pts);
Eric Laurent21e4b6e2012-01-23 18:56:59 -08002109 // increase sleep time progressively when application underrun condition clears.
2110 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2111 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2112 // such that we would underrun the audio HAL.
2113 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08002114 sleepTimeShift--;
2115 }
Eric Laurent21e4b6e2012-01-23 18:56:59 -08002116 sleepTime = 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08002117 standbyTime = systemTime() + mStandbyTimeInNsecs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002118 //TODO: delay standby when effects have a tail
2119 } else {
2120 // If no tracks are ready, sleep once for the duration of an output
2121 // buffer size, then write 0s to the output
2122 if (sleepTime == 0) {
2123 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08002124 sleepTime = activeSleepTime >> sleepTimeShift;
2125 if (sleepTime < kMinThreadSleepTimeUs) {
2126 sleepTime = kMinThreadSleepTimeUs;
2127 }
2128 // reduce sleep time in case of consecutive application underruns to avoid
2129 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2130 // duration we would end up writing less data than needed by the audio HAL if
2131 // the condition persists.
2132 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2133 sleepTimeShift++;
2134 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002135 } else {
2136 sleepTime = idleSleepTime;
2137 }
2138 } else if (mBytesWritten != 0 ||
2139 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2140 memset (mMixBuffer, 0, mixBufferSize);
2141 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01002142 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002143 }
2144 // TODO add standby time extension fct of effect tail
2145 }
2146
2147 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002148 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002149 }
Glenn Kasten04743e92012-02-24 11:20:09 -08002150
2151 // only process effects if we're going to write
Mathias Agopian65ab4712010-07-14 17:59:35 -07002152 if (sleepTime == 0) {
Glenn Kasten688a6402012-02-29 07:57:06 -08002153
2154 // DirectOutputThread adds applyVolume here
2155
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002156 for (size_t i = 0; i < effectChains.size(); i ++) {
2157 effectChains[i]->process_l();
2158 }
Glenn Kasten04743e92012-02-24 11:20:09 -08002159 }
2160
2161 // enable changes in effect chain
2162 unlockEffectChains(effectChains);
2163
2164 // sleepTime == 0 means we must write to audio hardware
2165 if (sleepTime == 0) {
Glenn Kasten688a6402012-02-29 07:57:06 -08002166 // FIXME Only in MixerThread, and rewrite to reduce number of system calls
Mathias Agopian65ab4712010-07-14 17:59:35 -07002167 mLastWriteTime = systemTime();
2168 mInWrite = true;
2169 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002170 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002171 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2172 mNumWrites++;
2173 mInWrite = false;
Glenn Kasten688a6402012-02-29 07:57:06 -08002174
2175 // Only in MixerThread: start of write blocked detection
Mathias Agopian65ab4712010-07-14 17:59:35 -07002176 nsecs_t now = systemTime();
2177 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002178 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002179 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002180 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002181 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002182 ns2ms(delta), mNumDelayedWrites, this);
2183 lastWarning = now;
2184 }
2185 if (mStandby) {
2186 longStandbyExit = true;
2187 }
2188 }
Glenn Kasten688a6402012-02-29 07:57:06 -08002189 // end of write blocked detection
2190
Mathias Agopian65ab4712010-07-14 17:59:35 -07002191 mStandby = false;
2192 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002193 usleep(sleepTime);
2194 }
2195
Glenn Kasten688a6402012-02-29 07:57:06 -08002196 // finally let go of removed track(s), without the lock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07002197 // since we can't guarantee the destructors won't acquire that
2198 // same lock.
2199 tracksToRemove.clear();
2200
2201 // Effect chains will be actually deleted here if they were removed from
2202 // mEffectChains list during mixing or effects processing
2203 effectChains.clear();
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002204
2205 // FIXME Note that the above .clear() is no longer necessary since effectChains
2206 // is now local to this block, but will keep it for now (at least until merge done).
Mathias Agopian65ab4712010-07-14 17:59:35 -07002207 }
2208
Glenn Kasten688a6402012-02-29 07:57:06 -08002209 // put output stream into standby mode
Mathias Agopian65ab4712010-07-14 17:59:35 -07002210 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002211 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002212 }
2213
Eric Laurentfeb0db62011-07-22 09:04:31 -07002214 releaseWakeLock();
2215
Glenn Kastenc0b52832012-02-24 11:18:09 -08002216 ALOGV("Thread %p type %d exiting", this, mType);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002217 return false;
2218}
2219
2220// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002221AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2222 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002223{
2224
Glenn Kasten29c23c32012-01-26 13:37:52 -08002225 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002226 // find out which tracks need to be processed
2227 size_t count = activeTracks.size();
2228 size_t mixedTracks = 0;
2229 size_t tracksWithEffect = 0;
2230
2231 float masterVolume = mMasterVolume;
2232 bool masterMute = mMasterMute;
2233
Eric Laurent571d49c2010-08-11 05:20:11 -07002234 if (masterMute) {
2235 masterVolume = 0;
2236 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002237 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002238 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002239 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002240 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002241 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002242 masterVolume = (float)((v + (1 << 23)) >> 24);
2243 chain.clear();
2244 }
2245
2246 for (size_t i=0 ; i<count ; i++) {
2247 sp<Track> t = activeTracks[i].promote();
2248 if (t == 0) continue;
2249
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002250 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002251 Track* const track = t.get();
2252 audio_track_cblk_t* cblk = track->cblk();
2253
2254 // The first time a track is added we wait
2255 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002256 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002257 // make sure that we have enough frames to mix one full buffer.
2258 // enforce this condition only once to enable draining the buffer in case the client
2259 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002260 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002261 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002262 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002263 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002264 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002265 if (t->sampleRate() == (int)mSampleRate) {
2266 minFrames = mFrameCount;
2267 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002268 // +1 for rounding and +1 for additional sample needed for interpolation
2269 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2270 // add frames already consumed but not yet released by the resampler
2271 // because cblk->framesReady() will include these frames
2272 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2273 // the minimum track buffer size is normally twice the number of frames necessary
2274 // to fill one buffer and the resampler should not leave more than one buffer worth
2275 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002276 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002277 }
2278 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002279 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002280 !track->isPaused() && !track->isTerminated())
2281 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002282 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002283
2284 mixedTracks++;
2285
2286 // track->mainBuffer() != mMixBuffer means there is an effect chain
2287 // connected to the track
2288 chain.clear();
2289 if (track->mainBuffer() != mMixBuffer) {
2290 chain = getEffectChain_l(track->sessionId());
2291 // Delegate volume control to effect in track effect chain if needed
2292 if (chain != 0) {
2293 tracksWithEffect++;
2294 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002295 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002296 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002297 }
2298 }
2299
2300
2301 int param = AudioMixer::VOLUME;
2302 if (track->mFillingUpStatus == Track::FS_FILLED) {
2303 // no ramp for the first volume setting
2304 track->mFillingUpStatus = Track::FS_ACTIVE;
2305 if (track->mState == TrackBase::RESUMING) {
2306 track->mState = TrackBase::ACTIVE;
2307 param = AudioMixer::RAMP_VOLUME;
2308 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002309 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002310 } else if (cblk->server != 0) {
2311 // If the track is stopped before the first frame was mixed,
2312 // do not apply ramp
2313 param = AudioMixer::RAMP_VOLUME;
2314 }
2315
2316 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002317 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002318 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002319 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002320 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002321 if (track->isPausing()) {
2322 track->setPaused();
2323 }
2324 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002325
Mathias Agopian65ab4712010-07-14 17:59:35 -07002326 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002327 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002328 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002329 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002330 vl = vlr & 0xFFFF;
2331 vr = vlr >> 16;
2332 // track volumes come from shared memory, so can't be trusted and must be clamped
2333 if (vl > MAX_GAIN_INT) {
2334 ALOGV("Track left volume out of range: %04X", vl);
2335 vl = MAX_GAIN_INT;
2336 }
2337 if (vr > MAX_GAIN_INT) {
2338 ALOGV("Track right volume out of range: %04X", vr);
2339 vr = MAX_GAIN_INT;
2340 }
2341 // now apply the master volume and stream type volume
2342 vl = (uint32_t)(v * vl) << 12;
2343 vr = (uint32_t)(v * vr) << 12;
2344 // assuming master volume and stream type volume each go up to 1.0,
2345 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002346
Glenn Kasten05632a52012-01-03 14:22:33 -08002347 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2348 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002349 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002350 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002351 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002352 }
2353 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002354 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002355 // Delegate volume control to effect in track effect chain if needed
2356 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2357 // Do not ramp volume if volume is controlled by effect
2358 param = AudioMixer::VOLUME;
2359 track->mHasVolumeController = true;
2360 } else {
2361 // force no volume ramp when volume controller was just disabled or removed
2362 // from effect chain to avoid volume spike
2363 if (track->mHasVolumeController) {
2364 param = AudioMixer::VOLUME;
2365 }
2366 track->mHasVolumeController = false;
2367 }
2368
2369 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002370 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002371 vl = (vl + (1 << 11)) >> 12;
2372 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2373 vr = (vr + (1 << 11)) >> 12;
2374 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002375
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002376 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 -07002377
Mathias Agopian65ab4712010-07-14 17:59:35 -07002378 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002379 mAudioMixer->setBufferProvider(name, track);
2380 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002381
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002382 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2383 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2384 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002385 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002386 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002387 AudioMixer::TRACK,
2388 AudioMixer::FORMAT, (void *)track->format());
2389 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002390 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002391 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002392 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002393 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002394 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002395 AudioMixer::RESAMPLE,
2396 AudioMixer::SAMPLE_RATE,
2397 (void *)(cblk->sampleRate));
2398 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002399 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002400 AudioMixer::TRACK,
2401 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2402 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002403 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002404 AudioMixer::TRACK,
2405 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2406
2407 // reset retry count
2408 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002409 // If one track is ready, set the mixer ready if:
2410 // - the mixer was not ready during previous round OR
2411 // - no other track is not ready
2412 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2413 mixerStatus != MIXER_TRACKS_ENABLED) {
2414 mixerStatus = MIXER_TRACKS_READY;
2415 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002416 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002417 //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 -07002418 if (track->isStopped()) {
2419 track->reset();
2420 }
2421 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2422 // We have consumed all the buffers of this track.
2423 // Remove it from the list of active tracks.
2424 tracksToRemove->add(track);
2425 } else {
2426 // No buffers for this track. Give it a few chances to
2427 // fill a buffer, then remove it from active list.
2428 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002429 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002430 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002431 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002432 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002433 // If one track is not ready, mark the mixer also not ready if:
2434 // - the mixer was ready during previous round OR
2435 // - no other track is ready
2436 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2437 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002438 mixerStatus = MIXER_TRACKS_ENABLED;
2439 }
2440 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002441 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002442 }
2443 }
2444
2445 // remove all the tracks that need to be...
2446 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002447 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002448 for (size_t i=0 ; i<count ; i++) {
2449 const sp<Track>& track = tracksToRemove->itemAt(i);
2450 mActiveTracks.remove(track);
2451 if (track->mainBuffer() != mMixBuffer) {
2452 chain = getEffectChain_l(track->sessionId());
2453 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002454 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002455 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002456 }
2457 }
2458 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002459 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002460 }
2461 }
2462 }
2463
2464 // mix buffer must be cleared if all tracks are connected to an
2465 // effect chain as in this case the mixer will not write to
2466 // mix buffer and track effects will accumulate into it
2467 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2468 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2469 }
2470
Eric Laurent27741442012-01-17 19:20:12 -08002471 mPrevMixerStatus = mixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002472 return mixerStatus;
2473}
2474
Glenn Kastenfff6d712012-01-12 16:38:12 -08002475void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002476{
Steve Block3856b092011-10-20 11:56:00 +01002477 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002478 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002479 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002480
Mathias Agopian65ab4712010-07-14 17:59:35 -07002481 size_t size = mTracks.size();
2482 for (size_t i = 0; i < size; i++) {
2483 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08002484 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002485 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002486 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002487 }
2488 }
2489}
2490
Glenn Kastenfff6d712012-01-12 16:38:12 -08002491void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002492{
Steve Block3856b092011-10-20 11:56:00 +01002493 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002494 this, streamType, valid);
2495 Mutex::Autolock _l(mLock);
2496
2497 mStreamTypes[streamType].valid = valid;
2498}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002499
2500// getTrackName_l() must be called with ThreadBase::mLock held
2501int AudioFlinger::MixerThread::getTrackName_l()
2502{
2503 return mAudioMixer->getTrackName();
2504}
2505
2506// deleteTrackName_l() must be called with ThreadBase::mLock held
2507void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2508{
Steve Block3856b092011-10-20 11:56:00 +01002509 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002510 mAudioMixer->deleteTrackName(name);
2511}
2512
2513// checkForNewParameters_l() must be called with ThreadBase::mLock held
2514bool AudioFlinger::MixerThread::checkForNewParameters_l()
2515{
2516 bool reconfig = false;
2517
2518 while (!mNewParameters.isEmpty()) {
2519 status_t status = NO_ERROR;
2520 String8 keyValuePair = mNewParameters[0];
2521 AudioParameter param = AudioParameter(keyValuePair);
2522 int value;
2523
2524 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2525 reconfig = true;
2526 }
2527 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002528 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002529 status = BAD_VALUE;
2530 } else {
2531 reconfig = true;
2532 }
2533 }
2534 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002535 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002536 status = BAD_VALUE;
2537 } else {
2538 reconfig = true;
2539 }
2540 }
2541 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2542 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002543 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002544 // if frame count is changed after track creation
2545 if (!mTracks.isEmpty()) {
2546 status = INVALID_OPERATION;
2547 } else {
2548 reconfig = true;
2549 }
2550 }
2551 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002552 // when changing the audio output device, call addBatteryData to notify
2553 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002554 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002555 uint32_t params = 0;
2556 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002557 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002558 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2559 }
2560
2561 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002562 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002563 // check if any other device (except speaker) is on
2564 if (value & deviceWithoutSpeaker ) {
2565 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2566 }
2567
2568 if (params != 0) {
2569 addBatteryData(params);
2570 }
2571 }
2572
Mathias Agopian65ab4712010-07-14 17:59:35 -07002573 // forward device change to effects that have requested to be
2574 // aware of attached audio device.
2575 mDevice = (uint32_t)value;
2576 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002577 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002578 }
2579 }
2580
2581 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002582 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002583 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002584 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002585 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002586 mStandby = true;
2587 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002588 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002589 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002590 }
2591 if (status == NO_ERROR && reconfig) {
2592 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002593 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2594 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002595 readOutputParameters();
2596 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2597 for (size_t i = 0; i < mTracks.size() ; i++) {
2598 int name = getTrackName_l();
2599 if (name < 0) break;
2600 mTracks[i]->mName = name;
2601 // limit track sample rate to 2 x new output sample rate
2602 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2603 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2604 }
2605 }
2606 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2607 }
2608 }
2609
2610 mNewParameters.removeAt(0);
2611
2612 mParamStatus = status;
2613 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002614 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2615 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002616 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002617 }
2618 return reconfig;
2619}
2620
2621status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2622{
2623 const size_t SIZE = 256;
2624 char buffer[SIZE];
2625 String8 result;
2626
2627 PlaybackThread::dumpInternals(fd, args);
2628
2629 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2630 result.append(buffer);
2631 write(fd, result.string(), result.size());
2632 return NO_ERROR;
2633}
2634
Mathias Agopian65ab4712010-07-14 17:59:35 -07002635uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2636{
Eric Laurent60e18242010-07-29 06:50:24 -07002637 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002638}
2639
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002640uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2641{
2642 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2643}
2644
Mathias Agopian65ab4712010-07-14 17:59:35 -07002645// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002646AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2647 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002648 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002649 // mLeftVolFloat, mRightVolFloat
2650 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002651{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002652}
2653
2654AudioFlinger::DirectOutputThread::~DirectOutputThread()
2655{
2656}
2657
Mathias Agopian65ab4712010-07-14 17:59:35 -07002658void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2659{
2660 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002661 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002662 return;
2663 }
2664
2665 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002666 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002667 size_t count = mFrameCount * mChannelCount;
2668 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2669 int16_t *dst = mMixBuffer + count-1;
2670 while(count--) {
2671 *dst-- = (int16_t)(*src--^0x80) << 8;
2672 }
2673 }
2674
2675 size_t frameCount = mFrameCount;
2676 int16_t *out = mMixBuffer;
2677 if (ramp) {
2678 if (mChannelCount == 1) {
2679 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2680 int32_t vlInc = d / (int32_t)frameCount;
2681 int32_t vl = ((int32_t)mLeftVolShort << 16);
2682 do {
2683 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2684 out++;
2685 vl += vlInc;
2686 } while (--frameCount);
2687
2688 } else {
2689 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2690 int32_t vlInc = d / (int32_t)frameCount;
2691 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2692 int32_t vrInc = d / (int32_t)frameCount;
2693 int32_t vl = ((int32_t)mLeftVolShort << 16);
2694 int32_t vr = ((int32_t)mRightVolShort << 16);
2695 do {
2696 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2697 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2698 out += 2;
2699 vl += vlInc;
2700 vr += vrInc;
2701 } while (--frameCount);
2702 }
2703 } else {
2704 if (mChannelCount == 1) {
2705 do {
2706 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2707 out++;
2708 } while (--frameCount);
2709 } else {
2710 do {
2711 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2712 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2713 out += 2;
2714 } while (--frameCount);
2715 }
2716 }
2717
2718 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002719 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002720 size_t count = mFrameCount * mChannelCount;
2721 int16_t *src = mMixBuffer;
2722 uint8_t *dst = (uint8_t *)mMixBuffer;
2723 while(count--) {
2724 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2725 }
2726 }
2727
2728 mLeftVolShort = leftVol;
2729 mRightVolShort = rightVol;
2730}
2731
2732bool AudioFlinger::DirectOutputThread::threadLoop()
2733{
Glenn Kasten688a6402012-02-29 07:57:06 -08002734 // MixerThread has Vector instead of single trackToRemove
Mathias Agopian65ab4712010-07-14 17:59:35 -07002735 sp<Track> trackToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002736 // MixerThread does not have activeTrack here
Mathias Agopian65ab4712010-07-14 17:59:35 -07002737 sp<Track> activeTrack;
2738 nsecs_t standbyTime = systemTime();
Glenn Kasten688a6402012-02-29 07:57:06 -08002739 size_t mixBufferSize = mFrameCount * mFrameSize;
2740
2741 // MixerThread has relaxed timing: maxPeriod, lastWarning, longStandbyExit
2742
Mathias Agopian65ab4712010-07-14 17:59:35 -07002743 uint32_t activeSleepTime = activeSleepTimeUs();
2744 uint32_t idleSleepTime = idleSleepTimeUs();
2745 uint32_t sleepTime = idleSleepTime;
Glenn Kasten688a6402012-02-29 07:57:06 -08002746
2747 // MixerThread has sleepTimeShift and cpuStats
2748
Mathias Agopian65ab4712010-07-14 17:59:35 -07002749 // use shorter standby delay as on normal output to release
2750 // hardware resources as soon as possible
2751 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2752
Eric Laurentfeb0db62011-07-22 09:04:31 -07002753 acquireWakeLock();
2754
Mathias Agopian65ab4712010-07-14 17:59:35 -07002755 while (!exitPending())
2756 {
Glenn Kasten688a6402012-02-29 07:57:06 -08002757 // MixerThread has cpuStats.sample()
2758
Mathias Agopian65ab4712010-07-14 17:59:35 -07002759 bool rampVolume;
2760 uint16_t leftVol;
2761 uint16_t rightVol;
Glenn Kasten688a6402012-02-29 07:57:06 -08002762
Mathias Agopian65ab4712010-07-14 17:59:35 -07002763 Vector< sp<EffectChain> > effectChains;
2764
2765 processConfigEvents();
2766
Glenn Kasten5d4eeea2012-02-24 07:25:40 -08002767 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002768 { // scope for the mLock
2769
2770 Mutex::Autolock _l(mLock);
2771
2772 if (checkForNewParameters_l()) {
Glenn Kasten688a6402012-02-29 07:57:06 -08002773 mixBufferSize = mFrameCount * mFrameSize;
2774
2775 // different calculations here
2776 standbyDelay = microseconds(activeSleepTime*2);
2777
Mathias Agopian65ab4712010-07-14 17:59:35 -07002778 activeSleepTime = activeSleepTimeUs();
2779 idleSleepTime = idleSleepTimeUs();
2780 standbyDelay = microseconds(activeSleepTime*2);
2781 }
2782
2783 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002784 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2785 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002786 if (!mStandby) {
Glenn Kastenc0b52832012-02-24 11:18:09 -08002787 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07002788 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002789 mStandby = true;
2790 mBytesWritten = 0;
2791 }
2792
2793 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2794 // we're about to wait, flush the binder command buffer
2795 IPCThreadState::self()->flushCommands();
2796
2797 if (exitPending()) break;
2798
Eric Laurentfeb0db62011-07-22 09:04:31 -07002799 releaseWakeLock_l();
Glenn Kasten688a6402012-02-29 07:57:06 -08002800 // wait until we have something to do...
Glenn Kastenc0b52832012-02-24 11:18:09 -08002801 ALOGV("Thread %p type %d TID %d going to sleep", this, mType, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002802 mWaitWorkCV.wait(mLock);
Glenn Kastenc0b52832012-02-24 11:18:09 -08002803 ALOGV("Thread %p type %d TID %d waking up", this, mType, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002804 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002805
Glenn Kasten688a6402012-02-29 07:57:06 -08002806 // MixerThread has "mPrevMixerStatus = MIXER_IDLE"
Glenn Kasten37d825e2012-02-24 07:21:48 -08002807 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002808
Glenn Kasten688a6402012-02-29 07:57:06 -08002809 // MixerThread has different standbyDelay
Mathias Agopian65ab4712010-07-14 17:59:35 -07002810 standbyTime = systemTime() + standbyDelay;
2811 sleepTime = idleSleepTime;
Glenn Kasten688a6402012-02-29 07:57:06 -08002812 // MixerThread has "sleepTimeShift = 0"
Mathias Agopian65ab4712010-07-14 17:59:35 -07002813 continue;
2814 }
2815 }
2816
Glenn Kasten688a6402012-02-29 07:57:06 -08002817 // MixerThread has "mixerStatus = prepareTracks_l(...)"
2818
2819 // equivalent to MixerThread's lockEffectChains_l, but without the lock
2820 // FIXME - is it OK to omit the lock here?
Mathias Agopian65ab4712010-07-14 17:59:35 -07002821 effectChains = mEffectChains;
2822
2823 // find out which tracks need to be processed
2824 if (mActiveTracks.size() != 0) {
2825 sp<Track> t = mActiveTracks[0].promote();
2826 if (t == 0) continue;
2827
2828 Track* const track = t.get();
2829 audio_track_cblk_t* cblk = track->cblk();
2830
2831 // The first time a track is added we wait
2832 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002833 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834 !track->isPaused() && !track->isTerminated())
2835 {
Steve Block3856b092011-10-20 11:56:00 +01002836 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002837
2838 if (track->mFillingUpStatus == Track::FS_FILLED) {
2839 track->mFillingUpStatus = Track::FS_ACTIVE;
2840 mLeftVolFloat = mRightVolFloat = 0;
2841 mLeftVolShort = mRightVolShort = 0;
2842 if (track->mState == TrackBase::RESUMING) {
2843 track->mState = TrackBase::ACTIVE;
2844 rampVolume = true;
2845 }
2846 } else if (cblk->server != 0) {
2847 // If the track is stopped before the first frame was mixed,
2848 // do not apply ramp
2849 rampVolume = true;
2850 }
2851 // compute volume for this track
2852 float left, right;
2853 if (track->isMuted() || mMasterMute || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002854 mStreamTypes[track->streamType()].mute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002855 left = right = 0;
2856 if (track->isPausing()) {
2857 track->setPaused();
2858 }
2859 } else {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002860 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002861 float v = mMasterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002862 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002863 float v_clamped = v * (vlr & 0xFFFF);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002864 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2865 left = v_clamped/MAX_GAIN;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002866 v_clamped = v * (vlr >> 16);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002867 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2868 right = v_clamped/MAX_GAIN;
2869 }
2870
2871 if (left != mLeftVolFloat || right != mRightVolFloat) {
2872 mLeftVolFloat = left;
2873 mRightVolFloat = right;
2874
2875 // If audio HAL implements volume control,
2876 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002877 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002878 left = 1.0f;
2879 right = 1.0f;
2880 }
2881
2882 // Convert volumes from float to 8.24
2883 uint32_t vl = (uint32_t)(left * (1 << 24));
2884 uint32_t vr = (uint32_t)(right * (1 << 24));
2885
2886 // Delegate volume control to effect in track effect chain if needed
2887 // only one effect chain can be present on DirectOutputThread, so if
2888 // there is one, the track is connected to it
2889 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002890 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002891 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002892 rampVolume = false;
2893 }
2894 }
2895
2896 // Convert volumes from 8.24 to 4.12 format
2897 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2898 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2899 leftVol = (uint16_t)v_clamped;
2900 v_clamped = (vr + (1 << 11)) >> 12;
2901 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2902 rightVol = (uint16_t)v_clamped;
2903 } else {
2904 leftVol = mLeftVolShort;
2905 rightVol = mRightVolShort;
2906 rampVolume = false;
2907 }
2908
2909 // reset retry count
2910 track->mRetryCount = kMaxTrackRetriesDirect;
2911 activeTrack = t;
2912 mixerStatus = MIXER_TRACKS_READY;
2913 } else {
Steve Block3856b092011-10-20 11:56:00 +01002914 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002915 if (track->isStopped()) {
2916 track->reset();
2917 }
2918 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2919 // We have consumed all the buffers of this track.
2920 // Remove it from the list of active tracks.
2921 trackToRemove = track;
2922 } else {
2923 // No buffers for this track. Give it a few chances to
2924 // fill a buffer, then remove it from active list.
2925 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002926 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002927 trackToRemove = track;
2928 } else {
2929 mixerStatus = MIXER_TRACKS_ENABLED;
2930 }
2931 }
2932 }
2933 }
2934
2935 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002936 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002937 mActiveTracks.remove(trackToRemove);
2938 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002939 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002940 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002941 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002942 }
2943 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002944 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002945 }
2946 }
2947
Eric Laurentde070132010-07-13 04:45:46 -07002948 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002949 }
2950
Glenn Kastenf6b16782011-12-15 09:51:17 -08002951 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002952 AudioBufferProvider::Buffer buffer;
2953 size_t frameCount = mFrameCount;
Glenn Kastena1117922012-01-26 10:53:32 -08002954 int8_t *curBuf = (int8_t *)mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002955 // output audio to hardware
2956 while (frameCount) {
2957 buffer.frameCount = frameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08002958 activeTrack->getNextBuffer(&buffer);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002959 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002960 memset(curBuf, 0, frameCount * mFrameSize);
2961 break;
2962 }
2963 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2964 frameCount -= buffer.frameCount;
2965 curBuf += buffer.frameCount * mFrameSize;
2966 activeTrack->releaseBuffer(&buffer);
2967 }
2968 sleepTime = 0;
2969 standbyTime = systemTime() + standbyDelay;
2970 } else {
2971 if (sleepTime == 0) {
2972 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2973 sleepTime = activeSleepTime;
2974 } else {
2975 sleepTime = idleSleepTime;
2976 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002977 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002978 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2979 sleepTime = 0;
2980 }
2981 }
2982
2983 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002984 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002985 }
Glenn Kasten04743e92012-02-24 11:20:09 -08002986
2987 // only process effects if we're going to write
Mathias Agopian65ab4712010-07-14 17:59:35 -07002988 if (sleepTime == 0) {
Glenn Kasten688a6402012-02-29 07:57:06 -08002989
2990 // MixerThread does not have applyVolume
Mathias Agopian65ab4712010-07-14 17:59:35 -07002991 if (mixerStatus == MIXER_TRACKS_READY) {
2992 applyVolume(leftVol, rightVol, rampVolume);
2993 }
Glenn Kasten688a6402012-02-29 07:57:06 -08002994
Mathias Agopian65ab4712010-07-14 17:59:35 -07002995 for (size_t i = 0; i < effectChains.size(); i ++) {
2996 effectChains[i]->process_l();
2997 }
Glenn Kasten04743e92012-02-24 11:20:09 -08002998 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002999
Glenn Kasten04743e92012-02-24 11:20:09 -08003000 // enable changes in effect chain
3001 unlockEffectChains(effectChains);
3002
3003 // sleepTime == 0 means we must write to audio hardware
3004 if (sleepTime == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003005 mLastWriteTime = systemTime();
3006 mInWrite = true;
3007 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07003008 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003009 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
3010 mNumWrites++;
3011 mInWrite = false;
Glenn Kasten688a6402012-02-29 07:57:06 -08003012
3013 // MixerThread has write blocked detection here
3014
Mathias Agopian65ab4712010-07-14 17:59:35 -07003015 mStandby = false;
3016 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003017 usleep(sleepTime);
3018 }
3019
Glenn Kasten688a6402012-02-29 07:57:06 -08003020 // finally let go of removed track(s), without the lock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07003021 // since we can't guarantee the destructors won't acquire that
3022 // same lock.
3023 trackToRemove.clear();
3024 activeTrack.clear();
3025
3026 // Effect chains will be actually deleted here if they were removed from
3027 // mEffectChains list during mixing or effects processing
3028 effectChains.clear();
Glenn Kasten73ca0f52012-02-29 07:56:15 -08003029
3030 // FIXME Note that the above .clear() is no longer necessary since effectChains
3031 // is now local to this block, but will keep it for now (at least until merge done).
Mathias Agopian65ab4712010-07-14 17:59:35 -07003032 }
3033
Glenn Kasten688a6402012-02-29 07:57:06 -08003034 // put output stream into standby mode
Mathias Agopian65ab4712010-07-14 17:59:35 -07003035 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003036 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003037 }
3038
Eric Laurentfeb0db62011-07-22 09:04:31 -07003039 releaseWakeLock();
3040
Glenn Kastenc0b52832012-02-24 11:18:09 -08003041 ALOGV("Thread %p type %d exiting", this, mType);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003042 return false;
3043}
3044
3045// getTrackName_l() must be called with ThreadBase::mLock held
3046int AudioFlinger::DirectOutputThread::getTrackName_l()
3047{
3048 return 0;
3049}
3050
3051// deleteTrackName_l() must be called with ThreadBase::mLock held
3052void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3053{
3054}
3055
3056// checkForNewParameters_l() must be called with ThreadBase::mLock held
3057bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3058{
3059 bool reconfig = false;
3060
3061 while (!mNewParameters.isEmpty()) {
3062 status_t status = NO_ERROR;
3063 String8 keyValuePair = mNewParameters[0];
3064 AudioParameter param = AudioParameter(keyValuePair);
3065 int value;
3066
3067 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3068 // do not accept frame count changes if tracks are open as the track buffer
3069 // size depends on frame count and correct behavior would not be garantied
3070 // if frame count is changed after track creation
3071 if (!mTracks.isEmpty()) {
3072 status = INVALID_OPERATION;
3073 } else {
3074 reconfig = true;
3075 }
3076 }
3077 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003078 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003079 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003080 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003081 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003082 mStandby = true;
3083 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07003084 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003085 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003086 }
3087 if (status == NO_ERROR && reconfig) {
3088 readOutputParameters();
3089 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3090 }
3091 }
3092
3093 mNewParameters.removeAt(0);
3094
3095 mParamStatus = status;
3096 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003097 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3098 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003099 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003100 }
3101 return reconfig;
3102}
3103
3104uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
3105{
3106 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003107 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003108 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003109 } else {
3110 time = 10000;
3111 }
3112 return time;
3113}
3114
3115uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
3116{
3117 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003118 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003119 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003120 } else {
3121 time = 10000;
3122 }
3123 return time;
3124}
3125
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003126uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
3127{
3128 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003129 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003130 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3131 } else {
3132 time = 10000;
3133 }
3134 return time;
3135}
3136
3137
Mathias Agopian65ab4712010-07-14 17:59:35 -07003138// ----------------------------------------------------------------------------
3139
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003140AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003141 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003142 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3143 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003144{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003145 addOutputTrack(mainThread);
3146}
3147
3148AudioFlinger::DuplicatingThread::~DuplicatingThread()
3149{
3150 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3151 mOutputTracks[i]->destroy();
3152 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003153}
3154
3155bool AudioFlinger::DuplicatingThread::threadLoop()
3156{
3157 Vector< sp<Track> > tracksToRemove;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003158 nsecs_t standbyTime = systemTime();
Glenn Kasten688a6402012-02-29 07:57:06 -08003159 size_t mixBufferSize = mFrameCount * mFrameSize;
3160
3161 // Only in DuplicatingThread
Mathias Agopian65ab4712010-07-14 17:59:35 -07003162 SortedVector< sp<OutputTrack> > outputTracks;
3163 uint32_t writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08003164
Mathias Agopian65ab4712010-07-14 17:59:35 -07003165 uint32_t activeSleepTime = activeSleepTimeUs();
3166 uint32_t idleSleepTime = idleSleepTimeUs();
3167 uint32_t sleepTime = idleSleepTime;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003168
Eric Laurentfeb0db62011-07-22 09:04:31 -07003169 acquireWakeLock();
3170
Mathias Agopian65ab4712010-07-14 17:59:35 -07003171 while (!exitPending())
3172 {
Glenn Kasten688a6402012-02-29 07:57:06 -08003173 // MixerThread has cpuStats.sample
3174
Glenn Kasten73ca0f52012-02-29 07:56:15 -08003175 Vector< sp<EffectChain> > effectChains;
3176
Mathias Agopian65ab4712010-07-14 17:59:35 -07003177 processConfigEvents();
3178
Glenn Kasten5d4eeea2012-02-24 07:25:40 -08003179 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003180 { // scope for the mLock
3181
3182 Mutex::Autolock _l(mLock);
3183
3184 if (checkForNewParameters_l()) {
Glenn Kasten688a6402012-02-29 07:57:06 -08003185 mixBufferSize = mFrameCount * mFrameSize;
3186
3187 // Only in DuplicatingThread
Mathias Agopian65ab4712010-07-14 17:59:35 -07003188 updateWaitTime();
Glenn Kasten688a6402012-02-29 07:57:06 -08003189
Mathias Agopian65ab4712010-07-14 17:59:35 -07003190 activeSleepTime = activeSleepTimeUs();
3191 idleSleepTime = idleSleepTimeUs();
3192 }
3193
3194 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3195
Glenn Kasten688a6402012-02-29 07:57:06 -08003196 // Only in DuplicatingThread
Mathias Agopian65ab4712010-07-14 17:59:35 -07003197 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3198 outputTracks.add(mOutputTracks[i]);
3199 }
3200
3201 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08003202 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3203 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003204 if (!mStandby) {
Glenn Kasten688a6402012-02-29 07:57:06 -08003205 // DuplicatingThread implements standby by stopping all tracks
Mathias Agopian65ab4712010-07-14 17:59:35 -07003206 for (size_t i = 0; i < outputTracks.size(); i++) {
3207 outputTracks[i]->stop();
3208 }
3209 mStandby = true;
3210 mBytesWritten = 0;
3211 }
3212
3213 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3214 // we're about to wait, flush the binder command buffer
3215 IPCThreadState::self()->flushCommands();
3216 outputTracks.clear();
3217
3218 if (exitPending()) break;
3219
Eric Laurentfeb0db62011-07-22 09:04:31 -07003220 releaseWakeLock_l();
Glenn Kastenc0b52832012-02-24 11:18:09 -08003221 // wait until we have something to do...
3222 ALOGV("Thread %p type %d TID %d going to sleep", this, mType, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003223 mWaitWorkCV.wait(mLock);
Glenn Kastenc0b52832012-02-24 11:18:09 -08003224 ALOGV("Thread %p type %d TID %d waking up", this, mType, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003225 acquireWakeLock_l();
3226
Glenn Kasten688a6402012-02-29 07:57:06 -08003227 // MixerThread has "mPrevMixerStatus = MIXER_IDLE"
Glenn Kasten37d825e2012-02-24 07:21:48 -08003228 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003229
John Grossman4ff14ba2012-02-08 16:37:41 -08003230 standbyTime = systemTime() + mStandbyTimeInNsecs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003231 sleepTime = idleSleepTime;
Glenn Kasten688a6402012-02-29 07:57:06 -08003232 // MixerThread has sleepTimeShift
Mathias Agopian65ab4712010-07-14 17:59:35 -07003233 continue;
3234 }
3235 }
3236
3237 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3238
3239 // prevent any changes in effect chain list and in each effect chain
3240 // during mixing and effect process as the audio buffers could be deleted
3241 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003242 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003243 }
3244
Glenn Kasten688a6402012-02-29 07:57:06 -08003245 // Duplicating Thread is completely different here
Glenn Kastenf6b16782011-12-15 09:51:17 -08003246 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003247 // mix buffers...
3248 if (outputsReady(outputTracks)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08003249 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003250 } else {
3251 memset(mMixBuffer, 0, mixBufferSize);
3252 }
3253 sleepTime = 0;
3254 writeFrames = mFrameCount;
3255 } else {
3256 if (sleepTime == 0) {
3257 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3258 sleepTime = activeSleepTime;
3259 } else {
3260 sleepTime = idleSleepTime;
3261 }
3262 } else if (mBytesWritten != 0) {
3263 // flush remaining overflow buffers in output tracks
3264 for (size_t i = 0; i < outputTracks.size(); i++) {
3265 if (outputTracks[i]->isActive()) {
3266 sleepTime = 0;
3267 writeFrames = 0;
3268 memset(mMixBuffer, 0, mixBufferSize);
3269 break;
3270 }
3271 }
3272 }
3273 }
3274
3275 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003276 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003277 }
Glenn Kasten04743e92012-02-24 11:20:09 -08003278
3279 // only process effects if we're going to write
Mathias Agopian65ab4712010-07-14 17:59:35 -07003280 if (sleepTime == 0) {
3281 for (size_t i = 0; i < effectChains.size(); i ++) {
3282 effectChains[i]->process_l();
3283 }
Glenn Kasten04743e92012-02-24 11:20:09 -08003284 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003285
Glenn Kasten04743e92012-02-24 11:20:09 -08003286 // enable changes in effect chain
3287 unlockEffectChains(effectChains);
3288
3289 // sleepTime == 0 means we must write to audio hardware
3290 if (sleepTime == 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08003291 standbyTime = systemTime() + mStandbyTimeInNsecs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003292 for (size_t i = 0; i < outputTracks.size(); i++) {
3293 outputTracks[i]->write(mMixBuffer, writeFrames);
3294 }
3295 mStandby = false;
3296 mBytesWritten += mixBufferSize;
Glenn Kasten688a6402012-02-29 07:57:06 -08003297
3298 // MixerThread has write blocked detection here
3299
Mathias Agopian65ab4712010-07-14 17:59:35 -07003300 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003301 usleep(sleepTime);
3302 }
3303
Glenn Kasten688a6402012-02-29 07:57:06 -08003304 // finally let go of removed track(s), without the lock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07003305 // since we can't guarantee the destructors won't acquire that
3306 // same lock.
3307 tracksToRemove.clear();
3308 outputTracks.clear();
3309
3310 // Effect chains will be actually deleted here if they were removed from
3311 // mEffectChains list during mixing or effects processing
3312 effectChains.clear();
Glenn Kasten73ca0f52012-02-29 07:56:15 -08003313
3314 // FIXME Note that the above .clear() is no longer necessary since effectChains
3315 // is now local to this block, but will keep it for now (at least until merge done).
Mathias Agopian65ab4712010-07-14 17:59:35 -07003316 }
3317
Glenn Kasten688a6402012-02-29 07:57:06 -08003318 // MixerThread and DirectOutpuThread have standby here,
3319 // but for DuplicatingThread this is handled by the outputTracks
3320
Eric Laurentfeb0db62011-07-22 09:04:31 -07003321 releaseWakeLock();
3322
Glenn Kastenc0b52832012-02-24 11:18:09 -08003323 ALOGV("Thread %p type %d exiting", this, mType);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003324 return false;
3325}
3326
3327void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3328{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003329 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003330 // FIXME explain this formula
Mathias Agopian65ab4712010-07-14 17:59:35 -07003331 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003332 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003333 this,
3334 mSampleRate,
3335 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003336 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003337 frameCount);
3338 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003339 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003340 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003341 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003342 updateWaitTime();
3343 }
3344}
3345
3346void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3347{
3348 Mutex::Autolock _l(mLock);
3349 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003350 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003351 mOutputTracks[i]->destroy();
3352 mOutputTracks.removeAt(i);
3353 updateWaitTime();
3354 return;
3355 }
3356 }
Steve Block3856b092011-10-20 11:56:00 +01003357 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003358}
3359
3360void AudioFlinger::DuplicatingThread::updateWaitTime()
3361{
3362 mWaitTimeMs = UINT_MAX;
3363 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3364 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003365 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003366 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3367 if (waitTimeMs < mWaitTimeMs) {
3368 mWaitTimeMs = waitTimeMs;
3369 }
3370 }
3371 }
3372}
3373
3374
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003375bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003376{
3377 for (size_t i = 0; i < outputTracks.size(); i++) {
3378 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3379 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003380 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003381 return false;
3382 }
3383 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3384 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003385 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003386 return false;
3387 }
3388 }
3389 return true;
3390}
3391
3392uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3393{
3394 return (mWaitTimeMs * 1000) / 2;
3395}
3396
3397// ----------------------------------------------------------------------------
3398
3399// TrackBase constructor must be called with AudioFlinger::mLock held
3400AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003401 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003402 const sp<Client>& client,
3403 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003404 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003405 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003406 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003407 const sp<IMemory>& sharedBuffer,
3408 int sessionId)
3409 : RefBase(),
3410 mThread(thread),
3411 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003412 mCblk(NULL),
3413 // mBuffer
3414 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003415 mFrameCount(0),
3416 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003417 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003418 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003419 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003420 // mChannelCount
3421 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003422{
Steve Block3856b092011-10-20 11:56:00 +01003423 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003424
Steve Blockb8a80522011-12-20 16:23:08 +00003425 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003426 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003427 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003428 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3429 if (sharedBuffer == 0) {
3430 size += bufferSize;
3431 }
3432
3433 if (client != NULL) {
3434 mCblkMemory = client->heap()->allocate(size);
3435 if (mCblkMemory != 0) {
3436 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003437 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003438 new(mCblk) audio_track_cblk_t();
3439 // clear all buffers
3440 mCblk->frameCount = frameCount;
3441 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003442 mChannelCount = channelCount;
3443 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003444 if (sharedBuffer == 0) {
3445 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3446 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3447 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003448 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003449 mCblk->flags = CBLK_UNDERRUN_ON;
3450 } else {
3451 mBuffer = sharedBuffer->pointer();
3452 }
3453 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3454 }
3455 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003456 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003457 client->heap()->dump("AudioTrack");
3458 return;
3459 }
3460 } else {
3461 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003462 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003463 new(mCblk) audio_track_cblk_t();
3464 // clear all buffers
3465 mCblk->frameCount = frameCount;
3466 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003467 mChannelCount = channelCount;
3468 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003469 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3470 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3471 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003472 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003473 mCblk->flags = CBLK_UNDERRUN_ON;
3474 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003475 }
3476}
3477
3478AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3479{
Glenn Kastena0d68332012-01-27 16:47:15 -08003480 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003481 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003482 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003483 } else {
3484 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003485 }
3486 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003487 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003488 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003489 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003490 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003491 // If the client's reference count drops to zero, the associated destructor
3492 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3493 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003494 mClient.clear();
3495 }
3496}
3497
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003498// AudioBufferProvider interface
3499// getNextBuffer() = 0;
3500// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07003501void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3502{
Glenn Kastene0feee32011-12-13 11:53:26 -08003503 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003504 mFrameCount = buffer->frameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003505 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003506 buffer->frameCount = 0;
3507}
3508
3509bool AudioFlinger::ThreadBase::TrackBase::step() {
3510 bool result;
3511 audio_track_cblk_t* cblk = this->cblk();
3512
3513 result = cblk->stepServer(mFrameCount);
3514 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003515 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003516 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003517 }
3518 return result;
3519}
3520
3521void AudioFlinger::ThreadBase::TrackBase::reset() {
3522 audio_track_cblk_t* cblk = this->cblk();
3523
3524 cblk->user = 0;
3525 cblk->server = 0;
3526 cblk->userBase = 0;
3527 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003528 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01003529 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003530}
3531
Mathias Agopian65ab4712010-07-14 17:59:35 -07003532int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3533 return (int)mCblk->sampleRate;
3534}
3535
Mathias Agopian65ab4712010-07-14 17:59:35 -07003536void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3537 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003538 size_t frameSize = cblk->frameSize;
3539 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3540 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003541
3542 // Check validity of returned pointer in case the track control block would have been corrupted.
3543 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003544 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003545 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 -07003546 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003547 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003548 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003549 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003550 }
3551
3552 return bufferStart;
3553}
3554
3555// ----------------------------------------------------------------------------
3556
3557// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3558AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003559 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003560 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003561 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003562 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003563 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003564 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003565 int frameCount,
3566 const sp<IMemory>& sharedBuffer,
3567 int sessionId)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003568 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003569 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3570 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003571{
3572 if (mCblk != NULL) {
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003573 if (thread != NULL) {
3574 mName = thread->getTrackName_l();
3575 mMainBuffer = thread->mixBuffer();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003576 }
Glenn Kasten23d82a92012-02-03 11:10:00 -08003577 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003578 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003579 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003580 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003581 mStreamType = streamType;
3582 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3583 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003584 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003585 }
3586}
3587
3588AudioFlinger::PlaybackThread::Track::~Track()
3589{
Steve Block3856b092011-10-20 11:56:00 +01003590 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003591 sp<ThreadBase> thread = mThread.promote();
3592 if (thread != 0) {
3593 Mutex::Autolock _l(thread->mLock);
3594 mState = TERMINATED;
3595 }
3596}
3597
3598void AudioFlinger::PlaybackThread::Track::destroy()
3599{
3600 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3601 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08003602 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003603 // we must acquire a strong reference on this Track before locking mLock
3604 // here so that the destructor is called only when exiting this function.
3605 // On the other hand, as long as Track::destroy() is only called by
3606 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3607 // this Track with its member mTrack.
3608 sp<Track> keep(this);
3609 { // scope for mLock
3610 sp<ThreadBase> thread = mThread.promote();
3611 if (thread != 0) {
3612 if (!isOutputTrack()) {
3613 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08003614 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003615
3616 // to track the speaker usage
3617 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003618 }
3619 AudioSystem::releaseOutput(thread->id());
3620 }
3621 Mutex::Autolock _l(thread->mLock);
3622 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3623 playbackThread->destroyTrack_l(this);
3624 }
3625 }
3626}
3627
3628void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3629{
Glenn Kasten83d86532012-01-17 14:39:34 -08003630 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003631 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 -07003632 mName - AudioMixer::TRACK0,
Glenn Kasten44deb052012-02-05 18:09:08 -08003633 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003634 mStreamType,
3635 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003636 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003637 mSessionId,
3638 mFrameCount,
3639 mState,
3640 mMute,
3641 mFillingUpStatus,
3642 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003643 vlr & 0xFFFF,
3644 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003645 mCblk->server,
3646 mCblk->user,
3647 (int)mMainBuffer,
3648 (int)mAuxBuffer);
3649}
3650
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003651// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08003652status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
3653 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003654{
3655 audio_track_cblk_t* cblk = this->cblk();
3656 uint32_t framesReady;
3657 uint32_t framesReq = buffer->frameCount;
3658
3659 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003660 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003661 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003662 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003663 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003664 }
3665
3666 framesReady = cblk->framesReady();
3667
Glenn Kastenf6b16782011-12-15 09:51:17 -08003668 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003669 uint32_t s = cblk->server;
3670 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3671
3672 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3673 if (framesReq > framesReady) {
3674 framesReq = framesReady;
3675 }
3676 if (s + framesReq > bufferEnd) {
3677 framesReq = bufferEnd - s;
3678 }
3679
3680 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003681 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003682
3683 buffer->frameCount = framesReq;
3684 return NO_ERROR;
3685 }
3686
3687getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003688 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003689 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003690 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003691 return NOT_ENOUGH_DATA;
3692}
3693
John Grossman4ff14ba2012-02-08 16:37:41 -08003694uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const{
3695 return mCblk->framesReady();
3696}
3697
Mathias Agopian65ab4712010-07-14 17:59:35 -07003698bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003699 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003700
John Grossman4ff14ba2012-02-08 16:37:41 -08003701 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003702 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3703 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003704 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003705 return true;
3706 }
3707 return false;
3708}
3709
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003710status_t AudioFlinger::PlaybackThread::Track::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003711{
3712 status_t status = NO_ERROR;
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003713 ALOGV("start(%d), calling pid %d session %d tid %d",
3714 mName, IPCThreadState::self()->getCallingPid(), mSessionId, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003715 sp<ThreadBase> thread = mThread.promote();
3716 if (thread != 0) {
3717 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003718 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003719 // here the track could be either new, or restarted
3720 // in both cases "unstop" the track
3721 if (mState == PAUSED) {
3722 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003723 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003724 } else {
3725 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003726 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003727 }
3728
3729 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3730 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003731 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003732 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003733
3734 // to track the speaker usage
3735 if (status == NO_ERROR) {
3736 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3737 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003738 }
3739 if (status == NO_ERROR) {
3740 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3741 playbackThread->addTrack_l(this);
3742 } else {
3743 mState = state;
3744 }
3745 } else {
3746 status = BAD_VALUE;
3747 }
3748 return status;
3749}
3750
3751void AudioFlinger::PlaybackThread::Track::stop()
3752{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003753 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003754 sp<ThreadBase> thread = mThread.promote();
3755 if (thread != 0) {
3756 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003757 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003758 if (mState > STOPPED) {
3759 mState = STOPPED;
3760 // If the track is not active (PAUSED and buffers full), flush buffers
3761 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3762 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3763 reset();
3764 }
Steve Block3856b092011-10-20 11:56:00 +01003765 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003766 }
3767 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3768 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003769 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003770 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003771
3772 // to track the speaker usage
3773 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003774 }
3775 }
3776}
3777
3778void AudioFlinger::PlaybackThread::Track::pause()
3779{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003780 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003781 sp<ThreadBase> thread = mThread.promote();
3782 if (thread != 0) {
3783 Mutex::Autolock _l(thread->mLock);
3784 if (mState == ACTIVE || mState == RESUMING) {
3785 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003786 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003787 if (!isOutputTrack()) {
3788 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003789 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003790 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003791
3792 // to track the speaker usage
3793 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003794 }
3795 }
3796 }
3797}
3798
3799void AudioFlinger::PlaybackThread::Track::flush()
3800{
Steve Block3856b092011-10-20 11:56:00 +01003801 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003802 sp<ThreadBase> thread = mThread.promote();
3803 if (thread != 0) {
3804 Mutex::Autolock _l(thread->mLock);
3805 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3806 return;
3807 }
3808 // No point remaining in PAUSED state after a flush => go to
3809 // STOPPED state
3810 mState = STOPPED;
3811
Eric Laurent38ccae22011-03-28 18:37:07 -07003812 // do not reset the track if it is still in the process of being stopped or paused.
3813 // this will be done by prepareTracks_l() when the track is stopped.
3814 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3815 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3816 reset();
3817 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003818 }
3819}
3820
3821void AudioFlinger::PlaybackThread::Track::reset()
3822{
3823 // Do not reset twice to avoid discarding data written just after a flush and before
3824 // the audioflinger thread detects the track is stopped.
3825 if (!mResetDone) {
3826 TrackBase::reset();
3827 // Force underrun condition to avoid false underrun callback until first data is
3828 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003829 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3830 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003831 mFillingUpStatus = FS_FILLING;
3832 mResetDone = true;
3833 }
3834}
3835
3836void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3837{
3838 mMute = muted;
3839}
3840
Mathias Agopian65ab4712010-07-14 17:59:35 -07003841status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3842{
3843 status_t status = DEAD_OBJECT;
3844 sp<ThreadBase> thread = mThread.promote();
3845 if (thread != 0) {
3846 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3847 status = playbackThread->attachAuxEffect(this, EffectId);
3848 }
3849 return status;
3850}
3851
3852void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3853{
3854 mAuxEffectId = EffectId;
3855 mAuxBuffer = buffer;
3856}
3857
John Grossman4ff14ba2012-02-08 16:37:41 -08003858// timed audio tracks
3859
3860sp<AudioFlinger::PlaybackThread::TimedTrack>
3861AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003862 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003863 const sp<Client>& client,
3864 audio_stream_type_t streamType,
3865 uint32_t sampleRate,
3866 audio_format_t format,
3867 uint32_t channelMask,
3868 int frameCount,
3869 const sp<IMemory>& sharedBuffer,
3870 int sessionId) {
3871 if (!client->reserveTimedTrack())
3872 return NULL;
3873
3874 sp<TimedTrack> track = new TimedTrack(
3875 thread, client, streamType, sampleRate, format, channelMask, frameCount,
3876 sharedBuffer, sessionId);
3877
3878 if (track == NULL) {
3879 client->releaseTimedTrack();
3880 return NULL;
3881 }
3882
3883 return track;
3884}
3885
3886AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003887 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003888 const sp<Client>& client,
3889 audio_stream_type_t streamType,
3890 uint32_t sampleRate,
3891 audio_format_t format,
3892 uint32_t channelMask,
3893 int frameCount,
3894 const sp<IMemory>& sharedBuffer,
3895 int sessionId)
3896 : Track(thread, client, streamType, sampleRate, format, channelMask,
3897 frameCount, sharedBuffer, sessionId),
3898 mTimedSilenceBuffer(NULL),
3899 mTimedSilenceBufferSize(0),
3900 mTimedAudioOutputOnTime(false),
3901 mMediaTimeTransformValid(false)
3902{
3903 LocalClock lc;
3904 mLocalTimeFreq = lc.getLocalFreq();
3905
3906 mLocalTimeToSampleTransform.a_zero = 0;
3907 mLocalTimeToSampleTransform.b_zero = 0;
3908 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3909 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3910 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3911 &mLocalTimeToSampleTransform.a_to_b_denom);
3912}
3913
3914AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3915 mClient->releaseTimedTrack();
3916 delete [] mTimedSilenceBuffer;
3917}
3918
3919status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3920 size_t size, sp<IMemory>* buffer) {
3921
3922 Mutex::Autolock _l(mTimedBufferQueueLock);
3923
3924 trimTimedBufferQueue_l();
3925
3926 // lazily initialize the shared memory heap for timed buffers
3927 if (mTimedMemoryDealer == NULL) {
3928 const int kTimedBufferHeapSize = 512 << 10;
3929
3930 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3931 "AudioFlingerTimed");
3932 if (mTimedMemoryDealer == NULL)
3933 return NO_MEMORY;
3934 }
3935
3936 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3937 if (newBuffer == NULL) {
3938 newBuffer = mTimedMemoryDealer->allocate(size);
3939 if (newBuffer == NULL)
3940 return NO_MEMORY;
3941 }
3942
3943 *buffer = newBuffer;
3944 return NO_ERROR;
3945}
3946
3947// caller must hold mTimedBufferQueueLock
3948void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
3949 int64_t mediaTimeNow;
3950 {
3951 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3952 if (!mMediaTimeTransformValid)
3953 return;
3954
3955 int64_t targetTimeNow;
3956 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
3957 ? mCCHelper.getCommonTime(&targetTimeNow)
3958 : mCCHelper.getLocalTime(&targetTimeNow);
3959
3960 if (OK != res)
3961 return;
3962
3963 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
3964 &mediaTimeNow)) {
3965 return;
3966 }
3967 }
3968
3969 size_t trimIndex;
3970 for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
3971 if (mTimedBufferQueue[trimIndex].pts() > mediaTimeNow)
3972 break;
3973 }
3974
3975 if (trimIndex) {
3976 mTimedBufferQueue.removeItemsAt(0, trimIndex);
3977 }
3978}
3979
3980status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
3981 const sp<IMemory>& buffer, int64_t pts) {
3982
3983 {
3984 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3985 if (!mMediaTimeTransformValid)
3986 return INVALID_OPERATION;
3987 }
3988
3989 Mutex::Autolock _l(mTimedBufferQueueLock);
3990
3991 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
3992
3993 return NO_ERROR;
3994}
3995
3996status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
3997 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
3998
3999 ALOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
4000 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4001 target);
4002
4003 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4004 target == TimedAudioTrack::COMMON_TIME)) {
4005 return BAD_VALUE;
4006 }
4007
4008 Mutex::Autolock lock(mMediaTimeTransformLock);
4009 mMediaTimeTransform = xform;
4010 mMediaTimeTransformTarget = target;
4011 mMediaTimeTransformValid = true;
4012
4013 return NO_ERROR;
4014}
4015
4016#define min(a, b) ((a) < (b) ? (a) : (b))
4017
4018// implementation of getNextBuffer for tracks whose buffers have timestamps
4019status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4020 AudioBufferProvider::Buffer* buffer, int64_t pts)
4021{
4022 if (pts == AudioBufferProvider::kInvalidPTS) {
4023 buffer->raw = 0;
4024 buffer->frameCount = 0;
4025 return INVALID_OPERATION;
4026 }
4027
John Grossman4ff14ba2012-02-08 16:37:41 -08004028 Mutex::Autolock _l(mTimedBufferQueueLock);
4029
4030 while (true) {
4031
4032 // if we have no timed buffers, then fail
4033 if (mTimedBufferQueue.isEmpty()) {
4034 buffer->raw = 0;
4035 buffer->frameCount = 0;
4036 return NOT_ENOUGH_DATA;
4037 }
4038
4039 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4040
4041 // calculate the PTS of the head of the timed buffer queue expressed in
4042 // local time
4043 int64_t headLocalPTS;
4044 {
4045 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4046
4047 assert(mMediaTimeTransformValid);
4048
4049 if (mMediaTimeTransform.a_to_b_denom == 0) {
4050 // the transform represents a pause, so yield silence
4051 timedYieldSilence(buffer->frameCount, buffer);
4052 return NO_ERROR;
4053 }
4054
4055 int64_t transformedPTS;
4056 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4057 &transformedPTS)) {
4058 // the transform failed. this shouldn't happen, but if it does
4059 // then just drop this buffer
4060 ALOGW("timedGetNextBuffer transform failed");
4061 buffer->raw = 0;
4062 buffer->frameCount = 0;
4063 mTimedBufferQueue.removeAt(0);
4064 return NO_ERROR;
4065 }
4066
4067 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
4068 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
4069 &headLocalPTS)) {
4070 buffer->raw = 0;
4071 buffer->frameCount = 0;
4072 return INVALID_OPERATION;
4073 }
4074 } else {
4075 headLocalPTS = transformedPTS;
4076 }
4077 }
4078
4079 // adjust the head buffer's PTS to reflect the portion of the head buffer
4080 // that has already been consumed
4081 int64_t effectivePTS = headLocalPTS +
4082 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4083
4084 // Calculate the delta in samples between the head of the input buffer
4085 // queue and the start of the next output buffer that will be written.
4086 // If the transformation fails because of over or underflow, it means
4087 // that the sample's position in the output stream is so far out of
4088 // whack that it should just be dropped.
4089 int64_t sampleDelta;
4090 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4091 ALOGV("*** head buffer is too far from PTS: dropped buffer");
4092 mTimedBufferQueue.removeAt(0);
4093 continue;
4094 }
4095 if (!mLocalTimeToSampleTransform.doForwardTransform(
4096 (effectivePTS - pts) << 32, &sampleDelta)) {
4097 ALOGV("*** too late during sample rate transform: dropped buffer");
4098 mTimedBufferQueue.removeAt(0);
4099 continue;
4100 }
4101
4102 ALOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
4103 __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
4104 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
4105 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
4106
4107 // if the delta between the ideal placement for the next input sample and
4108 // the current output position is within this threshold, then we will
4109 // concatenate the next input samples to the previous output
4110 const int64_t kSampleContinuityThreshold =
4111 (static_cast<int64_t>(sampleRate()) << 32) / 10;
4112
4113 // if this is the first buffer of audio that we're emitting from this track
4114 // then it should be almost exactly on time.
4115 const int64_t kSampleStartupThreshold = 1LL << 32;
4116
4117 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
4118 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
4119 // the next input is close enough to being on time, so concatenate it
4120 // with the last output
4121 timedYieldSamples(buffer);
4122
4123 ALOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4124 return NO_ERROR;
4125 } else if (sampleDelta > 0) {
4126 // the gap between the current output position and the proper start of
4127 // the next input sample is too big, so fill it with silence
4128 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4129
4130 timedYieldSilence(framesUntilNextInput, buffer);
4131 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4132 return NO_ERROR;
4133 } else {
4134 // the next input sample is late
4135 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4136 size_t onTimeSamplePosition =
4137 head.position() + lateFrames * mCblk->frameSize;
4138
4139 if (onTimeSamplePosition > head.buffer()->size()) {
4140 // all the remaining samples in the head are too late, so
4141 // drop it and move on
4142 ALOGV("*** too late: dropped buffer");
4143 mTimedBufferQueue.removeAt(0);
4144 continue;
4145 } else {
4146 // skip over the late samples
4147 head.setPosition(onTimeSamplePosition);
4148
4149 // yield the available samples
4150 timedYieldSamples(buffer);
4151
4152 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4153 return NO_ERROR;
4154 }
4155 }
4156 }
4157}
4158
4159// Yield samples from the timed buffer queue head up to the given output
4160// buffer's capacity.
4161//
4162// Caller must hold mTimedBufferQueueLock
4163void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples(
4164 AudioBufferProvider::Buffer* buffer) {
4165
4166 const TimedBuffer& head = mTimedBufferQueue[0];
4167
4168 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4169 head.position());
4170
4171 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4172 mCblk->frameSize);
4173 size_t framesRequested = buffer->frameCount;
4174 buffer->frameCount = min(framesLeftInHead, framesRequested);
4175
4176 mTimedAudioOutputOnTime = true;
4177}
4178
4179// Yield samples of silence up to the given output buffer's capacity
4180//
4181// Caller must hold mTimedBufferQueueLock
4182void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence(
4183 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4184
4185 // lazily allocate a buffer filled with silence
4186 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4187 delete [] mTimedSilenceBuffer;
4188 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4189 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4190 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4191 }
4192
4193 buffer->raw = mTimedSilenceBuffer;
4194 size_t framesRequested = buffer->frameCount;
4195 buffer->frameCount = min(numFrames, framesRequested);
4196
4197 mTimedAudioOutputOnTime = false;
4198}
4199
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004200// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004201void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4202 AudioBufferProvider::Buffer* buffer) {
4203
4204 Mutex::Autolock _l(mTimedBufferQueueLock);
4205
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004206 // If the buffer which was just released is part of the buffer at the head
4207 // of the queue, be sure to update the amt of the buffer which has been
4208 // consumed. If the buffer being returned is not part of the head of the
4209 // queue, its either because the buffer is part of the silence buffer, or
4210 // because the head of the timed queue was trimmed after the mixer called
4211 // getNextBuffer but before the mixer called releaseBuffer.
4212 if ((buffer->raw != mTimedSilenceBuffer) && mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004213 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004214
4215 void* start = head.buffer()->pointer();
Glenn Kastenf063b492012-02-17 16:24:10 -08004216 void* end = (char *) head.buffer()->pointer() + head.buffer()->size();
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004217
4218 if ((buffer->raw >= start) && (buffer->raw <= end)) {
4219 head.setPosition(head.position() +
4220 (buffer->frameCount * mCblk->frameSize));
4221 if (static_cast<size_t>(head.position()) >= head.buffer()->size()) {
4222 mTimedBufferQueue.removeAt(0);
4223 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004224 }
4225 }
4226
4227 buffer->raw = 0;
4228 buffer->frameCount = 0;
4229}
4230
4231uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4232 Mutex::Autolock _l(mTimedBufferQueueLock);
4233
4234 uint32_t frames = 0;
4235 for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4236 const TimedBuffer& tb = mTimedBufferQueue[i];
4237 frames += (tb.buffer()->size() - tb.position()) / mCblk->frameSize;
4238 }
4239
4240 return frames;
4241}
4242
4243AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4244 : mPTS(0), mPosition(0) {}
4245
4246AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4247 const sp<IMemory>& buffer, int64_t pts)
4248 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4249
Mathias Agopian65ab4712010-07-14 17:59:35 -07004250// ----------------------------------------------------------------------------
4251
4252// RecordTrack constructor must be called with AudioFlinger::mLock held
4253AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004254 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004255 const sp<Client>& client,
4256 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004257 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004258 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004259 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004260 int sessionId)
4261 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004262 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004263 mOverflow(false)
4264{
4265 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01004266 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07004267 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004268 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07004269 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004270 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004271 } else {
4272 mCblk->frameSize = sizeof(int8_t);
4273 }
4274 }
4275}
4276
4277AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4278{
4279 sp<ThreadBase> thread = mThread.promote();
4280 if (thread != 0) {
4281 AudioSystem::releaseInput(thread->id());
4282 }
4283}
4284
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004285// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004286status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004287{
4288 audio_track_cblk_t* cblk = this->cblk();
4289 uint32_t framesAvail;
4290 uint32_t framesReq = buffer->frameCount;
4291
4292 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004293 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004294 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004295 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004296 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004297 }
4298
4299 framesAvail = cblk->framesAvailable_l();
4300
Glenn Kastenf6b16782011-12-15 09:51:17 -08004301 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004302 uint32_t s = cblk->server;
4303 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4304
4305 if (framesReq > framesAvail) {
4306 framesReq = framesAvail;
4307 }
4308 if (s + framesReq > bufferEnd) {
4309 framesReq = bufferEnd - s;
4310 }
4311
4312 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004313 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004314
4315 buffer->frameCount = framesReq;
4316 return NO_ERROR;
4317 }
4318
4319getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004320 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004321 buffer->frameCount = 0;
4322 return NOT_ENOUGH_DATA;
4323}
4324
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004325status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004326{
4327 sp<ThreadBase> thread = mThread.promote();
4328 if (thread != 0) {
4329 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004330 return recordThread->start(this, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004331 } else {
4332 return BAD_VALUE;
4333 }
4334}
4335
4336void AudioFlinger::RecordThread::RecordTrack::stop()
4337{
4338 sp<ThreadBase> thread = mThread.promote();
4339 if (thread != 0) {
4340 RecordThread *recordThread = (RecordThread *)thread.get();
4341 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004342 TrackBase::reset();
4343 // Force overerrun condition to avoid false overrun callback until first data is
4344 // read from buffer
4345 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004346 }
4347}
4348
4349void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4350{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004351 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004352 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004353 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004354 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004355 mSessionId,
4356 mFrameCount,
4357 mState,
4358 mCblk->sampleRate,
4359 mCblk->server,
4360 mCblk->user);
4361}
4362
4363
4364// ----------------------------------------------------------------------------
4365
4366AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004367 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004368 DuplicatingThread *sourceThread,
4369 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004370 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004371 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004372 int frameCount)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004373 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004374 mActive(false), mSourceThread(sourceThread)
4375{
4376
Mathias Agopian65ab4712010-07-14 17:59:35 -07004377 if (mCblk != NULL) {
4378 mCblk->flags |= CBLK_DIRECTION_OUT;
4379 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004380 mOutBuffer.frameCount = 0;
4381 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01004382 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004383 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4384 mCblk, mBuffer, mCblk->buffers,
4385 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004386 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004387 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004388 }
4389}
4390
4391AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4392{
4393 clearBufferQueue();
4394}
4395
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004396status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004397{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004398 status_t status = Track::start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004399 if (status != NO_ERROR) {
4400 return status;
4401 }
4402
4403 mActive = true;
4404 mRetryCount = 127;
4405 return status;
4406}
4407
4408void AudioFlinger::PlaybackThread::OutputTrack::stop()
4409{
4410 Track::stop();
4411 clearBufferQueue();
4412 mOutBuffer.frameCount = 0;
4413 mActive = false;
4414}
4415
4416bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4417{
4418 Buffer *pInBuffer;
4419 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004420 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004421 bool outputBufferFull = false;
4422 inBuffer.frameCount = frames;
4423 inBuffer.i16 = data;
4424
4425 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4426
4427 if (!mActive && frames != 0) {
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004428 start(0);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004429 sp<ThreadBase> thread = mThread.promote();
4430 if (thread != 0) {
4431 MixerThread *mixerThread = (MixerThread *)thread.get();
4432 if (mCblk->frameCount > frames){
4433 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4434 uint32_t startFrames = (mCblk->frameCount - frames);
4435 pInBuffer = new Buffer;
4436 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4437 pInBuffer->frameCount = startFrames;
4438 pInBuffer->i16 = pInBuffer->mBuffer;
4439 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4440 mBufferQueue.add(pInBuffer);
4441 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004442 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004443 }
4444 }
4445 }
4446 }
4447
4448 while (waitTimeLeftMs) {
4449 // First write pending buffers, then new data
4450 if (mBufferQueue.size()) {
4451 pInBuffer = mBufferQueue.itemAt(0);
4452 } else {
4453 pInBuffer = &inBuffer;
4454 }
4455
4456 if (pInBuffer->frameCount == 0) {
4457 break;
4458 }
4459
4460 if (mOutBuffer.frameCount == 0) {
4461 mOutBuffer.frameCount = pInBuffer->frameCount;
4462 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08004463 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01004464 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004465 outputBufferFull = true;
4466 break;
4467 }
4468 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4469 if (waitTimeLeftMs >= waitTimeMs) {
4470 waitTimeLeftMs -= waitTimeMs;
4471 } else {
4472 waitTimeLeftMs = 0;
4473 }
4474 }
4475
4476 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4477 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4478 mCblk->stepUser(outFrames);
4479 pInBuffer->frameCount -= outFrames;
4480 pInBuffer->i16 += outFrames * channelCount;
4481 mOutBuffer.frameCount -= outFrames;
4482 mOutBuffer.i16 += outFrames * channelCount;
4483
4484 if (pInBuffer->frameCount == 0) {
4485 if (mBufferQueue.size()) {
4486 mBufferQueue.removeAt(0);
4487 delete [] pInBuffer->mBuffer;
4488 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01004489 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004490 } else {
4491 break;
4492 }
4493 }
4494 }
4495
4496 // If we could not write all frames, allocate a buffer and queue it for next time.
4497 if (inBuffer.frameCount) {
4498 sp<ThreadBase> thread = mThread.promote();
4499 if (thread != 0 && !thread->standby()) {
4500 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4501 pInBuffer = new Buffer;
4502 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4503 pInBuffer->frameCount = inBuffer.frameCount;
4504 pInBuffer->i16 = pInBuffer->mBuffer;
4505 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4506 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01004507 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004508 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004509 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004510 }
4511 }
4512 }
4513
4514 // Calling write() with a 0 length buffer, means that no more data will be written:
4515 // If no more buffers are pending, fill output track buffer to make sure it is started
4516 // by output mixer.
4517 if (frames == 0 && mBufferQueue.size() == 0) {
4518 if (mCblk->user < mCblk->frameCount) {
4519 frames = mCblk->frameCount - mCblk->user;
4520 pInBuffer = new Buffer;
4521 pInBuffer->mBuffer = new int16_t[frames * channelCount];
4522 pInBuffer->frameCount = frames;
4523 pInBuffer->i16 = pInBuffer->mBuffer;
4524 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4525 mBufferQueue.add(pInBuffer);
4526 } else if (mActive) {
4527 stop();
4528 }
4529 }
4530
4531 return outputBufferFull;
4532}
4533
4534status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4535{
4536 int active;
4537 status_t result;
4538 audio_track_cblk_t* cblk = mCblk;
4539 uint32_t framesReq = buffer->frameCount;
4540
Steve Block3856b092011-10-20 11:56:00 +01004541// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004542 buffer->frameCount = 0;
4543
4544 uint32_t framesAvail = cblk->framesAvailable();
4545
4546
4547 if (framesAvail == 0) {
4548 Mutex::Autolock _l(cblk->lock);
4549 goto start_loop_here;
4550 while (framesAvail == 0) {
4551 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004552 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004553 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004554 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004555 }
4556 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4557 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004558 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004559 }
4560 // read the server count again
4561 start_loop_here:
4562 framesAvail = cblk->framesAvailable_l();
4563 }
4564 }
4565
4566// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004567// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004568// }
4569
4570 if (framesReq > framesAvail) {
4571 framesReq = framesAvail;
4572 }
4573
4574 uint32_t u = cblk->user;
4575 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4576
4577 if (u + framesReq > bufferEnd) {
4578 framesReq = bufferEnd - u;
4579 }
4580
4581 buffer->frameCount = framesReq;
4582 buffer->raw = (void *)cblk->buffer(u);
4583 return NO_ERROR;
4584}
4585
4586
4587void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4588{
4589 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004590
4591 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004592 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004593 delete [] pBuffer->mBuffer;
4594 delete pBuffer;
4595 }
4596 mBufferQueue.clear();
4597}
4598
4599// ----------------------------------------------------------------------------
4600
4601AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4602 : RefBase(),
4603 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08004604 // 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 -07004605 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08004606 mPid(pid),
4607 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004608{
4609 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4610}
4611
4612// Client destructor must be called with AudioFlinger::mLock held
4613AudioFlinger::Client::~Client()
4614{
4615 mAudioFlinger->removeClient_l(mPid);
4616}
4617
Glenn Kasten435dbe62012-01-30 10:15:48 -08004618sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004619{
4620 return mMemoryDealer;
4621}
4622
John Grossman4ff14ba2012-02-08 16:37:41 -08004623// Reserve one of the limited slots for a timed audio track associated
4624// with this client
4625bool AudioFlinger::Client::reserveTimedTrack()
4626{
4627 const int kMaxTimedTracksPerClient = 4;
4628
4629 Mutex::Autolock _l(mTimedTrackLock);
4630
4631 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4632 ALOGW("can not create timed track - pid %d has exceeded the limit",
4633 mPid);
4634 return false;
4635 }
4636
4637 mTimedTrackCount++;
4638 return true;
4639}
4640
4641// Release a slot for a timed audio track
4642void AudioFlinger::Client::releaseTimedTrack()
4643{
4644 Mutex::Autolock _l(mTimedTrackLock);
4645 mTimedTrackCount--;
4646}
4647
Mathias Agopian65ab4712010-07-14 17:59:35 -07004648// ----------------------------------------------------------------------------
4649
4650AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4651 const sp<IAudioFlingerClient>& client,
4652 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004653 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004654{
4655}
4656
4657AudioFlinger::NotificationClient::~NotificationClient()
4658{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004659}
4660
4661void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4662{
4663 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08004664 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004665}
4666
4667// ----------------------------------------------------------------------------
4668
4669AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4670 : BnAudioTrack(),
4671 mTrack(track)
4672{
4673}
4674
4675AudioFlinger::TrackHandle::~TrackHandle() {
4676 // just stop the track on deletion, associated resources
4677 // will be freed from the main thread once all pending buffers have
4678 // been played. Unless it's not in the active track list, in which
4679 // case we free everything now...
4680 mTrack->destroy();
4681}
4682
Glenn Kasten90716c52012-01-26 13:40:12 -08004683sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4684 return mTrack->getCblk();
4685}
4686
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004687status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4688 return mTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004689}
4690
4691void AudioFlinger::TrackHandle::stop() {
4692 mTrack->stop();
4693}
4694
4695void AudioFlinger::TrackHandle::flush() {
4696 mTrack->flush();
4697}
4698
4699void AudioFlinger::TrackHandle::mute(bool e) {
4700 mTrack->mute(e);
4701}
4702
4703void AudioFlinger::TrackHandle::pause() {
4704 mTrack->pause();
4705}
4706
Mathias Agopian65ab4712010-07-14 17:59:35 -07004707status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4708{
4709 return mTrack->attachAuxEffect(EffectId);
4710}
4711
John Grossman4ff14ba2012-02-08 16:37:41 -08004712status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4713 sp<IMemory>* buffer) {
4714 if (!mTrack->isTimedTrack())
4715 return INVALID_OPERATION;
4716
4717 PlaybackThread::TimedTrack* tt =
4718 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4719 return tt->allocateTimedBuffer(size, buffer);
4720}
4721
4722status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4723 int64_t pts) {
4724 if (!mTrack->isTimedTrack())
4725 return INVALID_OPERATION;
4726
4727 PlaybackThread::TimedTrack* tt =
4728 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4729 return tt->queueTimedBuffer(buffer, pts);
4730}
4731
4732status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4733 const LinearTransform& xform, int target) {
4734
4735 if (!mTrack->isTimedTrack())
4736 return INVALID_OPERATION;
4737
4738 PlaybackThread::TimedTrack* tt =
4739 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4740 return tt->setMediaTimeTransform(
4741 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4742}
4743
Mathias Agopian65ab4712010-07-14 17:59:35 -07004744status_t AudioFlinger::TrackHandle::onTransact(
4745 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4746{
4747 return BnAudioTrack::onTransact(code, data, reply, flags);
4748}
4749
4750// ----------------------------------------------------------------------------
4751
4752sp<IAudioRecord> AudioFlinger::openRecord(
4753 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004754 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004755 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004756 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004757 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004758 int frameCount,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004759 // FIXME dead, remove from IAudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -07004760 uint32_t flags,
4761 int *sessionId,
4762 status_t *status)
4763{
4764 sp<RecordThread::RecordTrack> recordTrack;
4765 sp<RecordHandle> recordHandle;
4766 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004767 status_t lStatus;
4768 RecordThread *thread;
4769 size_t inFrameCount;
4770 int lSessionId;
4771
4772 // check calling permissions
4773 if (!recordingAllowed()) {
4774 lStatus = PERMISSION_DENIED;
4775 goto Exit;
4776 }
4777
4778 // add client to list
4779 { // scope for mLock
4780 Mutex::Autolock _l(mLock);
4781 thread = checkRecordThread_l(input);
4782 if (thread == NULL) {
4783 lStatus = BAD_VALUE;
4784 goto Exit;
4785 }
4786
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004787 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004788
4789 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004790 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004791 lSessionId = *sessionId;
4792 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004793 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004794 if (sessionId != NULL) {
4795 *sessionId = lSessionId;
4796 }
4797 }
4798 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004799 recordTrack = thread->createRecordTrack_l(client,
4800 sampleRate,
4801 format,
4802 channelMask,
4803 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004804 lSessionId,
4805 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004806 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004807 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004808 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4809 // destructor is called by the TrackBase destructor with mLock held
4810 client.clear();
4811 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004812 goto Exit;
4813 }
4814
4815 // return to handle to client
4816 recordHandle = new RecordHandle(recordTrack);
4817 lStatus = NO_ERROR;
4818
4819Exit:
4820 if (status) {
4821 *status = lStatus;
4822 }
4823 return recordHandle;
4824}
4825
4826// ----------------------------------------------------------------------------
4827
4828AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4829 : BnAudioRecord(),
4830 mRecordTrack(recordTrack)
4831{
4832}
4833
4834AudioFlinger::RecordHandle::~RecordHandle() {
4835 stop();
4836}
4837
Glenn Kasten90716c52012-01-26 13:40:12 -08004838sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4839 return mRecordTrack->getCblk();
4840}
4841
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004842status_t AudioFlinger::RecordHandle::start(pid_t tid) {
Steve Block3856b092011-10-20 11:56:00 +01004843 ALOGV("RecordHandle::start()");
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004844 return mRecordTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004845}
4846
4847void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004848 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004849 mRecordTrack->stop();
4850}
4851
Mathias Agopian65ab4712010-07-14 17:59:35 -07004852status_t AudioFlinger::RecordHandle::onTransact(
4853 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4854{
4855 return BnAudioRecord::onTransact(code, data, reply, flags);
4856}
4857
4858// ----------------------------------------------------------------------------
4859
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004860AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4861 AudioStreamIn *input,
4862 uint32_t sampleRate,
4863 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004864 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004865 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004866 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004867 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4868 // mRsmpInIndex and mInputBytes set by readInputParameters()
4869 mReqChannelCount(popcount(channels)),
4870 mReqSampleRate(sampleRate)
4871 // mBytesRead is only meaningful while active, and so is cleared in start()
4872 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004873{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004874 snprintf(mName, kNameLength, "AudioIn_%d", id);
4875
Mathias Agopian65ab4712010-07-14 17:59:35 -07004876 readInputParameters();
4877}
4878
4879
4880AudioFlinger::RecordThread::~RecordThread()
4881{
4882 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004883 delete mResampler;
4884 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004885}
4886
4887void AudioFlinger::RecordThread::onFirstRef()
4888{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004889 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004890}
4891
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004892status_t AudioFlinger::RecordThread::readyToRun()
4893{
4894 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004895 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004896 return status;
4897}
4898
Mathias Agopian65ab4712010-07-14 17:59:35 -07004899bool AudioFlinger::RecordThread::threadLoop()
4900{
4901 AudioBufferProvider::Buffer buffer;
4902 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004903 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004904
Eric Laurent44d98482010-09-30 16:12:31 -07004905 nsecs_t lastWarning = 0;
4906
Eric Laurentfeb0db62011-07-22 09:04:31 -07004907 acquireWakeLock();
4908
Mathias Agopian65ab4712010-07-14 17:59:35 -07004909 // start recording
4910 while (!exitPending()) {
4911
4912 processConfigEvents();
4913
4914 { // scope for mLock
4915 Mutex::Autolock _l(mLock);
4916 checkForNewParameters_l();
4917 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4918 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004919 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004920 mStandby = true;
4921 }
4922
4923 if (exitPending()) break;
4924
Eric Laurentfeb0db62011-07-22 09:04:31 -07004925 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004926 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004927 // go to sleep
4928 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004929 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004930 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004931 continue;
4932 }
4933 if (mActiveTrack != 0) {
4934 if (mActiveTrack->mState == TrackBase::PAUSING) {
4935 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004936 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004937 mStandby = true;
4938 }
4939 mActiveTrack.clear();
4940 mStartStopCond.broadcast();
4941 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4942 if (mReqChannelCount != mActiveTrack->channelCount()) {
4943 mActiveTrack.clear();
4944 mStartStopCond.broadcast();
4945 } else if (mBytesRead != 0) {
4946 // record start succeeds only if first read from audio input
4947 // succeeds
4948 if (mBytesRead > 0) {
4949 mActiveTrack->mState = TrackBase::ACTIVE;
4950 } else {
4951 mActiveTrack.clear();
4952 }
4953 mStartStopCond.broadcast();
4954 }
4955 mStandby = false;
4956 }
4957 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004958 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004959 }
4960
4961 if (mActiveTrack != 0) {
4962 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4963 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004964 unlockEffectChains(effectChains);
4965 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004966 continue;
4967 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004968 for (size_t i = 0; i < effectChains.size(); i ++) {
4969 effectChains[i]->process_l();
4970 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004971
Mathias Agopian65ab4712010-07-14 17:59:35 -07004972 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004973 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004974 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004975 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004976 // no resampling
4977 while (framesOut) {
4978 size_t framesIn = mFrameCount - mRsmpInIndex;
4979 if (framesIn) {
4980 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4981 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4982 if (framesIn > framesOut)
4983 framesIn = framesOut;
4984 mRsmpInIndex += framesIn;
4985 framesOut -= framesIn;
4986 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004987 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004988 memcpy(dst, src, framesIn * mFrameSize);
4989 } else {
4990 int16_t *src16 = (int16_t *)src;
4991 int16_t *dst16 = (int16_t *)dst;
4992 if (mChannelCount == 1) {
4993 while (framesIn--) {
4994 *dst16++ = *src16;
4995 *dst16++ = *src16++;
4996 }
4997 } else {
4998 while (framesIn--) {
4999 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
5000 src16 += 2;
5001 }
5002 }
5003 }
5004 }
5005 if (framesOut && mFrameCount == mRsmpInIndex) {
5006 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005007 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005008 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005009 framesOut = 0;
5010 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07005011 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005012 mRsmpInIndex = 0;
5013 }
5014 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005015 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005016 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5017 // Force input into standby so that it tries to
5018 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005019 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005020 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005021 }
5022 mRsmpInIndex = mFrameCount;
5023 framesOut = 0;
5024 buffer.frameCount = 0;
5025 }
5026 }
5027 }
5028 } else {
5029 // resampling
5030
5031 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
5032 // alter output frame count as if we were expecting stereo samples
5033 if (mChannelCount == 1 && mReqChannelCount == 1) {
5034 framesOut >>= 1;
5035 }
5036 mResampler->resample(mRsmpOutBuffer, framesOut, this);
5037 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
5038 // are 32 bit aligned which should be always true.
5039 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005040 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005041 // the resampler always outputs stereo samples: do post stereo to mono conversion
5042 int16_t *src = (int16_t *)mRsmpOutBuffer;
5043 int16_t *dst = buffer.i16;
5044 while (framesOut--) {
5045 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
5046 src += 2;
5047 }
5048 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005049 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005050 }
5051
5052 }
5053 mActiveTrack->releaseBuffer(&buffer);
5054 mActiveTrack->overflow();
5055 }
5056 // client isn't retrieving buffers fast enough
5057 else {
Eric Laurent44d98482010-09-30 16:12:31 -07005058 if (!mActiveTrack->setOverflow()) {
5059 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08005060 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005061 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07005062 lastWarning = now;
5063 }
5064 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005065 // Release the processor for a while before asking for a new buffer.
5066 // This will give the application more chance to read from the buffer and
5067 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005068 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005069 }
5070 }
Eric Laurentec437d82011-07-26 20:54:46 -07005071 // enable changes in effect chain
5072 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005073 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005074 }
5075
5076 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005077 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005078 }
5079 mActiveTrack.clear();
5080
5081 mStartStopCond.broadcast();
5082
Eric Laurentfeb0db62011-07-22 09:04:31 -07005083 releaseWakeLock();
5084
Steve Block3856b092011-10-20 11:56:00 +01005085 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005086 return false;
5087}
5088
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005089
5090sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5091 const sp<AudioFlinger::Client>& client,
5092 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005093 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005094 int channelMask,
5095 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005096 int sessionId,
5097 status_t *status)
5098{
5099 sp<RecordTrack> track;
5100 status_t lStatus;
5101
5102 lStatus = initCheck();
5103 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005104 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005105 goto Exit;
5106 }
5107
5108 { // scope for mLock
5109 Mutex::Autolock _l(mLock);
5110
5111 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005112 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005113
Glenn Kasten7378ca52012-01-20 13:44:40 -08005114 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005115 lStatus = NO_MEMORY;
5116 goto Exit;
5117 }
5118
5119 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005120 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5121 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005122 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005123 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5124 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005125 }
5126 lStatus = NO_ERROR;
5127
5128Exit:
5129 if (status) {
5130 *status = lStatus;
5131 }
5132 return track;
5133}
5134
Glenn Kasten6dbc1352012-02-02 10:56:47 -08005135status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005136{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08005137 ALOGV("RecordThread::start tid=%d", tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005138 sp <ThreadBase> strongMe = this;
5139 status_t status = NO_ERROR;
5140 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005141 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005142 if (mActiveTrack != 0) {
5143 if (recordTrack != mActiveTrack.get()) {
5144 status = -EBUSY;
5145 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5146 mActiveTrack->mState = TrackBase::ACTIVE;
5147 }
5148 return status;
5149 }
5150
5151 recordTrack->mState = TrackBase::IDLE;
5152 mActiveTrack = recordTrack;
5153 mLock.unlock();
5154 status_t status = AudioSystem::startInput(mId);
5155 mLock.lock();
5156 if (status != NO_ERROR) {
5157 mActiveTrack.clear();
5158 return status;
5159 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005160 mRsmpInIndex = mFrameCount;
5161 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005162 if (mResampler != NULL) {
5163 mResampler->reset();
5164 }
5165 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005166 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005167 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005168 mWaitWorkCV.signal();
5169 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005170 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005171 mActiveTrack.clear();
5172 status = INVALID_OPERATION;
5173 goto startError;
5174 }
5175 mStartStopCond.wait(mLock);
5176 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005177 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005178 status = BAD_VALUE;
5179 goto startError;
5180 }
Steve Block3856b092011-10-20 11:56:00 +01005181 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005182 return status;
5183 }
5184startError:
5185 AudioSystem::stopInput(mId);
5186 return status;
5187}
5188
5189void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005190 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005191 sp <ThreadBase> strongMe = this;
5192 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005193 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005194 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5195 mActiveTrack->mState = TrackBase::PAUSING;
5196 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005197 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005198 return;
5199 }
5200 mStartStopCond.wait(mLock);
5201 // if we have been restarted, recordTrack == mActiveTrack.get() here
5202 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5203 mLock.unlock();
5204 AudioSystem::stopInput(mId);
5205 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005206 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005207 }
5208 }
5209 }
5210}
5211
5212status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5213{
5214 const size_t SIZE = 256;
5215 char buffer[SIZE];
5216 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005217
5218 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5219 result.append(buffer);
5220
5221 if (mActiveTrack != 0) {
5222 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005223 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005224 mActiveTrack->dump(buffer, SIZE);
5225 result.append(buffer);
5226
5227 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5228 result.append(buffer);
5229 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5230 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005231 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005232 result.append(buffer);
5233 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5234 result.append(buffer);
5235 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5236 result.append(buffer);
5237
5238
5239 } else {
5240 result.append("No record client\n");
5241 }
5242 write(fd, result.string(), result.size());
5243
5244 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005245 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005246
5247 return NO_ERROR;
5248}
5249
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005250// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005251status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005252{
5253 size_t framesReq = buffer->frameCount;
5254 size_t framesReady = mFrameCount - mRsmpInIndex;
5255 int channelCount;
5256
5257 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005258 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005259 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005260 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005261 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5262 // Force input into standby so that it tries to
5263 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005264 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005265 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005266 }
Glenn Kastene0feee32011-12-13 11:53:26 -08005267 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005268 buffer->frameCount = 0;
5269 return NOT_ENOUGH_DATA;
5270 }
5271 mRsmpInIndex = 0;
5272 framesReady = mFrameCount;
5273 }
5274
5275 if (framesReq > framesReady) {
5276 framesReq = framesReady;
5277 }
5278
5279 if (mChannelCount == 1 && mReqChannelCount == 2) {
5280 channelCount = 1;
5281 } else {
5282 channelCount = 2;
5283 }
5284 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5285 buffer->frameCount = framesReq;
5286 return NO_ERROR;
5287}
5288
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005289// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07005290void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5291{
5292 mRsmpInIndex += buffer->frameCount;
5293 buffer->frameCount = 0;
5294}
5295
5296bool AudioFlinger::RecordThread::checkForNewParameters_l()
5297{
5298 bool reconfig = false;
5299
5300 while (!mNewParameters.isEmpty()) {
5301 status_t status = NO_ERROR;
5302 String8 keyValuePair = mNewParameters[0];
5303 AudioParameter param = AudioParameter(keyValuePair);
5304 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08005305 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005306 int reqSamplingRate = mReqSampleRate;
5307 int reqChannelCount = mReqChannelCount;
5308
5309 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5310 reqSamplingRate = value;
5311 reconfig = true;
5312 }
5313 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08005314 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005315 reconfig = true;
5316 }
5317 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005318 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005319 reconfig = true;
5320 }
5321 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5322 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08005323 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005324 // if frame count is changed after track creation
5325 if (mActiveTrack != 0) {
5326 status = INVALID_OPERATION;
5327 } else {
5328 reconfig = true;
5329 }
5330 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005331 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5332 // forward device change to effects that have requested to be
5333 // aware of attached audio device.
5334 for (size_t i = 0; i < mEffectChains.size(); i++) {
5335 mEffectChains[i]->setDevice_l(value);
5336 }
5337 // store input device and output device but do not forward output device to audio HAL.
5338 // Note that status is ignored by the caller for output device
5339 // (see AudioFlinger::setParameters()
5340 if (value & AUDIO_DEVICE_OUT_ALL) {
5341 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5342 status = BAD_VALUE;
5343 } else {
5344 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07005345 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5346 if (mTrack != NULL) {
5347 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005348 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005349 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5350 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5351 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005352 }
5353 mDevice |= (uint32_t)value;
5354 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005355 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005356 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005357 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005358 mInput->stream->common.standby(&mInput->stream->common);
5359 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005360 }
5361 if (reconfig) {
5362 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005363 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005364 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005365 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
5366 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005367 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005368 status = NO_ERROR;
5369 }
5370 if (status == NO_ERROR) {
5371 readInputParameters();
5372 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5373 }
5374 }
5375 }
5376
5377 mNewParameters.removeAt(0);
5378
5379 mParamStatus = status;
5380 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07005381 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5382 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08005383 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005384 }
5385 return reconfig;
5386}
5387
5388String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5389{
Dima Zavinfce7a472011-04-19 22:30:36 -07005390 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005391 String8 out_s8 = String8();
5392
5393 Mutex::Autolock _l(mLock);
5394 if (initCheck() != NO_ERROR) {
5395 return out_s8;
5396 }
Dima Zavinfce7a472011-04-19 22:30:36 -07005397
Dima Zavin799a70e2011-04-18 16:57:27 -07005398 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07005399 out_s8 = String8(s);
5400 free(s);
5401 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005402}
5403
5404void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5405 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08005406 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005407
5408 switch (event) {
5409 case AudioSystem::INPUT_OPENED:
5410 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005411 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005412 desc.samplingRate = mSampleRate;
5413 desc.format = mFormat;
5414 desc.frameCount = mFrameCount;
5415 desc.latency = 0;
5416 param2 = &desc;
5417 break;
5418
5419 case AudioSystem::INPUT_CLOSED:
5420 default:
5421 break;
5422 }
5423 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5424}
5425
5426void AudioFlinger::RecordThread::readInputParameters()
5427{
Glenn Kastene9dd0172012-01-27 18:08:45 -08005428 delete mRsmpInBuffer;
5429 // mRsmpInBuffer is always assigned a new[] below
5430 delete mRsmpOutBuffer;
5431 mRsmpOutBuffer = NULL;
5432 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08005433 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005434
Dima Zavin799a70e2011-04-18 16:57:27 -07005435 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005436 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5437 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07005438 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08005439 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07005440 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005441 mFrameCount = mInputBytes / mFrameSize;
5442 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5443
5444 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
5445 {
5446 int channelCount;
5447 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5448 // stereo to mono post process as the resampler always outputs stereo.
5449 if (mChannelCount == 1 && mReqChannelCount == 2) {
5450 channelCount = 1;
5451 } else {
5452 channelCount = 2;
5453 }
5454 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5455 mResampler->setSampleRate(mSampleRate);
5456 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5457 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5458
5459 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5460 if (mChannelCount == 1 && mReqChannelCount == 1) {
5461 mFrameCount >>= 1;
5462 }
5463
5464 }
5465 mRsmpInIndex = mFrameCount;
5466}
5467
5468unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5469{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005470 Mutex::Autolock _l(mLock);
5471 if (initCheck() != NO_ERROR) {
5472 return 0;
5473 }
5474
Dima Zavin799a70e2011-04-18 16:57:27 -07005475 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005476}
5477
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005478uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5479{
5480 Mutex::Autolock _l(mLock);
5481 uint32_t result = 0;
5482 if (getEffectChain_l(sessionId) != 0) {
5483 result = EFFECT_SESSION;
5484 }
5485
5486 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5487 result |= TRACK_SESSION;
5488 }
5489
5490 return result;
5491}
5492
Eric Laurent59bd0da2011-08-01 09:52:20 -07005493AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5494{
5495 Mutex::Autolock _l(mLock);
5496 return mTrack;
5497}
5498
Glenn Kastenaed850d2012-01-26 09:46:34 -08005499AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005500{
5501 Mutex::Autolock _l(mLock);
5502 return mInput;
5503}
5504
5505AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5506{
5507 Mutex::Autolock _l(mLock);
5508 AudioStreamIn *input = mInput;
5509 mInput = NULL;
5510 return input;
5511}
5512
5513// this method must always be called either with ThreadBase mLock held or inside the thread loop
5514audio_stream_t* AudioFlinger::RecordThread::stream()
5515{
5516 if (mInput == NULL) {
5517 return NULL;
5518 }
5519 return &mInput->stream->common;
5520}
5521
5522
Mathias Agopian65ab4712010-07-14 17:59:35 -07005523// ----------------------------------------------------------------------------
5524
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005525audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005526 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005527 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005528 uint32_t *pChannels,
5529 uint32_t *pLatencyMs,
5530 uint32_t flags)
5531{
5532 status_t status;
5533 PlaybackThread *thread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005534 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005535 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005536 uint32_t channels = pChannels ? *pChannels : 0;
5537 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07005538 audio_stream_out_t *outStream;
5539 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005540
Steve Block3856b092011-10-20 11:56:00 +01005541 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07005542 pDevices ? *pDevices : 0,
5543 samplingRate,
5544 format,
5545 channels,
5546 flags);
5547
5548 if (pDevices == NULL || *pDevices == 0) {
5549 return 0;
5550 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005551
Mathias Agopian65ab4712010-07-14 17:59:35 -07005552 Mutex::Autolock _l(mLock);
5553
Dima Zavin799a70e2011-04-18 16:57:27 -07005554 outHwDev = findSuitableHwDev_l(*pDevices);
5555 if (outHwDev == NULL)
5556 return 0;
5557
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005558 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Glenn Kasten58f30212012-01-12 12:27:51 -08005559 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005560 &channels, &samplingRate, &outStream);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005561 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01005562 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005563 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005564 samplingRate,
5565 format,
5566 channels,
5567 status);
5568
Dima Zavin799a70e2011-04-18 16:57:27 -07005569 if (outStream != NULL) {
5570 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005571 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07005572
Dima Zavinfce7a472011-04-19 22:30:36 -07005573 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5574 (format != AUDIO_FORMAT_PCM_16_BIT) ||
5575 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005576 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005577 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005578 } else {
5579 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005580 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005581 }
5582 mPlaybackThreads.add(id, thread);
5583
Glenn Kastena0d68332012-01-27 16:47:15 -08005584 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5585 if (pFormat != NULL) *pFormat = format;
5586 if (pChannels != NULL) *pChannels = channels;
5587 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005588
5589 // notify client processes of the new output creation
5590 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5591 return id;
5592 }
5593
5594 return 0;
5595}
5596
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005597audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
5598 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005599{
5600 Mutex::Autolock _l(mLock);
5601 MixerThread *thread1 = checkMixerThread_l(output1);
5602 MixerThread *thread2 = checkMixerThread_l(output2);
5603
5604 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005605 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005606 return 0;
5607 }
5608
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005609 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005610 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5611 thread->addOutputTrack(thread2);
5612 mPlaybackThreads.add(id, thread);
5613 // notify client processes of the new output creation
5614 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5615 return id;
5616}
5617
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005618status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005619{
5620 // keep strong reference on the playback thread so that
5621 // it is not destroyed while exit() is executed
5622 sp <PlaybackThread> thread;
5623 {
5624 Mutex::Autolock _l(mLock);
5625 thread = checkPlaybackThread_l(output);
5626 if (thread == NULL) {
5627 return BAD_VALUE;
5628 }
5629
Steve Block3856b092011-10-20 11:56:00 +01005630 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005631
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005632 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005633 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005634 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005635 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5636 dupThread->removeOutputTrack((MixerThread *)thread.get());
5637 }
5638 }
5639 }
Glenn Kastena1117922012-01-26 10:53:32 -08005640 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005641 mPlaybackThreads.removeItem(output);
5642 }
5643 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005644 // The thread entity (active unit of execution) is no longer running here,
5645 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005646
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005647 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005648 AudioStreamOut *out = thread->clearOutput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005649 assert(out != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005650 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005651 out->hwDev->close_output_stream(out->hwDev, out->stream);
5652 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005653 }
5654 return NO_ERROR;
5655}
5656
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005657status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005658{
5659 Mutex::Autolock _l(mLock);
5660 PlaybackThread *thread = checkPlaybackThread_l(output);
5661
5662 if (thread == NULL) {
5663 return BAD_VALUE;
5664 }
5665
Steve Block3856b092011-10-20 11:56:00 +01005666 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005667 thread->suspend();
5668
5669 return NO_ERROR;
5670}
5671
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005672status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005673{
5674 Mutex::Autolock _l(mLock);
5675 PlaybackThread *thread = checkPlaybackThread_l(output);
5676
5677 if (thread == NULL) {
5678 return BAD_VALUE;
5679 }
5680
Steve Block3856b092011-10-20 11:56:00 +01005681 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005682
5683 thread->restore();
5684
5685 return NO_ERROR;
5686}
5687
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005688audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005689 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005690 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005691 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005692 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005693{
5694 status_t status;
5695 RecordThread *thread = NULL;
5696 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005697 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005698 uint32_t channels = pChannels ? *pChannels : 0;
5699 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005700 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005701 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005702 audio_stream_in_t *inStream;
5703 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005704
5705 if (pDevices == NULL || *pDevices == 0) {
5706 return 0;
5707 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005708
Mathias Agopian65ab4712010-07-14 17:59:35 -07005709 Mutex::Autolock _l(mLock);
5710
Dima Zavin799a70e2011-04-18 16:57:27 -07005711 inHwDev = findSuitableHwDev_l(*pDevices);
5712 if (inHwDev == NULL)
5713 return 0;
5714
Glenn Kasten58f30212012-01-12 12:27:51 -08005715 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005716 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005717 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005718 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005719 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005720 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005721 samplingRate,
5722 format,
5723 channels,
5724 acoustics,
5725 status);
5726
5727 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5728 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5729 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005730 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005731 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005732 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005733 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005734 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005735 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005736 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005737 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005738 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005739 }
5740
Dima Zavin799a70e2011-04-18 16:57:27 -07005741 if (inStream != NULL) {
5742 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5743
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005744 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005745 // Start record thread
5746 // RecorThread require both input and output device indication to forward to audio
5747 // pre processing modules
5748 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5749 thread = new RecordThread(this,
5750 input,
5751 reqSamplingRate,
5752 reqChannels,
5753 id,
5754 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005755 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005756 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005757 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5758 if (pFormat != NULL) *pFormat = format;
5759 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005760
Dima Zavin799a70e2011-04-18 16:57:27 -07005761 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005762
5763 // notify client processes of the new input creation
5764 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5765 return id;
5766 }
5767
5768 return 0;
5769}
5770
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005771status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005772{
5773 // keep strong reference on the record thread so that
5774 // it is not destroyed while exit() is executed
5775 sp <RecordThread> thread;
5776 {
5777 Mutex::Autolock _l(mLock);
5778 thread = checkRecordThread_l(input);
5779 if (thread == NULL) {
5780 return BAD_VALUE;
5781 }
5782
Steve Block3856b092011-10-20 11:56:00 +01005783 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08005784 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005785 mRecordThreads.removeItem(input);
5786 }
5787 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005788 // The thread entity (active unit of execution) is no longer running here,
5789 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005790
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005791 AudioStreamIn *in = thread->clearInput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005792 assert(in != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005793 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005794 in->hwDev->close_input_stream(in->hwDev, in->stream);
5795 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005796
5797 return NO_ERROR;
5798}
5799
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005800status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005801{
5802 Mutex::Autolock _l(mLock);
5803 MixerThread *dstThread = checkMixerThread_l(output);
5804 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005805 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005806 return BAD_VALUE;
5807 }
5808
Steve Block3856b092011-10-20 11:56:00 +01005809 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005810 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5811
Eric Laurent9f6530f2011-08-30 10:18:54 -07005812 dstThread->setStreamValid(stream, true);
5813
Mathias Agopian65ab4712010-07-14 17:59:35 -07005814 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5815 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08005816 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005817 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005818 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005819 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005820 }
Eric Laurentde070132010-07-13 04:45:46 -07005821 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005822
5823 return NO_ERROR;
5824}
5825
5826
5827int AudioFlinger::newAudioSessionId()
5828{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005829 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005830}
5831
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005832void AudioFlinger::acquireAudioSessionId(int audioSession)
5833{
5834 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005835 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005836 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005837 size_t num = mAudioSessionRefs.size();
5838 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005839 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5840 if (ref->sessionid == audioSession && ref->pid == caller) {
5841 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005842 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005843 return;
5844 }
5845 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005846 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5847 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005848}
5849
5850void AudioFlinger::releaseAudioSessionId(int audioSession)
5851{
5852 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005853 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005854 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005855 size_t num = mAudioSessionRefs.size();
5856 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005857 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5858 if (ref->sessionid == audioSession && ref->pid == caller) {
5859 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005860 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005861 if (ref->cnt == 0) {
5862 mAudioSessionRefs.removeAt(i);
5863 delete ref;
5864 purgeStaleEffects_l();
5865 }
5866 return;
5867 }
5868 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005869 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005870}
5871
5872void AudioFlinger::purgeStaleEffects_l() {
5873
Steve Block3856b092011-10-20 11:56:00 +01005874 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005875
5876 Vector< sp<EffectChain> > chains;
5877
5878 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5879 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5880 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5881 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005882 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5883 chains.push(ec);
5884 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005885 }
5886 }
5887 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5888 sp<RecordThread> t = mRecordThreads.valueAt(i);
5889 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5890 sp<EffectChain> ec = t->mEffectChains[j];
5891 chains.push(ec);
5892 }
5893 }
5894
5895 for (size_t i = 0; i < chains.size(); i++) {
5896 sp<EffectChain> ec = chains[i];
5897 int sessionid = ec->sessionId();
5898 sp<ThreadBase> t = ec->mThread.promote();
5899 if (t == 0) {
5900 continue;
5901 }
5902 size_t numsessionrefs = mAudioSessionRefs.size();
5903 bool found = false;
5904 for (size_t k = 0; k < numsessionrefs; k++) {
5905 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5906 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005907 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005908 sessionid, ref->pid, ref->cnt);
5909 found = true;
5910 break;
5911 }
5912 }
5913 if (!found) {
5914 // remove all effects from the chain
5915 while (ec->mEffects.size()) {
5916 sp<EffectModule> effect = ec->mEffects[0];
5917 effect->unPin();
5918 Mutex::Autolock _l (t->mLock);
5919 t->removeEffect_l(effect);
5920 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5921 sp<EffectHandle> handle = effect->mHandles[j].promote();
5922 if (handle != 0) {
5923 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005924 if (handle->mHasControl && handle->mEnabled) {
5925 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5926 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005927 }
5928 }
5929 AudioSystem::unregisterEffect(effect->id());
5930 }
5931 }
5932 }
5933 return;
5934}
5935
Mathias Agopian65ab4712010-07-14 17:59:35 -07005936// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005937AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005938{
Glenn Kastena1117922012-01-26 10:53:32 -08005939 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005940}
5941
5942// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005943AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005944{
5945 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08005946 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005947}
5948
5949// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005950AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005951{
Glenn Kastena1117922012-01-26 10:53:32 -08005952 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005953}
5954
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005955uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005956{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005957 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005958}
5959
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08005960AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005961{
5962 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5963 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005964 AudioStreamOut *output = thread->getOutput();
5965 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005966 return thread;
5967 }
5968 }
5969 return NULL;
5970}
5971
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08005972uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005973{
5974 PlaybackThread *thread = primaryPlaybackThread_l();
5975
5976 if (thread == NULL) {
5977 return 0;
5978 }
5979
5980 return thread->device();
5981}
5982
5983
Mathias Agopian65ab4712010-07-14 17:59:35 -07005984// ----------------------------------------------------------------------------
5985// Effect management
5986// ----------------------------------------------------------------------------
5987
5988
Glenn Kastenf587ba52012-01-26 16:25:10 -08005989status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005990{
5991 Mutex::Autolock _l(mLock);
5992 return EffectQueryNumberEffects(numEffects);
5993}
5994
Glenn Kastenf587ba52012-01-26 16:25:10 -08005995status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005996{
5997 Mutex::Autolock _l(mLock);
5998 return EffectQueryEffect(index, descriptor);
5999}
6000
Glenn Kasten5e92a782012-01-30 07:40:52 -08006001status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08006002 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006003{
6004 Mutex::Autolock _l(mLock);
6005 return EffectGetDescriptor(pUuid, descriptor);
6006}
6007
6008
Mathias Agopian65ab4712010-07-14 17:59:35 -07006009sp<IEffect> AudioFlinger::createEffect(pid_t pid,
6010 effect_descriptor_t *pDesc,
6011 const sp<IEffectClient>& effectClient,
6012 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006013 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006014 int sessionId,
6015 status_t *status,
6016 int *id,
6017 int *enabled)
6018{
6019 status_t lStatus = NO_ERROR;
6020 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006021 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006022
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006023 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006024 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006025
6026 if (pDesc == NULL) {
6027 lStatus = BAD_VALUE;
6028 goto Exit;
6029 }
6030
Eric Laurent84e9a102010-09-23 16:10:16 -07006031 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006032 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006033 lStatus = PERMISSION_DENIED;
6034 goto Exit;
6035 }
6036
Dima Zavinfce7a472011-04-19 22:30:36 -07006037 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07006038 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08006039 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006040 lStatus = PERMISSION_DENIED;
6041 goto Exit;
6042 }
6043
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006044 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006045 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006046 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07006047 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07006048 lStatus = BAD_VALUE;
6049 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07006050 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006051 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006052 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07006053 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006054 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07006055 }
6056 }
6057
Mathias Agopian65ab4712010-07-14 17:59:35 -07006058 {
6059 Mutex::Autolock _l(mLock);
6060
Mathias Agopian65ab4712010-07-14 17:59:35 -07006061
6062 if (!EffectIsNullUuid(&pDesc->uuid)) {
6063 // if uuid is specified, request effect descriptor
6064 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
6065 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006066 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006067 goto Exit;
6068 }
6069 } else {
6070 // if uuid is not specified, look for an available implementation
6071 // of the required type in effect factory
6072 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006073 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006074 lStatus = BAD_VALUE;
6075 goto Exit;
6076 }
6077 uint32_t numEffects = 0;
6078 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006079 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07006080 bool found = false;
6081
6082 lStatus = EffectQueryNumberEffects(&numEffects);
6083 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006084 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006085 goto Exit;
6086 }
6087 for (uint32_t i = 0; i < numEffects; i++) {
6088 lStatus = EffectQueryEffect(i, &desc);
6089 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006090 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006091 continue;
6092 }
6093 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
6094 // If matching type found save effect descriptor. If the session is
6095 // 0 and the effect is not auxiliary, continue enumeration in case
6096 // an auxiliary version of this effect type is available
6097 found = true;
6098 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07006099 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006100 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6101 break;
6102 }
6103 }
6104 }
6105 if (!found) {
6106 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00006107 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006108 goto Exit;
6109 }
6110 // For same effect type, chose auxiliary version over insert version if
6111 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07006112 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006113 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
6114 memcpy(&desc, &d, sizeof(effect_descriptor_t));
6115 }
6116 }
6117
6118 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07006119 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006120 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6121 lStatus = INVALID_OPERATION;
6122 goto Exit;
6123 }
6124
Eric Laurent59255e42011-07-27 19:49:51 -07006125 // check recording permission for visualizer
6126 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
6127 !recordingAllowed()) {
6128 lStatus = PERMISSION_DENIED;
6129 goto Exit;
6130 }
6131
Mathias Agopian65ab4712010-07-14 17:59:35 -07006132 // return effect descriptor
6133 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
6134
6135 // If output is not specified try to find a matching audio session ID in one of the
6136 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07006137 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
6138 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006139 // Note: io is never 0 when creating an effect on an input
6140 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006141 // look for the thread where the specified audio session is present
6142 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6143 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006144 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07006145 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07006146 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006147 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006148 if (io == 0) {
6149 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6150 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6151 io = mRecordThreads.keyAt(i);
6152 break;
6153 }
6154 }
6155 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006156 // If no output thread contains the requested session ID, default to
6157 // first output. The effect chain will be moved to the correct output
6158 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006159 if (io == 0 && mPlaybackThreads.size()) {
6160 io = mPlaybackThreads.keyAt(0);
6161 }
Steve Block3856b092011-10-20 11:56:00 +01006162 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006163 }
6164 ThreadBase *thread = checkRecordThread_l(io);
6165 if (thread == NULL) {
6166 thread = checkPlaybackThread_l(io);
6167 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00006168 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006169 lStatus = BAD_VALUE;
6170 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07006171 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006172 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006173
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006174 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006175
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006176 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07006177 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6178 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006179 if (handle != 0 && id != NULL) {
6180 *id = handle->id();
6181 }
6182 }
6183
6184Exit:
6185 if(status) {
6186 *status = lStatus;
6187 }
6188 return handle;
6189}
6190
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006191status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
6192 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07006193{
Steve Block3856b092011-10-20 11:56:00 +01006194 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07006195 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006196 Mutex::Autolock _l(mLock);
6197 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006198 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006199 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006200 }
Eric Laurentde070132010-07-13 04:45:46 -07006201 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6202 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006203 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006204 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006205 }
Eric Laurentde070132010-07-13 04:45:46 -07006206 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6207 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006208 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006209 return BAD_VALUE;
6210 }
6211
6212 Mutex::Autolock _dl(dstThread->mLock);
6213 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07006214 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07006215
Mathias Agopian65ab4712010-07-14 17:59:35 -07006216 return NO_ERROR;
6217}
6218
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006219// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07006220status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07006221 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07006222 AudioFlinger::PlaybackThread *dstThread,
6223 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07006224{
Steve Block3856b092011-10-20 11:56:00 +01006225 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006226 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07006227
Eric Laurent59255e42011-07-27 19:49:51 -07006228 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006229 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006230 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006231 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07006232 return INVALID_OPERATION;
6233 }
6234
Eric Laurent39e94f82010-07-28 01:32:47 -07006235 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07006236 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07006237 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07006238 // removed.
6239 srcThread->removeEffectChain_l(chain);
6240
6241 // transfer all effects one by one so that new effect chain is created on new thread with
6242 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006243 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07006244 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006245 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07006246 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6247 while (effect != 0) {
6248 srcThread->removeEffect_l(effect);
6249 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07006250 // removeEffect_l() has stopped the effect if it was active so it must be restarted
6251 if (effect->state() == EffectModule::ACTIVE ||
6252 effect->state() == EffectModule::STOPPING) {
6253 effect->start();
6254 }
Eric Laurent39e94f82010-07-28 01:32:47 -07006255 // if the move request is not received from audio policy manager, the effect must be
6256 // re-registered with the new strategy and output
6257 if (dstChain == 0) {
6258 dstChain = effect->chain().promote();
6259 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006260 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07006261 srcThread->addEffect_l(effect);
6262 return NO_INIT;
6263 }
6264 strategy = dstChain->strategy();
6265 }
6266 if (reRegister) {
6267 AudioSystem::unregisterEffect(effect->id());
6268 AudioSystem::registerEffect(&effect->desc(),
6269 dstOutput,
6270 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07006271 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07006272 effect->id());
6273 }
Eric Laurentde070132010-07-13 04:45:46 -07006274 effect = chain->getEffectFromId_l(0);
6275 }
6276
6277 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006278}
6279
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006280
Mathias Agopian65ab4712010-07-14 17:59:35 -07006281// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006282sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07006283 const sp<AudioFlinger::Client>& client,
6284 const sp<IEffectClient>& effectClient,
6285 int32_t priority,
6286 int sessionId,
6287 effect_descriptor_t *desc,
6288 int *enabled,
6289 status_t *status
6290 )
6291{
6292 sp<EffectModule> effect;
6293 sp<EffectHandle> handle;
6294 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006295 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07006296 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006297 bool effectCreated = false;
6298 bool effectRegistered = false;
6299
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006300 lStatus = initCheck();
6301 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006302 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006303 goto Exit;
6304 }
6305
6306 // Do not allow effects with session ID 0 on direct output or duplicating threads
6307 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07006308 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006309 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07006310 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006311 lStatus = BAD_VALUE;
6312 goto Exit;
6313 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006314 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08006315 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006316 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006317 desc->name, desc->flags, mType);
6318 lStatus = BAD_VALUE;
6319 goto Exit;
6320 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006321
Steve Block3856b092011-10-20 11:56:00 +01006322 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006323
6324 { // scope for mLock
6325 Mutex::Autolock _l(mLock);
6326
6327 // check for existing effect chain with the requested audio session
6328 chain = getEffectChain_l(sessionId);
6329 if (chain == 0) {
6330 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006331 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006332 chain = new EffectChain(this, sessionId);
6333 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07006334 chain->setStrategy(getStrategyForSession_l(sessionId));
6335 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006336 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07006337 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006338 }
6339
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08006340 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006341
6342 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006343 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006344 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07006345 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006346 if (lStatus != NO_ERROR) {
6347 goto Exit;
6348 }
6349 effectRegistered = true;
6350 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07006351 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006352 lStatus = effect->status();
6353 if (lStatus != NO_ERROR) {
6354 goto Exit;
6355 }
Eric Laurentcab11242010-07-15 12:50:15 -07006356 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006357 if (lStatus != NO_ERROR) {
6358 goto Exit;
6359 }
6360 effectCreated = true;
6361
6362 effect->setDevice(mDevice);
6363 effect->setMode(mAudioFlinger->getMode());
6364 }
6365 // create effect handle and connect it to effect module
6366 handle = new EffectHandle(effect, client, effectClient, priority);
6367 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08006368 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006369 *enabled = (int)effect->isEnabled();
6370 }
6371 }
6372
6373Exit:
6374 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07006375 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006376 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07006377 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006378 }
6379 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07006380 AudioSystem::unregisterEffect(effect->id());
6381 }
6382 if (chainCreated) {
6383 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006384 }
6385 handle.clear();
6386 }
6387
6388 if(status) {
6389 *status = lStatus;
6390 }
6391 return handle;
6392}
6393
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006394sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6395{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006396 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08006397 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006398}
6399
Eric Laurentde070132010-07-13 04:45:46 -07006400// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6401// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006402status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07006403{
6404 // check for existing effect chain with the requested audio session
6405 int sessionId = effect->sessionId();
6406 sp<EffectChain> chain = getEffectChain_l(sessionId);
6407 bool chainCreated = false;
6408
6409 if (chain == 0) {
6410 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006411 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006412 chain = new EffectChain(this, sessionId);
6413 addEffectChain_l(chain);
6414 chain->setStrategy(getStrategyForSession_l(sessionId));
6415 chainCreated = true;
6416 }
Steve Block3856b092011-10-20 11:56:00 +01006417 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006418
6419 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006420 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07006421 this, effect->desc().name, chain.get());
6422 return BAD_VALUE;
6423 }
6424
6425 status_t status = chain->addEffect_l(effect);
6426 if (status != NO_ERROR) {
6427 if (chainCreated) {
6428 removeEffectChain_l(chain);
6429 }
6430 return status;
6431 }
6432
6433 effect->setDevice(mDevice);
6434 effect->setMode(mAudioFlinger->getMode());
6435 return NO_ERROR;
6436}
6437
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006438void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07006439
Steve Block3856b092011-10-20 11:56:00 +01006440 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006441 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07006442 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6443 detachAuxEffect_l(effect->id());
6444 }
6445
6446 sp<EffectChain> chain = effect->chain().promote();
6447 if (chain != 0) {
6448 // remove effect chain if removing last effect
6449 if (chain->removeEffect_l(effect) == 0) {
6450 removeEffectChain_l(chain);
6451 }
6452 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00006453 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006454 }
6455}
6456
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006457void AudioFlinger::ThreadBase::lockEffectChains_l(
6458 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
6459{
6460 effectChains = mEffectChains;
6461 for (size_t i = 0; i < mEffectChains.size(); i++) {
6462 mEffectChains[i]->lock();
6463 }
6464}
6465
6466void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006467 const Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006468{
6469 for (size_t i = 0; i < effectChains.size(); i++) {
6470 effectChains[i]->unlock();
6471 }
6472}
6473
6474sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6475{
6476 Mutex::Autolock _l(mLock);
6477 return getEffectChain_l(sessionId);
6478}
6479
6480sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6481{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006482 size_t size = mEffectChains.size();
6483 for (size_t i = 0; i < size; i++) {
6484 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08006485 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006486 }
6487 }
Glenn Kasten090f0192012-01-30 13:00:02 -08006488 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006489}
6490
Glenn Kastenf78aee72012-01-04 11:00:47 -08006491void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006492{
6493 Mutex::Autolock _l(mLock);
6494 size_t size = mEffectChains.size();
6495 for (size_t i = 0; i < size; i++) {
6496 mEffectChains[i]->setMode_l(mode);
6497 }
6498}
6499
6500void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006501 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08006502 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07006503
Mathias Agopian65ab4712010-07-14 17:59:35 -07006504 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006505 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006506 // delete the effect module if removing last handle on it
6507 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006508 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006509 removeEffect_l(effect);
6510 AudioSystem::unregisterEffect(effect->id());
6511 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006512 }
6513}
6514
6515status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6516{
6517 int session = chain->sessionId();
6518 int16_t *buffer = mMixBuffer;
6519 bool ownsBuffer = false;
6520
Steve Block3856b092011-10-20 11:56:00 +01006521 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006522 if (session > 0) {
6523 // Only one effect chain can be present in direct output thread and it uses
6524 // the mix buffer as input
6525 if (mType != DIRECT) {
6526 size_t numSamples = mFrameCount * mChannelCount;
6527 buffer = new int16_t[numSamples];
6528 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01006529 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006530 ownsBuffer = true;
6531 }
6532
6533 // Attach all tracks with same session ID to this chain.
6534 for (size_t i = 0; i < mTracks.size(); ++i) {
6535 sp<Track> track = mTracks[i];
6536 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006537 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006538 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006539 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006540 }
6541 }
6542
6543 // indicate all active tracks in the chain
6544 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6545 sp<Track> track = mActiveTracks[i].promote();
6546 if (track == 0) continue;
6547 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006548 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07006549 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006550 }
6551 }
6552 }
6553
6554 chain->setInBuffer(buffer, ownsBuffer);
6555 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006556 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006557 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006558 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6559 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006560 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006561 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6562 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006563 // Effect chain for other sessions are inserted at beginning of effect
6564 // chains list to be processed before output mix effects. Relative order between other
6565 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006566 size_t size = mEffectChains.size();
6567 size_t i = 0;
6568 for (i = 0; i < size; i++) {
6569 if (mEffectChains[i]->sessionId() < session) break;
6570 }
6571 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006572 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006573
6574 return NO_ERROR;
6575}
6576
6577size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6578{
6579 int session = chain->sessionId();
6580
Steve Block3856b092011-10-20 11:56:00 +01006581 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006582
6583 for (size_t i = 0; i < mEffectChains.size(); i++) {
6584 if (chain == mEffectChains[i]) {
6585 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006586 // detach all active tracks from the chain
6587 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6588 sp<Track> track = mActiveTracks[i].promote();
6589 if (track == 0) continue;
6590 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006591 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006592 chain.get(), session);
6593 chain->decActiveTrackCnt();
6594 }
6595 }
6596
Mathias Agopian65ab4712010-07-14 17:59:35 -07006597 // detach all tracks with same session ID from this chain
6598 for (size_t i = 0; i < mTracks.size(); ++i) {
6599 sp<Track> track = mTracks[i];
6600 if (session == track->sessionId()) {
6601 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006602 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006603 }
6604 }
Eric Laurentde070132010-07-13 04:45:46 -07006605 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006606 }
6607 }
6608 return mEffectChains.size();
6609}
6610
Eric Laurentde070132010-07-13 04:45:46 -07006611status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6612 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006613{
6614 Mutex::Autolock _l(mLock);
6615 return attachAuxEffect_l(track, EffectId);
6616}
6617
Eric Laurentde070132010-07-13 04:45:46 -07006618status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6619 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006620{
6621 status_t status = NO_ERROR;
6622
6623 if (EffectId == 0) {
6624 track->setAuxBuffer(0, NULL);
6625 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006626 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6627 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006628 if (effect != 0) {
6629 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6630 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6631 } else {
6632 status = INVALID_OPERATION;
6633 }
6634 } else {
6635 status = BAD_VALUE;
6636 }
6637 }
6638 return status;
6639}
6640
6641void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6642{
6643 for (size_t i = 0; i < mTracks.size(); ++i) {
6644 sp<Track> track = mTracks[i];
6645 if (track->auxEffectId() == effectId) {
6646 attachAuxEffect_l(track, 0);
6647 }
6648 }
6649}
6650
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006651status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6652{
6653 // only one chain per input thread
6654 if (mEffectChains.size() != 0) {
6655 return INVALID_OPERATION;
6656 }
Steve Block3856b092011-10-20 11:56:00 +01006657 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006658
6659 chain->setInBuffer(NULL);
6660 chain->setOutBuffer(NULL);
6661
Eric Laurent59255e42011-07-27 19:49:51 -07006662 checkSuspendOnAddEffectChain_l(chain);
6663
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006664 mEffectChains.add(chain);
6665
6666 return NO_ERROR;
6667}
6668
6669size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6670{
Steve Block3856b092011-10-20 11:56:00 +01006671 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006672 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006673 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6674 chain.get(), mEffectChains.size(), this);
6675 if (mEffectChains.size() == 1) {
6676 mEffectChains.removeAt(0);
6677 }
6678 return 0;
6679}
6680
Mathias Agopian65ab4712010-07-14 17:59:35 -07006681// ----------------------------------------------------------------------------
6682// EffectModule implementation
6683// ----------------------------------------------------------------------------
6684
6685#undef LOG_TAG
6686#define LOG_TAG "AudioFlinger::EffectModule"
6687
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006688AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006689 const wp<AudioFlinger::EffectChain>& chain,
6690 effect_descriptor_t *desc,
6691 int id,
6692 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006693 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006694 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006695{
Steve Block3856b092011-10-20 11:56:00 +01006696 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006697 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006698 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006699 return;
6700 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006701
6702 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6703
6704 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006705 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006706
6707 if (mStatus != NO_ERROR) {
6708 return;
6709 }
6710 lStatus = init();
6711 if (lStatus < 0) {
6712 mStatus = lStatus;
6713 goto Error;
6714 }
6715
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006716 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6717 mPinned = true;
6718 }
Steve Block3856b092011-10-20 11:56:00 +01006719 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006720 return;
6721Error:
6722 EffectRelease(mEffectInterface);
6723 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006724 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006725}
6726
6727AudioFlinger::EffectModule::~EffectModule()
6728{
Steve Block3856b092011-10-20 11:56:00 +01006729 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006730 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006731 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6732 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6733 sp<ThreadBase> thread = mThread.promote();
6734 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006735 audio_stream_t *stream = thread->stream();
6736 if (stream != NULL) {
6737 stream->remove_audio_effect(stream, mEffectInterface);
6738 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006739 }
6740 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006741 // release effect engine
6742 EffectRelease(mEffectInterface);
6743 }
6744}
6745
Glenn Kasten435dbe62012-01-30 10:15:48 -08006746status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006747{
6748 status_t status;
6749
6750 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006751 int priority = handle->priority();
6752 size_t size = mHandles.size();
6753 sp<EffectHandle> h;
6754 size_t i;
6755 for (i = 0; i < size; i++) {
6756 h = mHandles[i].promote();
6757 if (h == 0) continue;
6758 if (h->priority() <= priority) break;
6759 }
6760 // if inserted in first place, move effect control from previous owner to this handle
6761 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006762 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006763 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006764 enabled = h->enabled();
6765 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006766 }
Eric Laurent59255e42011-07-27 19:49:51 -07006767 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006768 status = NO_ERROR;
6769 } else {
6770 status = ALREADY_EXISTS;
6771 }
Steve Block3856b092011-10-20 11:56:00 +01006772 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006773 mHandles.insertAt(handle, i);
6774 return status;
6775}
6776
6777size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6778{
6779 Mutex::Autolock _l(mLock);
6780 size_t size = mHandles.size();
6781 size_t i;
6782 for (i = 0; i < size; i++) {
6783 if (mHandles[i] == handle) break;
6784 }
6785 if (i == size) {
6786 return size;
6787 }
Steve Block3856b092011-10-20 11:56:00 +01006788 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006789
6790 bool enabled = false;
6791 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006792 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006793 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006794 enabled = hdl->enabled();
6795 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006796 mHandles.removeAt(i);
6797 size = mHandles.size();
6798 // if removed from first place, move effect control from this handle to next in line
6799 if (i == 0 && size != 0) {
6800 sp<EffectHandle> h = mHandles[0].promote();
6801 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006802 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006803 }
6804 }
6805
Eric Laurentec437d82011-07-26 20:54:46 -07006806 // Prevent calls to process() and other functions on effect interface from now on.
6807 // The effect engine will be released by the destructor when the last strong reference on
6808 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006809 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006810 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006811 }
6812
Mathias Agopian65ab4712010-07-14 17:59:35 -07006813 return size;
6814}
6815
Eric Laurent59255e42011-07-27 19:49:51 -07006816sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6817{
6818 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08006819 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07006820}
6821
Glenn Kasten58123c32012-02-03 10:32:24 -08006822void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006823{
Glenn Kasten90bebef2012-01-27 15:24:38 -08006824 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006825 // keep a strong reference on this EffectModule to avoid calling the
6826 // destructor before we exit
6827 sp<EffectModule> keep(this);
6828 {
6829 sp<ThreadBase> thread = mThread.promote();
6830 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006831 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006832 }
6833 }
6834}
6835
6836void AudioFlinger::EffectModule::updateState() {
6837 Mutex::Autolock _l(mLock);
6838
6839 switch (mState) {
6840 case RESTART:
6841 reset_l();
6842 // FALL THROUGH
6843
6844 case STARTING:
6845 // clear auxiliary effect input buffer for next accumulation
6846 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6847 memset(mConfig.inputCfg.buffer.raw,
6848 0,
6849 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6850 }
6851 start_l();
6852 mState = ACTIVE;
6853 break;
6854 case STOPPING:
6855 stop_l();
6856 mDisableWaitCnt = mMaxDisableWaitCnt;
6857 mState = STOPPED;
6858 break;
6859 case STOPPED:
6860 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6861 // turn off sequence.
6862 if (--mDisableWaitCnt == 0) {
6863 reset_l();
6864 mState = IDLE;
6865 }
6866 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006867 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006868 break;
6869 }
6870}
6871
6872void AudioFlinger::EffectModule::process()
6873{
6874 Mutex::Autolock _l(mLock);
6875
Eric Laurentec437d82011-07-26 20:54:46 -07006876 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006877 mConfig.inputCfg.buffer.raw == NULL ||
6878 mConfig.outputCfg.buffer.raw == NULL) {
6879 return;
6880 }
6881
Eric Laurent8f45bd72010-08-31 13:50:07 -07006882 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006883 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6884 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006885 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006886 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006887 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006888 }
6889
6890 // do the actual processing in the effect engine
6891 int ret = (*mEffectInterface)->process(mEffectInterface,
6892 &mConfig.inputCfg.buffer,
6893 &mConfig.outputCfg.buffer);
6894
6895 // force transition to IDLE state when engine is ready
6896 if (mState == STOPPED && ret == -ENODATA) {
6897 mDisableWaitCnt = 1;
6898 }
6899
6900 // clear auxiliary effect input buffer for next accumulation
6901 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006902 memset(mConfig.inputCfg.buffer.raw, 0,
6903 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006904 }
6905 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006906 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6907 // If an insert effect is idle and input buffer is different from output buffer,
6908 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006909 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006910 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006911 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6912 int16_t *in = mConfig.inputCfg.buffer.s16;
6913 int16_t *out = mConfig.outputCfg.buffer.s16;
6914 for (size_t i = 0; i < frameCnt; i++) {
6915 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006916 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006917 }
6918 }
6919}
6920
6921void AudioFlinger::EffectModule::reset_l()
6922{
6923 if (mEffectInterface == NULL) {
6924 return;
6925 }
6926 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6927}
6928
6929status_t AudioFlinger::EffectModule::configure()
6930{
6931 uint32_t channels;
6932 if (mEffectInterface == NULL) {
6933 return NO_INIT;
6934 }
6935
6936 sp<ThreadBase> thread = mThread.promote();
6937 if (thread == 0) {
6938 return DEAD_OBJECT;
6939 }
6940
6941 // TODO: handle configuration of effects replacing track process
6942 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006943 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006944 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006945 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006946 }
6947
6948 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006949 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006950 } else {
6951 mConfig.inputCfg.channels = channels;
6952 }
6953 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006954 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6955 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006956 mConfig.inputCfg.samplingRate = thread->sampleRate();
6957 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6958 mConfig.inputCfg.bufferProvider.cookie = NULL;
6959 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6960 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6961 mConfig.outputCfg.bufferProvider.cookie = NULL;
6962 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6963 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6964 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6965 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006966 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006967 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006968 // - in other sessions:
6969 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6970 // other effect: overwrites output buffer: input buffer == output buffer
6971 // Auxiliary effect:
6972 // accumulates in output buffer: input buffer != output buffer
6973 // Therefore: accumulate <=> input buffer != output buffer
6974 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6975 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6976 } else {
6977 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6978 }
6979 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6980 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6981 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6982 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6983
Steve Block3856b092011-10-20 11:56:00 +01006984 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006985 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6986
Mathias Agopian65ab4712010-07-14 17:59:35 -07006987 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006988 uint32_t size = sizeof(int);
6989 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006990 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006991 sizeof(effect_config_t),
6992 &mConfig,
6993 &size,
6994 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006995 if (status == 0) {
6996 status = cmdStatus;
6997 }
6998
6999 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
7000 (1000 * mConfig.outputCfg.buffer.frameCount);
7001
7002 return status;
7003}
7004
7005status_t AudioFlinger::EffectModule::init()
7006{
7007 Mutex::Autolock _l(mLock);
7008 if (mEffectInterface == NULL) {
7009 return NO_INIT;
7010 }
7011 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007012 uint32_t size = sizeof(status_t);
7013 status_t status = (*mEffectInterface)->command(mEffectInterface,
7014 EFFECT_CMD_INIT,
7015 0,
7016 NULL,
7017 &size,
7018 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007019 if (status == 0) {
7020 status = cmdStatus;
7021 }
7022 return status;
7023}
7024
Eric Laurentec35a142011-10-05 17:42:25 -07007025status_t AudioFlinger::EffectModule::start()
7026{
7027 Mutex::Autolock _l(mLock);
7028 return start_l();
7029}
7030
Mathias Agopian65ab4712010-07-14 17:59:35 -07007031status_t AudioFlinger::EffectModule::start_l()
7032{
7033 if (mEffectInterface == NULL) {
7034 return NO_INIT;
7035 }
7036 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007037 uint32_t size = sizeof(status_t);
7038 status_t status = (*mEffectInterface)->command(mEffectInterface,
7039 EFFECT_CMD_ENABLE,
7040 0,
7041 NULL,
7042 &size,
7043 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007044 if (status == 0) {
7045 status = cmdStatus;
7046 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007047 if (status == 0 &&
7048 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7049 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7050 sp<ThreadBase> thread = mThread.promote();
7051 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007052 audio_stream_t *stream = thread->stream();
7053 if (stream != NULL) {
7054 stream->add_audio_effect(stream, mEffectInterface);
7055 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007056 }
7057 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007058 return status;
7059}
7060
Eric Laurentec437d82011-07-26 20:54:46 -07007061status_t AudioFlinger::EffectModule::stop()
7062{
7063 Mutex::Autolock _l(mLock);
7064 return stop_l();
7065}
7066
Mathias Agopian65ab4712010-07-14 17:59:35 -07007067status_t AudioFlinger::EffectModule::stop_l()
7068{
7069 if (mEffectInterface == NULL) {
7070 return NO_INIT;
7071 }
7072 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007073 uint32_t size = sizeof(status_t);
7074 status_t status = (*mEffectInterface)->command(mEffectInterface,
7075 EFFECT_CMD_DISABLE,
7076 0,
7077 NULL,
7078 &size,
7079 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007080 if (status == 0) {
7081 status = cmdStatus;
7082 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007083 if (status == 0 &&
7084 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7085 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7086 sp<ThreadBase> thread = mThread.promote();
7087 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007088 audio_stream_t *stream = thread->stream();
7089 if (stream != NULL) {
7090 stream->remove_audio_effect(stream, mEffectInterface);
7091 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007092 }
7093 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007094 return status;
7095}
7096
Eric Laurent25f43952010-07-28 05:40:18 -07007097status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
7098 uint32_t cmdSize,
7099 void *pCmdData,
7100 uint32_t *replySize,
7101 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007102{
7103 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007104// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007105
Eric Laurentec437d82011-07-26 20:54:46 -07007106 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007107 return NO_INIT;
7108 }
Eric Laurent25f43952010-07-28 05:40:18 -07007109 status_t status = (*mEffectInterface)->command(mEffectInterface,
7110 cmdCode,
7111 cmdSize,
7112 pCmdData,
7113 replySize,
7114 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007115 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07007116 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007117 for (size_t i = 1; i < mHandles.size(); i++) {
7118 sp<EffectHandle> h = mHandles[i].promote();
7119 if (h != 0) {
7120 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
7121 }
7122 }
7123 }
7124 return status;
7125}
7126
7127status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
7128{
Eric Laurentdb7c0792011-08-10 10:37:50 -07007129
Mathias Agopian65ab4712010-07-14 17:59:35 -07007130 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007131 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007132
7133 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007134 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
7135 if (enabled && status != NO_ERROR) {
7136 return status;
7137 }
7138
Mathias Agopian65ab4712010-07-14 17:59:35 -07007139 switch (mState) {
7140 // going from disabled to enabled
7141 case IDLE:
7142 mState = STARTING;
7143 break;
7144 case STOPPED:
7145 mState = RESTART;
7146 break;
7147 case STOPPING:
7148 mState = ACTIVE;
7149 break;
7150
7151 // going from enabled to disabled
7152 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007153 mState = STOPPED;
7154 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007155 case STARTING:
7156 mState = IDLE;
7157 break;
7158 case ACTIVE:
7159 mState = STOPPING;
7160 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007161 case DESTROYED:
7162 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007163 }
7164 for (size_t i = 1; i < mHandles.size(); i++) {
7165 sp<EffectHandle> h = mHandles[i].promote();
7166 if (h != 0) {
7167 h->setEnabled(enabled);
7168 }
7169 }
7170 }
7171 return NO_ERROR;
7172}
7173
Glenn Kastenc59c0042012-02-02 14:06:11 -08007174bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007175{
7176 switch (mState) {
7177 case RESTART:
7178 case STARTING:
7179 case ACTIVE:
7180 return true;
7181 case IDLE:
7182 case STOPPING:
7183 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07007184 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07007185 default:
7186 return false;
7187 }
7188}
7189
Glenn Kastenc59c0042012-02-02 14:06:11 -08007190bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07007191{
7192 switch (mState) {
7193 case RESTART:
7194 case ACTIVE:
7195 case STOPPING:
7196 case STOPPED:
7197 return true;
7198 case IDLE:
7199 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07007200 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007201 default:
7202 return false;
7203 }
7204}
7205
Mathias Agopian65ab4712010-07-14 17:59:35 -07007206status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7207{
7208 Mutex::Autolock _l(mLock);
7209 status_t status = NO_ERROR;
7210
7211 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7212 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07007213 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07007214 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7215 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007216 status_t cmdStatus;
7217 uint32_t volume[2];
7218 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07007219 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007220 volume[0] = *left;
7221 volume[1] = *right;
7222 if (controller) {
7223 pVolume = volume;
7224 }
Eric Laurent25f43952010-07-28 05:40:18 -07007225 status = (*mEffectInterface)->command(mEffectInterface,
7226 EFFECT_CMD_SET_VOLUME,
7227 size,
7228 volume,
7229 &size,
7230 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007231 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7232 *left = volume[0];
7233 *right = volume[1];
7234 }
7235 }
7236 return status;
7237}
7238
7239status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7240{
7241 Mutex::Autolock _l(mLock);
7242 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007243 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7244 // audio pre processing modules on RecordThread can receive both output and
7245 // input device indication in the same call
7246 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7247 if (dev) {
7248 status_t cmdStatus;
7249 uint32_t size = sizeof(status_t);
7250
7251 status = (*mEffectInterface)->command(mEffectInterface,
7252 EFFECT_CMD_SET_DEVICE,
7253 sizeof(uint32_t),
7254 &dev,
7255 &size,
7256 &cmdStatus);
7257 if (status == NO_ERROR) {
7258 status = cmdStatus;
7259 }
7260 }
7261 dev = device & AUDIO_DEVICE_IN_ALL;
7262 if (dev) {
7263 status_t cmdStatus;
7264 uint32_t size = sizeof(status_t);
7265
7266 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7267 EFFECT_CMD_SET_INPUT_DEVICE,
7268 sizeof(uint32_t),
7269 &dev,
7270 &size,
7271 &cmdStatus);
7272 if (status2 == NO_ERROR) {
7273 status2 = cmdStatus;
7274 }
7275 if (status == NO_ERROR) {
7276 status = status2;
7277 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007278 }
7279 }
7280 return status;
7281}
7282
Glenn Kastenf78aee72012-01-04 11:00:47 -08007283status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007284{
7285 Mutex::Autolock _l(mLock);
7286 status_t status = NO_ERROR;
7287 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007288 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007289 uint32_t size = sizeof(status_t);
7290 status = (*mEffectInterface)->command(mEffectInterface,
7291 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08007292 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07007293 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07007294 &size,
7295 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007296 if (status == NO_ERROR) {
7297 status = cmdStatus;
7298 }
7299 }
7300 return status;
7301}
7302
Eric Laurent59255e42011-07-27 19:49:51 -07007303void AudioFlinger::EffectModule::setSuspended(bool suspended)
7304{
7305 Mutex::Autolock _l(mLock);
7306 mSuspended = suspended;
7307}
Glenn Kastena3a85482012-01-04 11:01:11 -08007308
7309bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07007310{
7311 Mutex::Autolock _l(mLock);
7312 return mSuspended;
7313}
7314
Mathias Agopian65ab4712010-07-14 17:59:35 -07007315status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7316{
7317 const size_t SIZE = 256;
7318 char buffer[SIZE];
7319 String8 result;
7320
7321 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7322 result.append(buffer);
7323
7324 bool locked = tryLock(mLock);
7325 // failed to lock - AudioFlinger is probably deadlocked
7326 if (!locked) {
7327 result.append("\t\tCould not lock Fx mutex:\n");
7328 }
7329
7330 result.append("\t\tSession Status State Engine:\n");
7331 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7332 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7333 result.append(buffer);
7334
7335 result.append("\t\tDescriptor:\n");
7336 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7337 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7338 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7339 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7340 result.append(buffer);
7341 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7342 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7343 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7344 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7345 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07007346 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007347 mDescriptor.apiVersion,
7348 mDescriptor.flags);
7349 result.append(buffer);
7350 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7351 mDescriptor.name);
7352 result.append(buffer);
7353 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7354 mDescriptor.implementor);
7355 result.append(buffer);
7356
7357 result.append("\t\t- Input configuration:\n");
7358 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7359 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7360 (uint32_t)mConfig.inputCfg.buffer.raw,
7361 mConfig.inputCfg.buffer.frameCount,
7362 mConfig.inputCfg.samplingRate,
7363 mConfig.inputCfg.channels,
7364 mConfig.inputCfg.format);
7365 result.append(buffer);
7366
7367 result.append("\t\t- Output configuration:\n");
7368 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7369 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7370 (uint32_t)mConfig.outputCfg.buffer.raw,
7371 mConfig.outputCfg.buffer.frameCount,
7372 mConfig.outputCfg.samplingRate,
7373 mConfig.outputCfg.channels,
7374 mConfig.outputCfg.format);
7375 result.append(buffer);
7376
7377 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7378 result.append(buffer);
7379 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7380 for (size_t i = 0; i < mHandles.size(); ++i) {
7381 sp<EffectHandle> handle = mHandles[i].promote();
7382 if (handle != 0) {
7383 handle->dump(buffer, SIZE);
7384 result.append(buffer);
7385 }
7386 }
7387
7388 result.append("\n");
7389
7390 write(fd, result.string(), result.length());
7391
7392 if (locked) {
7393 mLock.unlock();
7394 }
7395
7396 return NO_ERROR;
7397}
7398
7399// ----------------------------------------------------------------------------
7400// EffectHandle implementation
7401// ----------------------------------------------------------------------------
7402
7403#undef LOG_TAG
7404#define LOG_TAG "AudioFlinger::EffectHandle"
7405
7406AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7407 const sp<AudioFlinger::Client>& client,
7408 const sp<IEffectClient>& effectClient,
7409 int32_t priority)
7410 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007411 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007412 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007413{
Steve Block3856b092011-10-20 11:56:00 +01007414 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007415
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007416 if (client == 0) {
7417 return;
7418 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007419 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7420 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7421 if (mCblkMemory != 0) {
7422 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7423
Glenn Kastena0d68332012-01-27 16:47:15 -08007424 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007425 new(mCblk) effect_param_cblk_t();
7426 mBuffer = (uint8_t *)mCblk + bufOffset;
7427 }
7428 } else {
Steve Block29357bc2012-01-06 19:20:56 +00007429 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007430 return;
7431 }
7432}
7433
7434AudioFlinger::EffectHandle::~EffectHandle()
7435{
Steve Block3856b092011-10-20 11:56:00 +01007436 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007437 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01007438 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007439}
7440
7441status_t AudioFlinger::EffectHandle::enable()
7442{
Steve Block3856b092011-10-20 11:56:00 +01007443 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007444 if (!mHasControl) return INVALID_OPERATION;
7445 if (mEffect == 0) return DEAD_OBJECT;
7446
Eric Laurentdb7c0792011-08-10 10:37:50 -07007447 if (mEnabled) {
7448 return NO_ERROR;
7449 }
7450
Eric Laurent59255e42011-07-27 19:49:51 -07007451 mEnabled = true;
7452
7453 sp<ThreadBase> thread = mEffect->thread().promote();
7454 if (thread != 0) {
7455 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7456 }
7457
7458 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7459 if (mEffect->suspended()) {
7460 return NO_ERROR;
7461 }
7462
Eric Laurentdb7c0792011-08-10 10:37:50 -07007463 status_t status = mEffect->setEnabled(true);
7464 if (status != NO_ERROR) {
7465 if (thread != 0) {
7466 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7467 }
7468 mEnabled = false;
7469 }
7470 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007471}
7472
7473status_t AudioFlinger::EffectHandle::disable()
7474{
Steve Block3856b092011-10-20 11:56:00 +01007475 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007476 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07007477 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007478
Eric Laurentdb7c0792011-08-10 10:37:50 -07007479 if (!mEnabled) {
7480 return NO_ERROR;
7481 }
Eric Laurent59255e42011-07-27 19:49:51 -07007482 mEnabled = false;
7483
7484 if (mEffect->suspended()) {
7485 return NO_ERROR;
7486 }
7487
7488 status_t status = mEffect->setEnabled(false);
7489
7490 sp<ThreadBase> thread = mEffect->thread().promote();
7491 if (thread != 0) {
7492 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7493 }
7494
7495 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007496}
7497
7498void AudioFlinger::EffectHandle::disconnect()
7499{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007500 disconnect(true);
7501}
7502
Glenn Kasten58123c32012-02-03 10:32:24 -08007503void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007504{
Glenn Kasten58123c32012-02-03 10:32:24 -08007505 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007506 if (mEffect == 0) {
7507 return;
7508 }
Glenn Kasten58123c32012-02-03 10:32:24 -08007509 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07007510
Eric Laurenta85a74a2011-10-19 11:44:54 -07007511 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007512 sp<ThreadBase> thread = mEffect->thread().promote();
7513 if (thread != 0) {
7514 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7515 }
Eric Laurent59255e42011-07-27 19:49:51 -07007516 }
7517
Mathias Agopian65ab4712010-07-14 17:59:35 -07007518 // release sp on module => module destructor can be called now
7519 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007520 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08007521 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08007522 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007523 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7524 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08007525 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007526 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07007527 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7528 mClient.clear();
7529 }
7530}
7531
Eric Laurent25f43952010-07-28 05:40:18 -07007532status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7533 uint32_t cmdSize,
7534 void *pCmdData,
7535 uint32_t *replySize,
7536 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007537{
Steve Block3856b092011-10-20 11:56:00 +01007538// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07007539// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007540
7541 // only get parameter command is permitted for applications not controlling the effect
7542 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7543 return INVALID_OPERATION;
7544 }
7545 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007546 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007547
7548 // handle commands that are not forwarded transparently to effect engine
7549 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7550 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7551 // no risk to block the whole media server process or mixer threads is we are stuck here
7552 Mutex::Autolock _l(mCblk->lock);
7553 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7554 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7555 mCblk->serverIndex = 0;
7556 mCblk->clientIndex = 0;
7557 return BAD_VALUE;
7558 }
7559 status_t status = NO_ERROR;
7560 while (mCblk->serverIndex < mCblk->clientIndex) {
7561 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007562 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007563 int *p = (int *)(mBuffer + mCblk->serverIndex);
7564 int size = *p++;
7565 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007566 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007567 break;
7568 }
7569 effect_param_t *param = (effect_param_t *)p;
7570 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007571 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007572 mCblk->serverIndex += size;
7573 continue;
7574 }
Eric Laurent25f43952010-07-28 05:40:18 -07007575 uint32_t psize = sizeof(effect_param_t) +
7576 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7577 param->vsize;
7578 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7579 psize,
7580 p,
7581 &rsize,
7582 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007583 // stop at first error encountered
7584 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007585 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007586 *(int *)pReplyData = reply;
7587 break;
7588 } else if (reply != NO_ERROR) {
7589 *(int *)pReplyData = reply;
7590 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007591 }
7592 mCblk->serverIndex += size;
7593 }
7594 mCblk->serverIndex = 0;
7595 mCblk->clientIndex = 0;
7596 return status;
7597 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007598 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007599 return enable();
7600 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007601 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007602 return disable();
7603 }
7604
7605 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7606}
7607
Eric Laurent59255e42011-07-27 19:49:51 -07007608void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007609{
Steve Block3856b092011-10-20 11:56:00 +01007610 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007611
7612 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007613 mEnabled = enabled;
7614
Mathias Agopian65ab4712010-07-14 17:59:35 -07007615 if (signal && mEffectClient != 0) {
7616 mEffectClient->controlStatusChanged(hasControl);
7617 }
7618}
7619
Eric Laurent25f43952010-07-28 05:40:18 -07007620void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7621 uint32_t cmdSize,
7622 void *pCmdData,
7623 uint32_t replySize,
7624 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007625{
7626 if (mEffectClient != 0) {
7627 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7628 }
7629}
7630
7631
7632
7633void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7634{
7635 if (mEffectClient != 0) {
7636 mEffectClient->enableStatusChanged(enabled);
7637 }
7638}
7639
7640status_t AudioFlinger::EffectHandle::onTransact(
7641 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7642{
7643 return BnEffect::onTransact(code, data, reply, flags);
7644}
7645
7646
7647void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7648{
Glenn Kastena0d68332012-01-27 16:47:15 -08007649 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007650
7651 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08007652 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007653 mPriority,
7654 mHasControl,
7655 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007656 mCblk ? mCblk->clientIndex : 0,
7657 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007658 );
7659
7660 if (locked) {
7661 mCblk->lock.unlock();
7662 }
7663}
7664
7665#undef LOG_TAG
7666#define LOG_TAG "AudioFlinger::EffectChain"
7667
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007668AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007669 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007670 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007671 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7672 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007673{
Dima Zavinfce7a472011-04-19 22:30:36 -07007674 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007675 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007676 return;
7677 }
7678 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7679 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007680}
7681
7682AudioFlinger::EffectChain::~EffectChain()
7683{
7684 if (mOwnInBuffer) {
7685 delete mInBuffer;
7686 }
7687
7688}
7689
Eric Laurent59255e42011-07-27 19:49:51 -07007690// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007691sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007692{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007693 size_t size = mEffects.size();
7694
7695 for (size_t i = 0; i < size; i++) {
7696 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007697 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007698 }
7699 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007700 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007701}
7702
Eric Laurent59255e42011-07-27 19:49:51 -07007703// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007704sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007705{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007706 size_t size = mEffects.size();
7707
7708 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007709 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7710 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007711 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007712 }
7713 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007714 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007715}
7716
Eric Laurent59255e42011-07-27 19:49:51 -07007717// getEffectFromType_l() must be called with ThreadBase::mLock held
7718sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7719 const effect_uuid_t *type)
7720{
Eric Laurent59255e42011-07-27 19:49:51 -07007721 size_t size = mEffects.size();
7722
7723 for (size_t i = 0; i < size; i++) {
7724 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007725 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007726 }
7727 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007728 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007729}
7730
Mathias Agopian65ab4712010-07-14 17:59:35 -07007731// Must be called with EffectChain::mLock locked
7732void AudioFlinger::EffectChain::process_l()
7733{
Eric Laurentdac69112010-09-28 14:09:57 -07007734 sp<ThreadBase> thread = mThread.promote();
7735 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007736 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007737 return;
7738 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007739 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7740 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007741 // always process effects unless no more tracks are on the session and the effect tail
7742 // has been rendered
7743 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007744 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007745 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007746
Eric Laurent544fe9b2011-11-11 15:42:52 -08007747 if (!tracksOnSession && mTailBufferCount == 0) {
7748 doProcess = false;
7749 }
7750
7751 if (activeTrackCnt() == 0) {
7752 // if no track is active and the effect tail has not been rendered,
7753 // the input buffer must be cleared here as the mixer process will not do it
7754 if (tracksOnSession || mTailBufferCount > 0) {
7755 size_t numSamples = thread->frameCount() * thread->channelCount();
7756 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7757 if (mTailBufferCount > 0) {
7758 mTailBufferCount--;
7759 }
7760 }
7761 }
Eric Laurentdac69112010-09-28 14:09:57 -07007762 }
7763
Mathias Agopian65ab4712010-07-14 17:59:35 -07007764 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007765 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007766 for (size_t i = 0; i < size; i++) {
7767 mEffects[i]->process();
7768 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007769 }
7770 for (size_t i = 0; i < size; i++) {
7771 mEffects[i]->updateState();
7772 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007773}
7774
Eric Laurentcab11242010-07-15 12:50:15 -07007775// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007776status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007777{
7778 effect_descriptor_t desc = effect->desc();
7779 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7780
7781 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007782 effect->setChain(this);
7783 sp<ThreadBase> thread = mThread.promote();
7784 if (thread == 0) {
7785 return NO_INIT;
7786 }
7787 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007788
7789 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7790 // Auxiliary effects are inserted at the beginning of mEffects vector as
7791 // they are processed first and accumulated in chain input buffer
7792 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007793
Mathias Agopian65ab4712010-07-14 17:59:35 -07007794 // the input buffer for auxiliary effect contains mono samples in
7795 // 32 bit format. This is to avoid saturation in AudoMixer
7796 // accumulation stage. Saturation is done in EffectModule::process() before
7797 // calling the process in effect engine
7798 size_t numSamples = thread->frameCount();
7799 int32_t *buffer = new int32_t[numSamples];
7800 memset(buffer, 0, numSamples * sizeof(int32_t));
7801 effect->setInBuffer((int16_t *)buffer);
7802 // auxiliary effects output samples to chain input buffer for further processing
7803 // by insert effects
7804 effect->setOutBuffer(mInBuffer);
7805 } else {
7806 // Insert effects are inserted at the end of mEffects vector as they are processed
7807 // after track and auxiliary effects.
7808 // Insert effect order as a function of indicated preference:
7809 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7810 // another effect is present
7811 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7812 // last effect claiming first position
7813 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7814 // first effect claiming last position
7815 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7816 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7817 // already present
7818
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007819 size_t size = mEffects.size();
7820 size_t idx_insert = size;
7821 ssize_t idx_insert_first = -1;
7822 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007823
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007824 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007825 effect_descriptor_t d = mEffects[i]->desc();
7826 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7827 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7828 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7829 // check invalid effect chaining combinations
7830 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7831 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007832 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007833 return INVALID_OPERATION;
7834 }
7835 // remember position of first insert effect and by default
7836 // select this as insert position for new effect
7837 if (idx_insert == size) {
7838 idx_insert = i;
7839 }
7840 // remember position of last insert effect claiming
7841 // first position
7842 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7843 idx_insert_first = i;
7844 }
7845 // remember position of first insert effect claiming
7846 // last position
7847 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7848 idx_insert_last == -1) {
7849 idx_insert_last = i;
7850 }
7851 }
7852 }
7853
7854 // modify idx_insert from first position if needed
7855 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7856 if (idx_insert_last != -1) {
7857 idx_insert = idx_insert_last;
7858 } else {
7859 idx_insert = size;
7860 }
7861 } else {
7862 if (idx_insert_first != -1) {
7863 idx_insert = idx_insert_first + 1;
7864 }
7865 }
7866
7867 // always read samples from chain input buffer
7868 effect->setInBuffer(mInBuffer);
7869
7870 // if last effect in the chain, output samples to chain
7871 // output buffer, otherwise to chain input buffer
7872 if (idx_insert == size) {
7873 if (idx_insert != 0) {
7874 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7875 mEffects[idx_insert-1]->configure();
7876 }
7877 effect->setOutBuffer(mOutBuffer);
7878 } else {
7879 effect->setOutBuffer(mInBuffer);
7880 }
7881 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007882
Steve Block3856b092011-10-20 11:56:00 +01007883 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007884 }
7885 effect->configure();
7886 return NO_ERROR;
7887}
7888
Eric Laurentcab11242010-07-15 12:50:15 -07007889// removeEffect_l() must be called with PlaybackThread::mLock held
7890size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007891{
7892 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007893 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007894 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7895
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007896 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007897 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007898 // calling stop here will remove pre-processing effect from the audio HAL.
7899 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7900 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007901 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7902 mEffects[i]->state() == EffectModule::STOPPING) {
7903 mEffects[i]->stop();
7904 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007905 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7906 delete[] effect->inBuffer();
7907 } else {
7908 if (i == size - 1 && i != 0) {
7909 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7910 mEffects[i - 1]->configure();
7911 }
7912 }
7913 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007914 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007915 break;
7916 }
7917 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007918
7919 return mEffects.size();
7920}
7921
Eric Laurentcab11242010-07-15 12:50:15 -07007922// setDevice_l() must be called with PlaybackThread::mLock held
7923void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007924{
7925 size_t size = mEffects.size();
7926 for (size_t i = 0; i < size; i++) {
7927 mEffects[i]->setDevice(device);
7928 }
7929}
7930
Eric Laurentcab11242010-07-15 12:50:15 -07007931// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007932void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007933{
7934 size_t size = mEffects.size();
7935 for (size_t i = 0; i < size; i++) {
7936 mEffects[i]->setMode(mode);
7937 }
7938}
7939
Eric Laurentcab11242010-07-15 12:50:15 -07007940// setVolume_l() must be called with PlaybackThread::mLock held
7941bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007942{
7943 uint32_t newLeft = *left;
7944 uint32_t newRight = *right;
7945 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007946 int ctrlIdx = -1;
7947 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007948
Eric Laurentcab11242010-07-15 12:50:15 -07007949 // first update volume controller
7950 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007951 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007952 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7953 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007954 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007955 break;
7956 }
7957 }
7958
7959 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007960 if (hasControl) {
7961 *left = mNewLeftVolume;
7962 *right = mNewRightVolume;
7963 }
7964 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007965 }
7966
7967 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007968 mLeftVolume = newLeft;
7969 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007970
7971 // second get volume update from volume controller
7972 if (ctrlIdx >= 0) {
7973 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007974 mNewLeftVolume = newLeft;
7975 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007976 }
7977 // then indicate volume to all other effects in chain.
7978 // Pass altered volume to effects before volume controller
7979 // and requested volume to effects after controller
7980 uint32_t lVol = newLeft;
7981 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007982
Mathias Agopian65ab4712010-07-14 17:59:35 -07007983 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007984 if ((int)i == ctrlIdx) continue;
7985 // this also works for ctrlIdx == -1 when there is no volume controller
7986 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007987 lVol = *left;
7988 rVol = *right;
7989 }
7990 mEffects[i]->setVolume(&lVol, &rVol, false);
7991 }
7992 *left = newLeft;
7993 *right = newRight;
7994
7995 return hasControl;
7996}
7997
Mathias Agopian65ab4712010-07-14 17:59:35 -07007998status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7999{
8000 const size_t SIZE = 256;
8001 char buffer[SIZE];
8002 String8 result;
8003
8004 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
8005 result.append(buffer);
8006
8007 bool locked = tryLock(mLock);
8008 // failed to lock - AudioFlinger is probably deadlocked
8009 if (!locked) {
8010 result.append("\tCould not lock mutex:\n");
8011 }
8012
Eric Laurentcab11242010-07-15 12:50:15 -07008013 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
8014 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008015 mEffects.size(),
8016 (uint32_t)mInBuffer,
8017 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008018 mActiveTrackCnt);
8019 result.append(buffer);
8020 write(fd, result.string(), result.size());
8021
8022 for (size_t i = 0; i < mEffects.size(); ++i) {
8023 sp<EffectModule> effect = mEffects[i];
8024 if (effect != 0) {
8025 effect->dump(fd, args);
8026 }
8027 }
8028
8029 if (locked) {
8030 mLock.unlock();
8031 }
8032
8033 return NO_ERROR;
8034}
8035
Eric Laurent59255e42011-07-27 19:49:51 -07008036// must be called with ThreadBase::mLock held
8037void AudioFlinger::EffectChain::setEffectSuspended_l(
8038 const effect_uuid_t *type, bool suspend)
8039{
8040 sp<SuspendedEffectDesc> desc;
8041 // use effect type UUID timelow as key as there is no real risk of identical
8042 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008043 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008044 if (suspend) {
8045 if (index >= 0) {
8046 desc = mSuspendedEffects.valueAt(index);
8047 } else {
8048 desc = new SuspendedEffectDesc();
8049 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
8050 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01008051 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008052 }
8053 if (desc->mRefCount++ == 0) {
8054 sp<EffectModule> effect = getEffectIfEnabled(type);
8055 if (effect != 0) {
8056 desc->mEffect = effect;
8057 effect->setSuspended(true);
8058 effect->setEnabled(false);
8059 }
8060 }
8061 } else {
8062 if (index < 0) {
8063 return;
8064 }
8065 desc = mSuspendedEffects.valueAt(index);
8066 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008067 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008068 desc->mRefCount = 1;
8069 }
8070 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01008071 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008072 if (desc->mEffect != 0) {
8073 sp<EffectModule> effect = desc->mEffect.promote();
8074 if (effect != 0) {
8075 effect->setSuspended(false);
8076 sp<EffectHandle> handle = effect->controlHandle();
8077 if (handle != 0) {
8078 effect->setEnabled(handle->enabled());
8079 }
8080 }
8081 desc->mEffect.clear();
8082 }
8083 mSuspendedEffects.removeItemsAt(index);
8084 }
8085 }
8086}
8087
8088// must be called with ThreadBase::mLock held
8089void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
8090{
8091 sp<SuspendedEffectDesc> desc;
8092
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008093 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07008094 if (suspend) {
8095 if (index >= 0) {
8096 desc = mSuspendedEffects.valueAt(index);
8097 } else {
8098 desc = new SuspendedEffectDesc();
8099 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01008100 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07008101 }
8102 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08008103 Vector< sp<EffectModule> > effects;
8104 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07008105 for (size_t i = 0; i < effects.size(); i++) {
8106 setEffectSuspended_l(&effects[i]->desc().type, true);
8107 }
8108 }
8109 } else {
8110 if (index < 0) {
8111 return;
8112 }
8113 desc = mSuspendedEffects.valueAt(index);
8114 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008115 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008116 desc->mRefCount = 1;
8117 }
8118 if (--desc->mRefCount == 0) {
8119 Vector<const effect_uuid_t *> types;
8120 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
8121 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
8122 continue;
8123 }
8124 types.add(&mSuspendedEffects.valueAt(i)->mType);
8125 }
8126 for (size_t i = 0; i < types.size(); i++) {
8127 setEffectSuspended_l(types[i], false);
8128 }
Steve Block3856b092011-10-20 11:56:00 +01008129 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008130 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
8131 }
8132 }
8133}
8134
Eric Laurent6bffdb82011-09-23 08:40:41 -07008135
8136// The volume effect is used for automated tests only
8137#ifndef OPENSL_ES_H_
8138static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
8139 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
8140const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
8141#endif //OPENSL_ES_H_
8142
Eric Laurentdb7c0792011-08-10 10:37:50 -07008143bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
8144{
8145 // auxiliary effects and visualizer are never suspended on output mix
8146 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8147 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07008148 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8149 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008150 return false;
8151 }
8152 return true;
8153}
8154
Glenn Kastend0539712012-01-30 12:56:03 -08008155void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07008156{
Glenn Kastend0539712012-01-30 12:56:03 -08008157 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07008158 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08008159 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8160 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07008161 }
Eric Laurent59255e42011-07-27 19:49:51 -07008162 }
Eric Laurent59255e42011-07-27 19:49:51 -07008163}
8164
8165sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8166 const effect_uuid_t *type)
8167{
Glenn Kasten090f0192012-01-30 13:00:02 -08008168 sp<EffectModule> effect = getEffectFromType_l(type);
8169 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008170}
8171
8172void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8173 bool enabled)
8174{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008175 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008176 if (enabled) {
8177 if (index < 0) {
8178 // if the effect is not suspend check if all effects are suspended
8179 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8180 if (index < 0) {
8181 return;
8182 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07008183 if (!isEffectEligibleForSuspend(effect->desc())) {
8184 return;
8185 }
Eric Laurent59255e42011-07-27 19:49:51 -07008186 setEffectSuspended_l(&effect->desc().type, enabled);
8187 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07008188 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008189 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07008190 return;
8191 }
Eric Laurent59255e42011-07-27 19:49:51 -07008192 }
Steve Block3856b092011-10-20 11:56:00 +01008193 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07008194 effect->desc().type.timeLow);
8195 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8196 // if effect is requested to suspended but was not yet enabled, supend it now.
8197 if (desc->mEffect == 0) {
8198 desc->mEffect = effect;
8199 effect->setEnabled(false);
8200 effect->setSuspended(true);
8201 }
8202 } else {
8203 if (index < 0) {
8204 return;
8205 }
Steve Block3856b092011-10-20 11:56:00 +01008206 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07008207 effect->desc().type.timeLow);
8208 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8209 desc->mEffect.clear();
8210 effect->setSuspended(false);
8211 }
8212}
8213
Mathias Agopian65ab4712010-07-14 17:59:35 -07008214#undef LOG_TAG
8215#define LOG_TAG "AudioFlinger"
8216
8217// ----------------------------------------------------------------------------
8218
8219status_t AudioFlinger::onTransact(
8220 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8221{
8222 return BnAudioFlinger::onTransact(code, data, reply, flags);
8223}
8224
Mathias Agopian65ab4712010-07-14 17:59:35 -07008225}; // namespace android