blob: 3f4994183df608be65b9ad95e067f3f874f2edf7 [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 }
235 mHardwareStatus = AUDIO_HW_INIT;
236 }
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
257 mHardwareStatus = AUDIO_HW_INIT;
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{
826 status_t result;
827
Glenn Kasten23d82a92012-02-03 11:10:00 -0800828 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700829 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
830 // check calling permissions
831 if (!settingsAllowed()) {
832 return PERMISSION_DENIED;
833 }
834
Mathias Agopian65ab4712010-07-14 17:59:35 -0700835 // ioHandle == 0 means the parameters are global to the audio hardware interface
836 if (ioHandle == 0) {
837 AutoMutex lock(mHardwareLock);
838 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700839 status_t final_result = NO_ERROR;
840 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
841 audio_hw_device_t *dev = mAudioHwDevs[i];
842 result = dev->set_parameters(dev, keyValuePairs.string());
843 final_result = result ?: final_result;
844 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845 mHardwareStatus = AUDIO_HW_IDLE;
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++) {
908 audio_hw_device_t *dev = mAudioHwDevs[i];
909 char *s = dev->get_parameters(dev, keys.string());
John Grossmanef7740b2012-02-09 11:28:36 -0800910 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700911 free(s);
912 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700913 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700914 }
915
916 Mutex::Autolock _l(mLock);
917
918 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
919 if (playbackThread != NULL) {
920 return playbackThread->getParameters(keys);
921 }
922 RecordThread *recordThread = checkRecordThread_l(ioHandle);
923 if (recordThread != NULL) {
924 return recordThread->getParameters(keys);
925 }
926 return String8("");
927}
928
Glenn Kastenf587ba52012-01-26 16:25:10 -0800929size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700930{
Eric Laurenta1884f92011-08-23 08:25:03 -0700931 status_t ret = initCheck();
932 if (ret != NO_ERROR) {
933 return 0;
934 }
935
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800936 AutoMutex lock(mHardwareLock);
937 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
938 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
939 mHardwareStatus = AUDIO_HW_IDLE;
940 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700941}
942
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800943unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700944{
945 if (ioHandle == 0) {
946 return 0;
947 }
948
949 Mutex::Autolock _l(mLock);
950
951 RecordThread *recordThread = checkRecordThread_l(ioHandle);
952 if (recordThread != NULL) {
953 return recordThread->getInputFramesLost();
954 }
955 return 0;
956}
957
958status_t AudioFlinger::setVoiceVolume(float value)
959{
Eric Laurenta1884f92011-08-23 08:25:03 -0700960 status_t ret = initCheck();
961 if (ret != NO_ERROR) {
962 return ret;
963 }
964
Mathias Agopian65ab4712010-07-14 17:59:35 -0700965 // check calling permissions
966 if (!settingsAllowed()) {
967 return PERMISSION_DENIED;
968 }
969
970 AutoMutex lock(mHardwareLock);
971 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700972 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700973 mHardwareStatus = AUDIO_HW_IDLE;
974
975 return ret;
976}
977
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800978status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
979 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700980{
981 status_t status;
982
983 Mutex::Autolock _l(mLock);
984
985 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
986 if (playbackThread != NULL) {
987 return playbackThread->getRenderPosition(halFrames, dspFrames);
988 }
989
990 return BAD_VALUE;
991}
992
993void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
994{
995
996 Mutex::Autolock _l(mLock);
997
Glenn Kastenbb001922012-02-03 11:10:26 -0800998 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700999 if (mNotificationClients.indexOfKey(pid) < 0) {
1000 sp<NotificationClient> notificationClient = new NotificationClient(this,
1001 client,
1002 pid);
Steve Block3856b092011-10-20 11:56:00 +01001003 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001004
1005 mNotificationClients.add(pid, notificationClient);
1006
1007 sp<IBinder> binder = client->asBinder();
1008 binder->linkToDeath(notificationClient);
1009
1010 // the config change is always sent from playback or record threads to avoid deadlock
1011 // with AudioSystem::gLock
1012 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1013 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1014 }
1015
1016 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1017 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1018 }
1019 }
1020}
1021
1022void AudioFlinger::removeNotificationClient(pid_t pid)
1023{
1024 Mutex::Autolock _l(mLock);
1025
Glenn Kastena3b09252012-01-20 09:19:01 -08001026 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001027
Steve Block3856b092011-10-20 11:56:00 +01001028 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001029 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001030 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001031 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001032 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +01001033 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001034 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +01001035 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001036 mAudioSessionRefs.removeAt(i);
1037 delete ref;
1038 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001039 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001040 } else {
1041 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001042 }
1043 }
1044 if (removed) {
1045 purgeStaleEffects_l();
1046 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001047}
1048
1049// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001050void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001051{
1052 size_t size = mNotificationClients.size();
1053 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001054 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1055 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001056 }
1057}
1058
1059// removeClient_l() must be called with AudioFlinger::mLock held
1060void AudioFlinger::removeClient_l(pid_t pid)
1061{
Steve Block3856b092011-10-20 11:56:00 +01001062 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001063 mClients.removeItem(pid);
1064}
1065
1066
1067// ----------------------------------------------------------------------------
1068
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001069AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1070 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001071 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001072 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001073 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
1074 // mChannelMask
1075 mChannelCount(0),
1076 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1077 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001078 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001079 mDevice(device),
1080 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001081{
1082}
1083
1084AudioFlinger::ThreadBase::~ThreadBase()
1085{
1086 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001087 // do not lock the mutex in destructor
1088 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001089 if (mPowerManager != 0) {
1090 sp<IBinder> binder = mPowerManager->asBinder();
1091 binder->unlinkToDeath(mDeathRecipient);
1092 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001093}
1094
1095void AudioFlinger::ThreadBase::exit()
1096{
Steve Block3856b092011-10-20 11:56:00 +01001097 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001098 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001099 // This lock prevents the following race in thread (uniprocessor for illustration):
1100 // if (!exitPending()) {
1101 // // context switch from here to exit()
1102 // // exit() calls requestExit(), what exitPending() observes
1103 // // exit() calls signal(), which is dropped since no waiters
1104 // // context switch back from exit() to here
1105 // mWaitWorkCV.wait(...);
1106 // // now thread is hung
1107 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001108 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001109 requestExit();
1110 mWaitWorkCV.signal();
1111 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001112 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1113 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001114 requestExitAndWait();
1115}
1116
Mathias Agopian65ab4712010-07-14 17:59:35 -07001117status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1118{
1119 status_t status;
1120
Steve Block3856b092011-10-20 11:56:00 +01001121 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001122 Mutex::Autolock _l(mLock);
1123
1124 mNewParameters.add(keyValuePairs);
1125 mWaitWorkCV.signal();
1126 // wait condition with timeout in case the thread loop has exited
1127 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001128 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001129 status = mParamStatus;
1130 mWaitWorkCV.signal();
1131 } else {
1132 status = TIMED_OUT;
1133 }
1134 return status;
1135}
1136
1137void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1138{
1139 Mutex::Autolock _l(mLock);
1140 sendConfigEvent_l(event, param);
1141}
1142
1143// sendConfigEvent_l() must be called with ThreadBase::mLock held
1144void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1145{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001146 ConfigEvent configEvent;
1147 configEvent.mEvent = event;
1148 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001149 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001150 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001151 mWaitWorkCV.signal();
1152}
1153
1154void AudioFlinger::ThreadBase::processConfigEvents()
1155{
1156 mLock.lock();
1157 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001158 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001159 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001160 mConfigEvents.removeAt(0);
1161 // release mLock before locking AudioFlinger mLock: lock order is always
1162 // AudioFlinger then ThreadBase to avoid cross deadlock
1163 mLock.unlock();
1164 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001165 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001166 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001167 mLock.lock();
1168 }
1169 mLock.unlock();
1170}
1171
1172status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1173{
1174 const size_t SIZE = 256;
1175 char buffer[SIZE];
1176 String8 result;
1177
1178 bool locked = tryLock(mLock);
1179 if (!locked) {
1180 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1181 write(fd, buffer, strlen(buffer));
1182 }
1183
1184 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1185 result.append(buffer);
1186 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1187 result.append(buffer);
1188 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1189 result.append(buffer);
1190 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1191 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001192 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1193 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001194 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1195 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001196 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001197 result.append(buffer);
1198
1199 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1200 result.append(buffer);
1201 result.append(" Index Command");
1202 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1203 snprintf(buffer, SIZE, "\n %02d ", i);
1204 result.append(buffer);
1205 result.append(mNewParameters[i]);
1206 }
1207
1208 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1209 result.append(buffer);
1210 snprintf(buffer, SIZE, " Index event param\n");
1211 result.append(buffer);
1212 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001213 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001214 result.append(buffer);
1215 }
1216 result.append("\n");
1217
1218 write(fd, result.string(), result.size());
1219
1220 if (locked) {
1221 mLock.unlock();
1222 }
1223 return NO_ERROR;
1224}
1225
Eric Laurent1d2bff02011-07-24 17:49:51 -07001226status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1227{
1228 const size_t SIZE = 256;
1229 char buffer[SIZE];
1230 String8 result;
1231
1232 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1233 write(fd, buffer, strlen(buffer));
1234
1235 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1236 sp<EffectChain> chain = mEffectChains[i];
1237 if (chain != 0) {
1238 chain->dump(fd, args);
1239 }
1240 }
1241 return NO_ERROR;
1242}
1243
Eric Laurentfeb0db62011-07-22 09:04:31 -07001244void AudioFlinger::ThreadBase::acquireWakeLock()
1245{
1246 Mutex::Autolock _l(mLock);
1247 acquireWakeLock_l();
1248}
1249
1250void AudioFlinger::ThreadBase::acquireWakeLock_l()
1251{
1252 if (mPowerManager == 0) {
1253 // use checkService() to avoid blocking if power service is not up yet
1254 sp<IBinder> binder =
1255 defaultServiceManager()->checkService(String16("power"));
1256 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001257 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001258 } else {
1259 mPowerManager = interface_cast<IPowerManager>(binder);
1260 binder->linkToDeath(mDeathRecipient);
1261 }
1262 }
1263 if (mPowerManager != 0) {
1264 sp<IBinder> binder = new BBinder();
1265 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1266 binder,
1267 String16(mName));
1268 if (status == NO_ERROR) {
1269 mWakeLockToken = binder;
1270 }
Steve Block3856b092011-10-20 11:56:00 +01001271 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001272 }
1273}
1274
1275void AudioFlinger::ThreadBase::releaseWakeLock()
1276{
1277 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001278 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001279}
1280
1281void AudioFlinger::ThreadBase::releaseWakeLock_l()
1282{
1283 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001284 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001285 if (mPowerManager != 0) {
1286 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1287 }
1288 mWakeLockToken.clear();
1289 }
1290}
1291
1292void AudioFlinger::ThreadBase::clearPowerManager()
1293{
1294 Mutex::Autolock _l(mLock);
1295 releaseWakeLock_l();
1296 mPowerManager.clear();
1297}
1298
1299void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1300{
1301 sp<ThreadBase> thread = mThread.promote();
1302 if (thread != 0) {
1303 thread->clearPowerManager();
1304 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001305 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001306}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001307
Eric Laurent59255e42011-07-27 19:49:51 -07001308void AudioFlinger::ThreadBase::setEffectSuspended(
1309 const effect_uuid_t *type, bool suspend, int sessionId)
1310{
1311 Mutex::Autolock _l(mLock);
1312 setEffectSuspended_l(type, suspend, sessionId);
1313}
1314
1315void AudioFlinger::ThreadBase::setEffectSuspended_l(
1316 const effect_uuid_t *type, bool suspend, int sessionId)
1317{
Glenn Kasten090f0192012-01-30 13:00:02 -08001318 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001319 if (chain != 0) {
1320 if (type != NULL) {
1321 chain->setEffectSuspended_l(type, suspend);
1322 } else {
1323 chain->setEffectSuspendedAll_l(suspend);
1324 }
1325 }
1326
1327 updateSuspendedSessions_l(type, suspend, sessionId);
1328}
1329
1330void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1331{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001332 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001333 if (index < 0) {
1334 return;
1335 }
1336
1337 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1338 mSuspendedSessions.editValueAt(index);
1339
1340 for (size_t i = 0; i < sessionEffects.size(); i++) {
1341 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1342 for (int j = 0; j < desc->mRefCount; j++) {
1343 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1344 chain->setEffectSuspendedAll_l(true);
1345 } else {
Steve Block3856b092011-10-20 11:56:00 +01001346 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001347 desc->mType.timeLow);
1348 chain->setEffectSuspended_l(&desc->mType, true);
1349 }
1350 }
1351 }
1352}
1353
Eric Laurent59255e42011-07-27 19:49:51 -07001354void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1355 bool suspend,
1356 int sessionId)
1357{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001358 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001359
1360 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1361
1362 if (suspend) {
1363 if (index >= 0) {
1364 sessionEffects = mSuspendedSessions.editValueAt(index);
1365 } else {
1366 mSuspendedSessions.add(sessionId, sessionEffects);
1367 }
1368 } else {
1369 if (index < 0) {
1370 return;
1371 }
1372 sessionEffects = mSuspendedSessions.editValueAt(index);
1373 }
1374
1375
1376 int key = EffectChain::kKeyForSuspendAll;
1377 if (type != NULL) {
1378 key = type->timeLow;
1379 }
1380 index = sessionEffects.indexOfKey(key);
1381
1382 sp <SuspendedSessionDesc> desc;
1383 if (suspend) {
1384 if (index >= 0) {
1385 desc = sessionEffects.valueAt(index);
1386 } else {
1387 desc = new SuspendedSessionDesc();
1388 if (type != NULL) {
1389 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1390 }
1391 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001392 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001393 }
1394 desc->mRefCount++;
1395 } else {
1396 if (index < 0) {
1397 return;
1398 }
1399 desc = sessionEffects.valueAt(index);
1400 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001401 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001402 sessionEffects.removeItemsAt(index);
1403 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001404 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001405 sessionId);
1406 mSuspendedSessions.removeItem(sessionId);
1407 }
1408 }
1409 }
1410 if (!sessionEffects.isEmpty()) {
1411 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1412 }
1413}
1414
1415void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1416 bool enabled,
1417 int sessionId)
1418{
1419 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001420 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1421}
Eric Laurent59255e42011-07-27 19:49:51 -07001422
Eric Laurenta85a74a2011-10-19 11:44:54 -07001423void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1424 bool enabled,
1425 int sessionId)
1426{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001427 if (mType != RECORD) {
1428 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1429 // another session. This gives the priority to well behaved effect control panels
1430 // and applications not using global effects.
1431 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1432 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1433 }
1434 }
Eric Laurent59255e42011-07-27 19:49:51 -07001435
1436 sp<EffectChain> chain = getEffectChain_l(sessionId);
1437 if (chain != 0) {
1438 chain->checkSuspendOnEffectEnabled(effect, enabled);
1439 }
1440}
1441
Mathias Agopian65ab4712010-07-14 17:59:35 -07001442// ----------------------------------------------------------------------------
1443
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001444AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1445 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001446 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001447 uint32_t device,
1448 type_t type)
1449 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001450 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1451 // Assumes constructor is called by AudioFlinger with it's mLock held,
1452 // but it would be safer to explicitly pass initial masterMute as parameter
1453 mMasterMute(audioFlinger->masterMute_l()),
1454 // mStreamTypes[] initialized in constructor body
1455 mOutput(output),
1456 // Assumes constructor is called by AudioFlinger with it's mLock held,
1457 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001458 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001459 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001460{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001461 snprintf(mName, kNameLength, "AudioOut_%d", id);
1462
Mathias Agopian65ab4712010-07-14 17:59:35 -07001463 readOutputParameters();
1464
Glenn Kasten263709e2012-01-06 08:40:01 -08001465 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001466 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1467 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1468 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001469 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1470 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001471 // initialized by stream_type_t default constructor
1472 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001473 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001474 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1475 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001476}
1477
1478AudioFlinger::PlaybackThread::~PlaybackThread()
1479{
1480 delete [] mMixBuffer;
1481}
1482
1483status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1484{
1485 dumpInternals(fd, args);
1486 dumpTracks(fd, args);
1487 dumpEffectChains(fd, args);
1488 return NO_ERROR;
1489}
1490
1491status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1492{
1493 const size_t SIZE = 256;
1494 char buffer[SIZE];
1495 String8 result;
1496
1497 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1498 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001499 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 -07001500 for (size_t i = 0; i < mTracks.size(); ++i) {
1501 sp<Track> track = mTracks[i];
1502 if (track != 0) {
1503 track->dump(buffer, SIZE);
1504 result.append(buffer);
1505 }
1506 }
1507
1508 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1509 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001510 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 -07001511 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001512 sp<Track> track = mActiveTracks[i].promote();
1513 if (track != 0) {
1514 track->dump(buffer, SIZE);
1515 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001516 }
1517 }
1518 write(fd, result.string(), result.size());
1519 return NO_ERROR;
1520}
1521
Mathias Agopian65ab4712010-07-14 17:59:35 -07001522status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1523{
1524 const size_t SIZE = 256;
1525 char buffer[SIZE];
1526 String8 result;
1527
1528 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1529 result.append(buffer);
1530 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1531 result.append(buffer);
1532 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1533 result.append(buffer);
1534 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1535 result.append(buffer);
1536 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1537 result.append(buffer);
1538 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1539 result.append(buffer);
1540 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1541 result.append(buffer);
1542 write(fd, result.string(), result.size());
1543
1544 dumpBase(fd, args);
1545
1546 return NO_ERROR;
1547}
1548
1549// Thread virtuals
1550status_t AudioFlinger::PlaybackThread::readyToRun()
1551{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001552 status_t status = initCheck();
1553 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001554 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001555 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001556 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001557 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001558 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001559}
1560
1561void AudioFlinger::PlaybackThread::onFirstRef()
1562{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001563 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001564}
1565
1566// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1567sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1568 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001569 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001570 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001571 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001572 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001573 int frameCount,
1574 const sp<IMemory>& sharedBuffer,
1575 int sessionId,
John Grossman4ff14ba2012-02-08 16:37:41 -08001576 bool isTimed,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001577 status_t *status)
1578{
1579 sp<Track> track;
1580 status_t lStatus;
1581
1582 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001583 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1584 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001585 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001586 "for output %p with format %d",
1587 sampleRate, format, channelMask, mOutput, mFormat);
1588 lStatus = BAD_VALUE;
1589 goto Exit;
1590 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001591 }
1592 } else {
1593 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1594 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001595 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001596 lStatus = BAD_VALUE;
1597 goto Exit;
1598 }
1599 }
1600
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001601 lStatus = initCheck();
1602 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001603 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001604 goto Exit;
1605 }
1606
1607 { // scope for mLock
1608 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001609
1610 // all tracks in same audio session must share the same routing strategy otherwise
1611 // conflicts will happen when tracks are moved from one output to another by audio policy
1612 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001613 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001614 for (size_t i = 0; i < mTracks.size(); ++i) {
1615 sp<Track> t = mTracks[i];
1616 if (t != 0) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001617 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001618 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001619 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001620 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001621 lStatus = BAD_VALUE;
1622 goto Exit;
1623 }
1624 }
1625 }
1626
John Grossman4ff14ba2012-02-08 16:37:41 -08001627 if (!isTimed) {
1628 track = new Track(this, client, streamType, sampleRate, format,
1629 channelMask, frameCount, sharedBuffer, sessionId);
1630 } else {
1631 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1632 channelMask, frameCount, sharedBuffer, sessionId);
1633 }
1634 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001635 lStatus = NO_MEMORY;
1636 goto Exit;
1637 }
1638 mTracks.add(track);
1639
1640 sp<EffectChain> chain = getEffectChain_l(sessionId);
1641 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001642 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001643 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001644 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001645 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001646 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001647
1648 // invalidate track immediately if the stream type was moved to another thread since
1649 // createTrack() was called by the client process.
1650 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001651 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001652 this, streamType);
1653 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1654 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001655 }
1656 lStatus = NO_ERROR;
1657
1658Exit:
1659 if(status) {
1660 *status = lStatus;
1661 }
1662 return track;
1663}
1664
1665uint32_t AudioFlinger::PlaybackThread::latency() const
1666{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001667 Mutex::Autolock _l(mLock);
1668 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001669 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001670 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001671 return 0;
1672 }
1673}
1674
Glenn Kasten6637baa2012-01-09 09:40:36 -08001675void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001676{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001677 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001678 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001679}
1680
Glenn Kasten6637baa2012-01-09 09:40:36 -08001681void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001682{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001683 Mutex::Autolock _l(mLock);
1684 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685}
1686
Glenn Kasten6637baa2012-01-09 09:40:36 -08001687void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001688{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001689 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001690 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001691}
1692
Glenn Kasten6637baa2012-01-09 09:40:36 -08001693void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
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].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001697}
1698
Glenn Kastenfff6d712012-01-12 16:38:12 -08001699float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
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 return mStreamTypes[stream].volume;
1703}
1704
Mathias Agopian65ab4712010-07-14 17:59:35 -07001705// addTrack_l() must be called with ThreadBase::mLock held
1706status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1707{
1708 status_t status = ALREADY_EXISTS;
1709
1710 // set retry count for buffer fill
1711 track->mRetryCount = kMaxTrackStartupRetries;
1712 if (mActiveTracks.indexOf(track) < 0) {
1713 // the track is newly added, make sure it fills up all its
1714 // buffers before playing. This is to ensure the client will
1715 // effectively get the latency it requested.
1716 track->mFillingUpStatus = Track::FS_FILLING;
1717 track->mResetDone = false;
1718 mActiveTracks.add(track);
1719 if (track->mainBuffer() != mMixBuffer) {
1720 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1721 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001722 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001723 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001724 }
1725 }
1726
1727 status = NO_ERROR;
1728 }
1729
Steve Block3856b092011-10-20 11:56:00 +01001730 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001731 mWaitWorkCV.broadcast();
1732
1733 return status;
1734}
1735
1736// destroyTrack_l() must be called with ThreadBase::mLock held
1737void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1738{
1739 track->mState = TrackBase::TERMINATED;
1740 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001741 removeTrack_l(track);
1742 }
1743}
1744
1745void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1746{
1747 mTracks.remove(track);
1748 deleteTrackName_l(track->name());
1749 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1750 if (chain != 0) {
1751 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001752 }
1753}
1754
1755String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1756{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001757 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001758 char *s;
1759
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001760 Mutex::Autolock _l(mLock);
1761 if (initCheck() != NO_ERROR) {
1762 return out_s8;
1763 }
1764
Dima Zavin799a70e2011-04-18 16:57:27 -07001765 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001766 out_s8 = String8(s);
1767 free(s);
1768 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001769}
1770
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001771// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001772void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1773 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001774 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001775
Steve Block3856b092011-10-20 11:56:00 +01001776 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001777
1778 switch (event) {
1779 case AudioSystem::OUTPUT_OPENED:
1780 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001781 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001782 desc.samplingRate = mSampleRate;
1783 desc.format = mFormat;
1784 desc.frameCount = mFrameCount;
1785 desc.latency = latency();
1786 param2 = &desc;
1787 break;
1788
1789 case AudioSystem::STREAM_CONFIG_CHANGED:
1790 param2 = &param;
1791 case AudioSystem::OUTPUT_CLOSED:
1792 default:
1793 break;
1794 }
1795 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1796}
1797
1798void AudioFlinger::PlaybackThread::readOutputParameters()
1799{
Dima Zavin799a70e2011-04-18 16:57:27 -07001800 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001801 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1802 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001803 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001804 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001805 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001806
1807 // FIXME - Current mixer implementation only supports stereo output: Always
1808 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001809 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001810 mMixBuffer = new int16_t[mFrameCount * 2];
1811 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1812
Eric Laurentde070132010-07-13 04:45:46 -07001813 // force reconfiguration of effect chains and engines to take new buffer size and audio
1814 // parameters into account
1815 // Note that mLock is not held when readOutputParameters() is called from the constructor
1816 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1817 // matter.
1818 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1819 Vector< sp<EffectChain> > effectChains = mEffectChains;
1820 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001821 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001822 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001823}
1824
1825status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1826{
Glenn Kastena0d68332012-01-27 16:47:15 -08001827 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001828 return BAD_VALUE;
1829 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001830 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001831 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001832 return INVALID_OPERATION;
1833 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001834 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001835
Dima Zavin799a70e2011-04-18 16:57:27 -07001836 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001837}
1838
Eric Laurent39e94f82010-07-28 01:32:47 -07001839uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001840{
1841 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001842 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001843 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001844 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001845 }
1846
1847 for (size_t i = 0; i < mTracks.size(); ++i) {
1848 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001849 if (sessionId == track->sessionId() &&
1850 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001851 result |= TRACK_SESSION;
1852 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853 }
1854 }
1855
Eric Laurent39e94f82010-07-28 01:32:47 -07001856 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001857}
1858
Eric Laurentde070132010-07-13 04:45:46 -07001859uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1860{
Dima Zavinfce7a472011-04-19 22:30:36 -07001861 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001862 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001863 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1864 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001865 }
1866 for (size_t i = 0; i < mTracks.size(); i++) {
1867 sp<Track> track = mTracks[i];
1868 if (sessionId == track->sessionId() &&
1869 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001870 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07001871 }
1872 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001873 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001874}
1875
Mathias Agopian65ab4712010-07-14 17:59:35 -07001876
Glenn Kastenaed850d2012-01-26 09:46:34 -08001877AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001878{
1879 Mutex::Autolock _l(mLock);
1880 return mOutput;
1881}
1882
1883AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1884{
1885 Mutex::Autolock _l(mLock);
1886 AudioStreamOut *output = mOutput;
1887 mOutput = NULL;
1888 return output;
1889}
1890
1891// this method must always be called either with ThreadBase mLock held or inside the thread loop
1892audio_stream_t* AudioFlinger::PlaybackThread::stream()
1893{
1894 if (mOutput == NULL) {
1895 return NULL;
1896 }
1897 return &mOutput->stream->common;
1898}
1899
Eric Laurent162b40b2011-12-05 09:47:19 -08001900uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1901{
1902 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1903 // decoding and transfer time. So sleeping for half of the latency would likely cause
1904 // underruns
1905 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1906 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1907 } else {
1908 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1909 }
1910}
1911
Mathias Agopian65ab4712010-07-14 17:59:35 -07001912// ----------------------------------------------------------------------------
1913
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001914AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001915 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001916 : PlaybackThread(audioFlinger, output, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001917 mAudioMixer(new AudioMixer(mFrameCount, mSampleRate)),
1918 mPrevMixerStatus(MIXER_IDLE)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001919{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001920 // FIXME - Current mixer implementation only supports stereo output
1921 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001922 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001923 }
1924}
1925
1926AudioFlinger::MixerThread::~MixerThread()
1927{
1928 delete mAudioMixer;
1929}
1930
Glenn Kasten83efdd02012-02-24 07:21:32 -08001931class CpuStats {
1932public:
1933 void sample();
1934#ifdef DEBUG_CPU_USAGE
1935private:
1936 ThreadCpuUsage mCpu;
1937#endif
1938};
1939
1940void CpuStats::sample() {
1941#ifdef DEBUG_CPU_USAGE
1942 const CentralTendencyStatistics& stats = mCpu.statistics();
1943 mCpu.sampleAndEnable();
1944 unsigned n = stats.n();
1945 // mCpu.elapsed() is expensive, so don't call it every loop
1946 if ((n & 127) == 1) {
1947 long long elapsed = mCpu.elapsed();
1948 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1949 double perLoop = elapsed / (double) n;
1950 double perLoop100 = perLoop * 0.01;
1951 double mean = stats.mean();
1952 double stddev = stats.stddev();
1953 double minimum = stats.minimum();
1954 double maximum = stats.maximum();
1955 mCpu.resetStatistics();
1956 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",
1957 elapsed * .000000001, n, perLoop * .000001,
1958 mean * .001,
1959 stddev * .001,
1960 minimum * .001,
1961 maximum * .001,
1962 mean / perLoop100,
1963 stddev / perLoop100,
1964 minimum / perLoop100,
1965 maximum / perLoop100);
1966 }
1967 }
1968#endif
1969};
1970
Glenn Kasten37d825e2012-02-24 07:21:48 -08001971void AudioFlinger::PlaybackThread::checkSilentMode_l()
1972{
1973 if (!mMasterMute) {
1974 char value[PROPERTY_VALUE_MAX];
1975 if (property_get("ro.audio.silent", value, "0") > 0) {
1976 char *endptr;
1977 unsigned long ul = strtoul(value, &endptr, 0);
1978 if (*endptr == '\0' && ul != 0) {
1979 ALOGD("Silence is golden");
1980 // The setprop command will not allow a property to be changed after
1981 // the first time it is set, so we don't have to worry about un-muting.
1982 setMasterMute_l(true);
1983 }
1984 }
1985 }
1986}
1987
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988bool AudioFlinger::MixerThread::threadLoop()
1989{
1990 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08001991 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992 nsecs_t standbyTime = systemTime();
1993 size_t mixBufferSize = mFrameCount * mFrameSize;
1994 // FIXME: Relaxed timing because of a certain device that can't meet latency
1995 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001996 // increase threshold again due to low power audio mode. The way this warning threshold is
1997 // calculated and its usefulness should be reconsidered anyway.
1998 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001999 nsecs_t lastWarning = 0;
2000 bool longStandbyExit = false;
2001 uint32_t activeSleepTime = activeSleepTimeUs();
2002 uint32_t idleSleepTime = idleSleepTimeUs();
2003 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08002004 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002005 Vector< sp<EffectChain> > effectChains;
Glenn Kasten83efdd02012-02-24 07:21:32 -08002006 CpuStats cpuStats;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002007
Eric Laurentfeb0db62011-07-22 09:04:31 -07002008 acquireWakeLock();
2009
Mathias Agopian65ab4712010-07-14 17:59:35 -07002010 while (!exitPending())
2011 {
Glenn Kasten83efdd02012-02-24 07:21:32 -08002012 cpuStats.sample();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002013 processConfigEvents();
2014
2015 mixerStatus = MIXER_IDLE;
2016 { // scope for mLock
2017
2018 Mutex::Autolock _l(mLock);
2019
2020 if (checkForNewParameters_l()) {
2021 mixBufferSize = mFrameCount * mFrameSize;
2022 // FIXME: Relaxed timing because of a certain device that can't meet latency
2023 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07002024 // increase threshold again due to low power audio mode. The way this warning
2025 // threshold is calculated and its usefulness should be reconsidered anyway.
2026 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002027 activeSleepTime = activeSleepTimeUs();
2028 idleSleepTime = idleSleepTimeUs();
2029 }
2030
2031 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2032
2033 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002034 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2035 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002036 if (!mStandby) {
Glenn Kasten90bebef2012-01-27 15:24:38 -08002037 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07002038 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002039 mStandby = true;
2040 mBytesWritten = 0;
2041 }
2042
2043 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2044 // we're about to wait, flush the binder command buffer
2045 IPCThreadState::self()->flushCommands();
2046
2047 if (exitPending()) break;
2048
Eric Laurentfeb0db62011-07-22 09:04:31 -07002049 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002050 // wait until we have something to do...
Glenn Kasten90bebef2012-01-27 15:24:38 -08002051 ALOGV("MixerThread %p TID %d going to sleep", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002052 mWaitWorkCV.wait(mLock);
Glenn Kasten90bebef2012-01-27 15:24:38 -08002053 ALOGV("MixerThread %p TID %d waking up", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002054 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002055
Eric Laurent27741442012-01-17 19:20:12 -08002056 mPrevMixerStatus = MIXER_IDLE;
Glenn Kasten37d825e2012-02-24 07:21:48 -08002057 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002058
John Grossman4ff14ba2012-02-08 16:37:41 -08002059 standbyTime = systemTime() + mStandbyTimeInNsecs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002060 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08002061 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002062 continue;
2063 }
2064 }
2065
2066 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
2067
2068 // prevent any changes in effect chain list and in each effect chain
2069 // during mixing and effect process as the audio buffers could be deleted
2070 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002071 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002072 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002073
Glenn Kastenf6b16782011-12-15 09:51:17 -08002074 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08002075 // obtain the presentation timestamp of the next output buffer
2076 int64_t pts;
2077 status_t status = INVALID_OPERATION;
2078
2079 if (NULL != mOutput->stream->get_next_write_timestamp) {
2080 status = mOutput->stream->get_next_write_timestamp(
2081 mOutput->stream, &pts);
2082 }
2083
2084 if (status != NO_ERROR) {
2085 pts = AudioBufferProvider::kInvalidPTS;
2086 }
2087
Mathias Agopian65ab4712010-07-14 17:59:35 -07002088 // mix buffers...
John Grossman4ff14ba2012-02-08 16:37:41 -08002089 mAudioMixer->process(pts);
Eric Laurent21e4b6e2012-01-23 18:56:59 -08002090 // increase sleep time progressively when application underrun condition clears.
2091 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2092 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2093 // such that we would underrun the audio HAL.
2094 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08002095 sleepTimeShift--;
2096 }
Eric Laurent21e4b6e2012-01-23 18:56:59 -08002097 sleepTime = 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08002098 standbyTime = systemTime() + mStandbyTimeInNsecs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002099 //TODO: delay standby when effects have a tail
2100 } else {
2101 // If no tracks are ready, sleep once for the duration of an output
2102 // buffer size, then write 0s to the output
2103 if (sleepTime == 0) {
2104 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08002105 sleepTime = activeSleepTime >> sleepTimeShift;
2106 if (sleepTime < kMinThreadSleepTimeUs) {
2107 sleepTime = kMinThreadSleepTimeUs;
2108 }
2109 // reduce sleep time in case of consecutive application underruns to avoid
2110 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2111 // duration we would end up writing less data than needed by the audio HAL if
2112 // the condition persists.
2113 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2114 sleepTimeShift++;
2115 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002116 } else {
2117 sleepTime = idleSleepTime;
2118 }
2119 } else if (mBytesWritten != 0 ||
2120 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2121 memset (mMixBuffer, 0, mixBufferSize);
2122 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01002123 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002124 }
2125 // TODO add standby time extension fct of effect tail
2126 }
2127
2128 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002129 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002130 }
2131 // sleepTime == 0 means we must write to audio hardware
2132 if (sleepTime == 0) {
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002133 for (size_t i = 0; i < effectChains.size(); i ++) {
2134 effectChains[i]->process_l();
2135 }
2136 // enable changes in effect chain
2137 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002138 mLastWriteTime = systemTime();
2139 mInWrite = true;
2140 mBytesWritten += mixBufferSize;
2141
Dima Zavin799a70e2011-04-18 16:57:27 -07002142 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002143 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2144 mNumWrites++;
2145 mInWrite = false;
2146 nsecs_t now = systemTime();
2147 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002148 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002149 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002150 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002151 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002152 ns2ms(delta), mNumDelayedWrites, this);
2153 lastWarning = now;
2154 }
2155 if (mStandby) {
2156 longStandbyExit = true;
2157 }
2158 }
2159 mStandby = false;
2160 } else {
2161 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002162 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002163 usleep(sleepTime);
2164 }
2165
2166 // finally let go of all our tracks, without the lock held
2167 // since we can't guarantee the destructors won't acquire that
2168 // same lock.
2169 tracksToRemove.clear();
2170
2171 // Effect chains will be actually deleted here if they were removed from
2172 // mEffectChains list during mixing or effects processing
2173 effectChains.clear();
2174 }
2175
2176 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002177 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002178 }
2179
Eric Laurentfeb0db62011-07-22 09:04:31 -07002180 releaseWakeLock();
2181
Steve Block3856b092011-10-20 11:56:00 +01002182 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002183 return false;
2184}
2185
2186// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002187AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2188 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002189{
2190
Glenn Kasten29c23c32012-01-26 13:37:52 -08002191 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002192 // find out which tracks need to be processed
2193 size_t count = activeTracks.size();
2194 size_t mixedTracks = 0;
2195 size_t tracksWithEffect = 0;
2196
2197 float masterVolume = mMasterVolume;
2198 bool masterMute = mMasterMute;
2199
Eric Laurent571d49c2010-08-11 05:20:11 -07002200 if (masterMute) {
2201 masterVolume = 0;
2202 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002203 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002204 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002205 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002206 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002207 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002208 masterVolume = (float)((v + (1 << 23)) >> 24);
2209 chain.clear();
2210 }
2211
2212 for (size_t i=0 ; i<count ; i++) {
2213 sp<Track> t = activeTracks[i].promote();
2214 if (t == 0) continue;
2215
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002216 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002217 Track* const track = t.get();
2218 audio_track_cblk_t* cblk = track->cblk();
2219
2220 // The first time a track is added we wait
2221 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002222 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002223 // make sure that we have enough frames to mix one full buffer.
2224 // enforce this condition only once to enable draining the buffer in case the client
2225 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002226 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002227 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002228 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002229 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002230 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002231 if (t->sampleRate() == (int)mSampleRate) {
2232 minFrames = mFrameCount;
2233 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002234 // +1 for rounding and +1 for additional sample needed for interpolation
2235 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2236 // add frames already consumed but not yet released by the resampler
2237 // because cblk->framesReady() will include these frames
2238 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2239 // the minimum track buffer size is normally twice the number of frames necessary
2240 // to fill one buffer and the resampler should not leave more than one buffer worth
2241 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002242 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002243 }
2244 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002245 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002246 !track->isPaused() && !track->isTerminated())
2247 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002248 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002249
2250 mixedTracks++;
2251
2252 // track->mainBuffer() != mMixBuffer means there is an effect chain
2253 // connected to the track
2254 chain.clear();
2255 if (track->mainBuffer() != mMixBuffer) {
2256 chain = getEffectChain_l(track->sessionId());
2257 // Delegate volume control to effect in track effect chain if needed
2258 if (chain != 0) {
2259 tracksWithEffect++;
2260 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002261 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002262 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002263 }
2264 }
2265
2266
2267 int param = AudioMixer::VOLUME;
2268 if (track->mFillingUpStatus == Track::FS_FILLED) {
2269 // no ramp for the first volume setting
2270 track->mFillingUpStatus = Track::FS_ACTIVE;
2271 if (track->mState == TrackBase::RESUMING) {
2272 track->mState = TrackBase::ACTIVE;
2273 param = AudioMixer::RAMP_VOLUME;
2274 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002275 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002276 } else if (cblk->server != 0) {
2277 // If the track is stopped before the first frame was mixed,
2278 // do not apply ramp
2279 param = AudioMixer::RAMP_VOLUME;
2280 }
2281
2282 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002283 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002284 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002285 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002286 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002287 if (track->isPausing()) {
2288 track->setPaused();
2289 }
2290 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002291
Mathias Agopian65ab4712010-07-14 17:59:35 -07002292 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002293 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002294 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002295 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002296 vl = vlr & 0xFFFF;
2297 vr = vlr >> 16;
2298 // track volumes come from shared memory, so can't be trusted and must be clamped
2299 if (vl > MAX_GAIN_INT) {
2300 ALOGV("Track left volume out of range: %04X", vl);
2301 vl = MAX_GAIN_INT;
2302 }
2303 if (vr > MAX_GAIN_INT) {
2304 ALOGV("Track right volume out of range: %04X", vr);
2305 vr = MAX_GAIN_INT;
2306 }
2307 // now apply the master volume and stream type volume
2308 vl = (uint32_t)(v * vl) << 12;
2309 vr = (uint32_t)(v * vr) << 12;
2310 // assuming master volume and stream type volume each go up to 1.0,
2311 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002312
Glenn Kasten05632a52012-01-03 14:22:33 -08002313 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2314 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002315 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002316 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002317 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002318 }
2319 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002320 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002321 // Delegate volume control to effect in track effect chain if needed
2322 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2323 // Do not ramp volume if volume is controlled by effect
2324 param = AudioMixer::VOLUME;
2325 track->mHasVolumeController = true;
2326 } else {
2327 // force no volume ramp when volume controller was just disabled or removed
2328 // from effect chain to avoid volume spike
2329 if (track->mHasVolumeController) {
2330 param = AudioMixer::VOLUME;
2331 }
2332 track->mHasVolumeController = false;
2333 }
2334
2335 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002336 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002337 vl = (vl + (1 << 11)) >> 12;
2338 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2339 vr = (vr + (1 << 11)) >> 12;
2340 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002341
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002342 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 -07002343
Mathias Agopian65ab4712010-07-14 17:59:35 -07002344 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002345 mAudioMixer->setBufferProvider(name, track);
2346 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002347
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002348 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2349 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2350 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002351 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002352 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002353 AudioMixer::TRACK,
2354 AudioMixer::FORMAT, (void *)track->format());
2355 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002356 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002357 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002358 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002359 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002360 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002361 AudioMixer::RESAMPLE,
2362 AudioMixer::SAMPLE_RATE,
2363 (void *)(cblk->sampleRate));
2364 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002365 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002366 AudioMixer::TRACK,
2367 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2368 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002369 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002370 AudioMixer::TRACK,
2371 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2372
2373 // reset retry count
2374 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002375 // If one track is ready, set the mixer ready if:
2376 // - the mixer was not ready during previous round OR
2377 // - no other track is not ready
2378 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2379 mixerStatus != MIXER_TRACKS_ENABLED) {
2380 mixerStatus = MIXER_TRACKS_READY;
2381 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002382 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002383 //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 -07002384 if (track->isStopped()) {
2385 track->reset();
2386 }
2387 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2388 // We have consumed all the buffers of this track.
2389 // Remove it from the list of active tracks.
2390 tracksToRemove->add(track);
2391 } else {
2392 // No buffers for this track. Give it a few chances to
2393 // fill a buffer, then remove it from active list.
2394 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002395 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002396 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002397 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002398 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002399 // If one track is not ready, mark the mixer also not ready if:
2400 // - the mixer was ready during previous round OR
2401 // - no other track is ready
2402 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2403 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002404 mixerStatus = MIXER_TRACKS_ENABLED;
2405 }
2406 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002407 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002408 }
2409 }
2410
2411 // remove all the tracks that need to be...
2412 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002413 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002414 for (size_t i=0 ; i<count ; i++) {
2415 const sp<Track>& track = tracksToRemove->itemAt(i);
2416 mActiveTracks.remove(track);
2417 if (track->mainBuffer() != mMixBuffer) {
2418 chain = getEffectChain_l(track->sessionId());
2419 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002420 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002421 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002422 }
2423 }
2424 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002425 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002426 }
2427 }
2428 }
2429
2430 // mix buffer must be cleared if all tracks are connected to an
2431 // effect chain as in this case the mixer will not write to
2432 // mix buffer and track effects will accumulate into it
2433 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2434 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2435 }
2436
Eric Laurent27741442012-01-17 19:20:12 -08002437 mPrevMixerStatus = mixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002438 return mixerStatus;
2439}
2440
Glenn Kastenfff6d712012-01-12 16:38:12 -08002441void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002442{
Steve Block3856b092011-10-20 11:56:00 +01002443 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002444 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002445 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002446
Mathias Agopian65ab4712010-07-14 17:59:35 -07002447 size_t size = mTracks.size();
2448 for (size_t i = 0; i < size; i++) {
2449 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08002450 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002451 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002452 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002453 }
2454 }
2455}
2456
Glenn Kastenfff6d712012-01-12 16:38:12 -08002457void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002458{
Steve Block3856b092011-10-20 11:56:00 +01002459 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002460 this, streamType, valid);
2461 Mutex::Autolock _l(mLock);
2462
2463 mStreamTypes[streamType].valid = valid;
2464}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002465
2466// getTrackName_l() must be called with ThreadBase::mLock held
2467int AudioFlinger::MixerThread::getTrackName_l()
2468{
2469 return mAudioMixer->getTrackName();
2470}
2471
2472// deleteTrackName_l() must be called with ThreadBase::mLock held
2473void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2474{
Steve Block3856b092011-10-20 11:56:00 +01002475 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002476 mAudioMixer->deleteTrackName(name);
2477}
2478
2479// checkForNewParameters_l() must be called with ThreadBase::mLock held
2480bool AudioFlinger::MixerThread::checkForNewParameters_l()
2481{
2482 bool reconfig = false;
2483
2484 while (!mNewParameters.isEmpty()) {
2485 status_t status = NO_ERROR;
2486 String8 keyValuePair = mNewParameters[0];
2487 AudioParameter param = AudioParameter(keyValuePair);
2488 int value;
2489
2490 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2491 reconfig = true;
2492 }
2493 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002494 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002495 status = BAD_VALUE;
2496 } else {
2497 reconfig = true;
2498 }
2499 }
2500 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002501 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002502 status = BAD_VALUE;
2503 } else {
2504 reconfig = true;
2505 }
2506 }
2507 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2508 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002509 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002510 // if frame count is changed after track creation
2511 if (!mTracks.isEmpty()) {
2512 status = INVALID_OPERATION;
2513 } else {
2514 reconfig = true;
2515 }
2516 }
2517 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002518 // when changing the audio output device, call addBatteryData to notify
2519 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002520 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002521 uint32_t params = 0;
2522 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002523 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002524 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2525 }
2526
2527 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002528 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002529 // check if any other device (except speaker) is on
2530 if (value & deviceWithoutSpeaker ) {
2531 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2532 }
2533
2534 if (params != 0) {
2535 addBatteryData(params);
2536 }
2537 }
2538
Mathias Agopian65ab4712010-07-14 17:59:35 -07002539 // forward device change to effects that have requested to be
2540 // aware of attached audio device.
2541 mDevice = (uint32_t)value;
2542 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002543 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002544 }
2545 }
2546
2547 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002548 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002549 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002550 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002551 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002552 mStandby = true;
2553 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002554 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002555 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002556 }
2557 if (status == NO_ERROR && reconfig) {
2558 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002559 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2560 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002561 readOutputParameters();
2562 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2563 for (size_t i = 0; i < mTracks.size() ; i++) {
2564 int name = getTrackName_l();
2565 if (name < 0) break;
2566 mTracks[i]->mName = name;
2567 // limit track sample rate to 2 x new output sample rate
2568 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2569 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2570 }
2571 }
2572 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2573 }
2574 }
2575
2576 mNewParameters.removeAt(0);
2577
2578 mParamStatus = status;
2579 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002580 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2581 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002582 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002583 }
2584 return reconfig;
2585}
2586
2587status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2588{
2589 const size_t SIZE = 256;
2590 char buffer[SIZE];
2591 String8 result;
2592
2593 PlaybackThread::dumpInternals(fd, args);
2594
2595 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2596 result.append(buffer);
2597 write(fd, result.string(), result.size());
2598 return NO_ERROR;
2599}
2600
Mathias Agopian65ab4712010-07-14 17:59:35 -07002601uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2602{
Eric Laurent60e18242010-07-29 06:50:24 -07002603 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002604}
2605
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002606uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2607{
2608 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2609}
2610
Mathias Agopian65ab4712010-07-14 17:59:35 -07002611// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002612AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2613 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002614 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002615 // mLeftVolFloat, mRightVolFloat
2616 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002617{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002618}
2619
2620AudioFlinger::DirectOutputThread::~DirectOutputThread()
2621{
2622}
2623
Mathias Agopian65ab4712010-07-14 17:59:35 -07002624void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2625{
2626 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002627 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002628 return;
2629 }
2630
2631 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002632 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002633 size_t count = mFrameCount * mChannelCount;
2634 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2635 int16_t *dst = mMixBuffer + count-1;
2636 while(count--) {
2637 *dst-- = (int16_t)(*src--^0x80) << 8;
2638 }
2639 }
2640
2641 size_t frameCount = mFrameCount;
2642 int16_t *out = mMixBuffer;
2643 if (ramp) {
2644 if (mChannelCount == 1) {
2645 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2646 int32_t vlInc = d / (int32_t)frameCount;
2647 int32_t vl = ((int32_t)mLeftVolShort << 16);
2648 do {
2649 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2650 out++;
2651 vl += vlInc;
2652 } while (--frameCount);
2653
2654 } else {
2655 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2656 int32_t vlInc = d / (int32_t)frameCount;
2657 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2658 int32_t vrInc = d / (int32_t)frameCount;
2659 int32_t vl = ((int32_t)mLeftVolShort << 16);
2660 int32_t vr = ((int32_t)mRightVolShort << 16);
2661 do {
2662 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2663 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2664 out += 2;
2665 vl += vlInc;
2666 vr += vrInc;
2667 } while (--frameCount);
2668 }
2669 } else {
2670 if (mChannelCount == 1) {
2671 do {
2672 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2673 out++;
2674 } while (--frameCount);
2675 } else {
2676 do {
2677 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2678 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2679 out += 2;
2680 } while (--frameCount);
2681 }
2682 }
2683
2684 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002685 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002686 size_t count = mFrameCount * mChannelCount;
2687 int16_t *src = mMixBuffer;
2688 uint8_t *dst = (uint8_t *)mMixBuffer;
2689 while(count--) {
2690 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2691 }
2692 }
2693
2694 mLeftVolShort = leftVol;
2695 mRightVolShort = rightVol;
2696}
2697
2698bool AudioFlinger::DirectOutputThread::threadLoop()
2699{
Glenn Kasten29c23c32012-01-26 13:37:52 -08002700 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002701 sp<Track> trackToRemove;
2702 sp<Track> activeTrack;
2703 nsecs_t standbyTime = systemTime();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002704 size_t mixBufferSize = mFrameCount*mFrameSize;
2705 uint32_t activeSleepTime = activeSleepTimeUs();
2706 uint32_t idleSleepTime = idleSleepTimeUs();
2707 uint32_t sleepTime = idleSleepTime;
2708 // use shorter standby delay as on normal output to release
2709 // hardware resources as soon as possible
2710 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2711
Eric Laurentfeb0db62011-07-22 09:04:31 -07002712 acquireWakeLock();
2713
Mathias Agopian65ab4712010-07-14 17:59:35 -07002714 while (!exitPending())
2715 {
2716 bool rampVolume;
2717 uint16_t leftVol;
2718 uint16_t rightVol;
2719 Vector< sp<EffectChain> > effectChains;
2720
2721 processConfigEvents();
2722
2723 mixerStatus = MIXER_IDLE;
2724
2725 { // scope for the mLock
2726
2727 Mutex::Autolock _l(mLock);
2728
2729 if (checkForNewParameters_l()) {
2730 mixBufferSize = mFrameCount*mFrameSize;
2731 activeSleepTime = activeSleepTimeUs();
2732 idleSleepTime = idleSleepTimeUs();
2733 standbyDelay = microseconds(activeSleepTime*2);
2734 }
2735
2736 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002737 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2738 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002739 // wait until we have something to do...
2740 if (!mStandby) {
Glenn Kasten90bebef2012-01-27 15:24:38 -08002741 ALOGV("Audio hardware entering standby, mixer %p", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002742 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002743 mStandby = true;
2744 mBytesWritten = 0;
2745 }
2746
2747 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2748 // we're about to wait, flush the binder command buffer
2749 IPCThreadState::self()->flushCommands();
2750
2751 if (exitPending()) break;
2752
Eric Laurentfeb0db62011-07-22 09:04:31 -07002753 releaseWakeLock_l();
Glenn Kasten90bebef2012-01-27 15:24:38 -08002754 ALOGV("DirectOutputThread %p TID %d going to sleep", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002755 mWaitWorkCV.wait(mLock);
Glenn Kasten90bebef2012-01-27 15:24:38 -08002756 ALOGV("DirectOutputThread %p TID %d waking up in active mode", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002757 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002758
Glenn Kasten37d825e2012-02-24 07:21:48 -08002759 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002760
2761 standbyTime = systemTime() + standbyDelay;
2762 sleepTime = idleSleepTime;
2763 continue;
2764 }
2765 }
2766
2767 effectChains = mEffectChains;
2768
2769 // find out which tracks need to be processed
2770 if (mActiveTracks.size() != 0) {
2771 sp<Track> t = mActiveTracks[0].promote();
2772 if (t == 0) continue;
2773
2774 Track* const track = t.get();
2775 audio_track_cblk_t* cblk = track->cblk();
2776
2777 // The first time a track is added we wait
2778 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002779 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002780 !track->isPaused() && !track->isTerminated())
2781 {
Steve Block3856b092011-10-20 11:56:00 +01002782 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002783
2784 if (track->mFillingUpStatus == Track::FS_FILLED) {
2785 track->mFillingUpStatus = Track::FS_ACTIVE;
2786 mLeftVolFloat = mRightVolFloat = 0;
2787 mLeftVolShort = mRightVolShort = 0;
2788 if (track->mState == TrackBase::RESUMING) {
2789 track->mState = TrackBase::ACTIVE;
2790 rampVolume = true;
2791 }
2792 } else if (cblk->server != 0) {
2793 // If the track is stopped before the first frame was mixed,
2794 // do not apply ramp
2795 rampVolume = true;
2796 }
2797 // compute volume for this track
2798 float left, right;
2799 if (track->isMuted() || mMasterMute || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002800 mStreamTypes[track->streamType()].mute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002801 left = right = 0;
2802 if (track->isPausing()) {
2803 track->setPaused();
2804 }
2805 } else {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002806 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002807 float v = mMasterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002808 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002809 float v_clamped = v * (vlr & 0xFFFF);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002810 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2811 left = v_clamped/MAX_GAIN;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002812 v_clamped = v * (vlr >> 16);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002813 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2814 right = v_clamped/MAX_GAIN;
2815 }
2816
2817 if (left != mLeftVolFloat || right != mRightVolFloat) {
2818 mLeftVolFloat = left;
2819 mRightVolFloat = right;
2820
2821 // If audio HAL implements volume control,
2822 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002823 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002824 left = 1.0f;
2825 right = 1.0f;
2826 }
2827
2828 // Convert volumes from float to 8.24
2829 uint32_t vl = (uint32_t)(left * (1 << 24));
2830 uint32_t vr = (uint32_t)(right * (1 << 24));
2831
2832 // Delegate volume control to effect in track effect chain if needed
2833 // only one effect chain can be present on DirectOutputThread, so if
2834 // there is one, the track is connected to it
2835 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002836 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002837 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002838 rampVolume = false;
2839 }
2840 }
2841
2842 // Convert volumes from 8.24 to 4.12 format
2843 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2844 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2845 leftVol = (uint16_t)v_clamped;
2846 v_clamped = (vr + (1 << 11)) >> 12;
2847 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2848 rightVol = (uint16_t)v_clamped;
2849 } else {
2850 leftVol = mLeftVolShort;
2851 rightVol = mRightVolShort;
2852 rampVolume = false;
2853 }
2854
2855 // reset retry count
2856 track->mRetryCount = kMaxTrackRetriesDirect;
2857 activeTrack = t;
2858 mixerStatus = MIXER_TRACKS_READY;
2859 } else {
Steve Block3856b092011-10-20 11:56:00 +01002860 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002861 if (track->isStopped()) {
2862 track->reset();
2863 }
2864 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2865 // We have consumed all the buffers of this track.
2866 // Remove it from the list of active tracks.
2867 trackToRemove = track;
2868 } else {
2869 // No buffers for this track. Give it a few chances to
2870 // fill a buffer, then remove it from active list.
2871 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002872 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002873 trackToRemove = track;
2874 } else {
2875 mixerStatus = MIXER_TRACKS_ENABLED;
2876 }
2877 }
2878 }
2879 }
2880
2881 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002882 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002883 mActiveTracks.remove(trackToRemove);
2884 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002885 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002886 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002887 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002888 }
2889 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002890 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002891 }
2892 }
2893
Eric Laurentde070132010-07-13 04:45:46 -07002894 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002895 }
2896
Glenn Kastenf6b16782011-12-15 09:51:17 -08002897 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002898 AudioBufferProvider::Buffer buffer;
2899 size_t frameCount = mFrameCount;
Glenn Kastena1117922012-01-26 10:53:32 -08002900 int8_t *curBuf = (int8_t *)mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002901 // output audio to hardware
2902 while (frameCount) {
2903 buffer.frameCount = frameCount;
John Grossman4ff14ba2012-02-08 16:37:41 -08002904 activeTrack->getNextBuffer(&buffer,
2905 AudioBufferProvider::kInvalidPTS);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002906 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002907 memset(curBuf, 0, frameCount * mFrameSize);
2908 break;
2909 }
2910 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2911 frameCount -= buffer.frameCount;
2912 curBuf += buffer.frameCount * mFrameSize;
2913 activeTrack->releaseBuffer(&buffer);
2914 }
2915 sleepTime = 0;
2916 standbyTime = systemTime() + standbyDelay;
2917 } else {
2918 if (sleepTime == 0) {
2919 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2920 sleepTime = activeSleepTime;
2921 } else {
2922 sleepTime = idleSleepTime;
2923 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002924 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002925 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2926 sleepTime = 0;
2927 }
2928 }
2929
2930 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002931 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002932 }
2933 // sleepTime == 0 means we must write to audio hardware
2934 if (sleepTime == 0) {
2935 if (mixerStatus == MIXER_TRACKS_READY) {
2936 applyVolume(leftVol, rightVol, rampVolume);
2937 }
2938 for (size_t i = 0; i < effectChains.size(); i ++) {
2939 effectChains[i]->process_l();
2940 }
Eric Laurentde070132010-07-13 04:45:46 -07002941 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002942
2943 mLastWriteTime = systemTime();
2944 mInWrite = true;
2945 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002946 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002947 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2948 mNumWrites++;
2949 mInWrite = false;
2950 mStandby = false;
2951 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002952 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002953 usleep(sleepTime);
2954 }
2955
2956 // finally let go of removed track, without the lock held
2957 // since we can't guarantee the destructors won't acquire that
2958 // same lock.
2959 trackToRemove.clear();
2960 activeTrack.clear();
2961
2962 // Effect chains will be actually deleted here if they were removed from
2963 // mEffectChains list during mixing or effects processing
2964 effectChains.clear();
2965 }
2966
2967 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002968 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002969 }
2970
Eric Laurentfeb0db62011-07-22 09:04:31 -07002971 releaseWakeLock();
2972
Steve Block3856b092011-10-20 11:56:00 +01002973 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002974 return false;
2975}
2976
2977// getTrackName_l() must be called with ThreadBase::mLock held
2978int AudioFlinger::DirectOutputThread::getTrackName_l()
2979{
2980 return 0;
2981}
2982
2983// deleteTrackName_l() must be called with ThreadBase::mLock held
2984void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2985{
2986}
2987
2988// checkForNewParameters_l() must be called with ThreadBase::mLock held
2989bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2990{
2991 bool reconfig = false;
2992
2993 while (!mNewParameters.isEmpty()) {
2994 status_t status = NO_ERROR;
2995 String8 keyValuePair = mNewParameters[0];
2996 AudioParameter param = AudioParameter(keyValuePair);
2997 int value;
2998
2999 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3000 // do not accept frame count changes if tracks are open as the track buffer
3001 // size depends on frame count and correct behavior would not be garantied
3002 // if frame count is changed after track creation
3003 if (!mTracks.isEmpty()) {
3004 status = INVALID_OPERATION;
3005 } else {
3006 reconfig = true;
3007 }
3008 }
3009 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003010 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003011 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003012 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003013 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003014 mStandby = true;
3015 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07003016 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003017 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003018 }
3019 if (status == NO_ERROR && reconfig) {
3020 readOutputParameters();
3021 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3022 }
3023 }
3024
3025 mNewParameters.removeAt(0);
3026
3027 mParamStatus = status;
3028 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003029 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3030 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003031 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003032 }
3033 return reconfig;
3034}
3035
3036uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
3037{
3038 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003039 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003040 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003041 } else {
3042 time = 10000;
3043 }
3044 return time;
3045}
3046
3047uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
3048{
3049 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003050 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003051 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003052 } else {
3053 time = 10000;
3054 }
3055 return time;
3056}
3057
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003058uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
3059{
3060 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003061 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003062 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3063 } else {
3064 time = 10000;
3065 }
3066 return time;
3067}
3068
3069
Mathias Agopian65ab4712010-07-14 17:59:35 -07003070// ----------------------------------------------------------------------------
3071
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003072AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003073 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003074 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3075 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003076{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003077 addOutputTrack(mainThread);
3078}
3079
3080AudioFlinger::DuplicatingThread::~DuplicatingThread()
3081{
3082 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3083 mOutputTracks[i]->destroy();
3084 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003085}
3086
3087bool AudioFlinger::DuplicatingThread::threadLoop()
3088{
3089 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08003090 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003091 nsecs_t standbyTime = systemTime();
3092 size_t mixBufferSize = mFrameCount*mFrameSize;
3093 SortedVector< sp<OutputTrack> > outputTracks;
3094 uint32_t writeFrames = 0;
3095 uint32_t activeSleepTime = activeSleepTimeUs();
3096 uint32_t idleSleepTime = idleSleepTimeUs();
3097 uint32_t sleepTime = idleSleepTime;
3098 Vector< sp<EffectChain> > effectChains;
3099
Eric Laurentfeb0db62011-07-22 09:04:31 -07003100 acquireWakeLock();
3101
Mathias Agopian65ab4712010-07-14 17:59:35 -07003102 while (!exitPending())
3103 {
3104 processConfigEvents();
3105
3106 mixerStatus = MIXER_IDLE;
3107 { // scope for the mLock
3108
3109 Mutex::Autolock _l(mLock);
3110
3111 if (checkForNewParameters_l()) {
3112 mixBufferSize = mFrameCount*mFrameSize;
3113 updateWaitTime();
3114 activeSleepTime = activeSleepTimeUs();
3115 idleSleepTime = idleSleepTimeUs();
3116 }
3117
3118 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3119
3120 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3121 outputTracks.add(mOutputTracks[i]);
3122 }
3123
3124 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08003125 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3126 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003127 if (!mStandby) {
3128 for (size_t i = 0; i < outputTracks.size(); i++) {
3129 outputTracks[i]->stop();
3130 }
3131 mStandby = true;
3132 mBytesWritten = 0;
3133 }
3134
3135 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3136 // we're about to wait, flush the binder command buffer
3137 IPCThreadState::self()->flushCommands();
3138 outputTracks.clear();
3139
3140 if (exitPending()) break;
3141
Eric Laurentfeb0db62011-07-22 09:04:31 -07003142 releaseWakeLock_l();
Glenn Kasten90bebef2012-01-27 15:24:38 -08003143 ALOGV("DuplicatingThread %p TID %d going to sleep", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003144 mWaitWorkCV.wait(mLock);
Glenn Kasten90bebef2012-01-27 15:24:38 -08003145 ALOGV("DuplicatingThread %p TID %d waking up", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003146 acquireWakeLock_l();
3147
Glenn Kasten37d825e2012-02-24 07:21:48 -08003148 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003149
John Grossman4ff14ba2012-02-08 16:37:41 -08003150 standbyTime = systemTime() + mStandbyTimeInNsecs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003151 sleepTime = idleSleepTime;
3152 continue;
3153 }
3154 }
3155
3156 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3157
3158 // prevent any changes in effect chain list and in each effect chain
3159 // during mixing and effect process as the audio buffers could be deleted
3160 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003161 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003162 }
3163
Glenn Kastenf6b16782011-12-15 09:51:17 -08003164 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003165 // mix buffers...
3166 if (outputsReady(outputTracks)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08003167 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003168 } else {
3169 memset(mMixBuffer, 0, mixBufferSize);
3170 }
3171 sleepTime = 0;
3172 writeFrames = mFrameCount;
3173 } else {
3174 if (sleepTime == 0) {
3175 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3176 sleepTime = activeSleepTime;
3177 } else {
3178 sleepTime = idleSleepTime;
3179 }
3180 } else if (mBytesWritten != 0) {
3181 // flush remaining overflow buffers in output tracks
3182 for (size_t i = 0; i < outputTracks.size(); i++) {
3183 if (outputTracks[i]->isActive()) {
3184 sleepTime = 0;
3185 writeFrames = 0;
3186 memset(mMixBuffer, 0, mixBufferSize);
3187 break;
3188 }
3189 }
3190 }
3191 }
3192
3193 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003194 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003195 }
3196 // sleepTime == 0 means we must write to audio hardware
3197 if (sleepTime == 0) {
3198 for (size_t i = 0; i < effectChains.size(); i ++) {
3199 effectChains[i]->process_l();
3200 }
3201 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003202 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003203
John Grossman4ff14ba2012-02-08 16:37:41 -08003204 standbyTime = systemTime() + mStandbyTimeInNsecs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003205 for (size_t i = 0; i < outputTracks.size(); i++) {
3206 outputTracks[i]->write(mMixBuffer, writeFrames);
3207 }
3208 mStandby = false;
3209 mBytesWritten += mixBufferSize;
3210 } else {
3211 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003212 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003213 usleep(sleepTime);
3214 }
3215
3216 // finally let go of all our tracks, without the lock held
3217 // since we can't guarantee the destructors won't acquire that
3218 // same lock.
3219 tracksToRemove.clear();
3220 outputTracks.clear();
3221
3222 // Effect chains will be actually deleted here if they were removed from
3223 // mEffectChains list during mixing or effects processing
3224 effectChains.clear();
3225 }
3226
Eric Laurentfeb0db62011-07-22 09:04:31 -07003227 releaseWakeLock();
3228
Mathias Agopian65ab4712010-07-14 17:59:35 -07003229 return false;
3230}
3231
3232void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3233{
Glenn Kasten99e53b82012-01-19 08:59:58 -08003234 // FIXME explain this formula
Mathias Agopian65ab4712010-07-14 17:59:35 -07003235 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003236 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003237 this,
3238 mSampleRate,
3239 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003240 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003241 frameCount);
3242 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003243 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003244 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003245 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003246 updateWaitTime();
3247 }
3248}
3249
3250void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3251{
3252 Mutex::Autolock _l(mLock);
3253 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003254 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003255 mOutputTracks[i]->destroy();
3256 mOutputTracks.removeAt(i);
3257 updateWaitTime();
3258 return;
3259 }
3260 }
Steve Block3856b092011-10-20 11:56:00 +01003261 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003262}
3263
3264void AudioFlinger::DuplicatingThread::updateWaitTime()
3265{
3266 mWaitTimeMs = UINT_MAX;
3267 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3268 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003269 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003270 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3271 if (waitTimeMs < mWaitTimeMs) {
3272 mWaitTimeMs = waitTimeMs;
3273 }
3274 }
3275 }
3276}
3277
3278
3279bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3280{
3281 for (size_t i = 0; i < outputTracks.size(); i++) {
3282 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3283 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003284 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003285 return false;
3286 }
3287 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3288 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003289 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003290 return false;
3291 }
3292 }
3293 return true;
3294}
3295
3296uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3297{
3298 return (mWaitTimeMs * 1000) / 2;
3299}
3300
3301// ----------------------------------------------------------------------------
3302
3303// TrackBase constructor must be called with AudioFlinger::mLock held
3304AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003305 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003306 const sp<Client>& client,
3307 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003308 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003309 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003310 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003311 const sp<IMemory>& sharedBuffer,
3312 int sessionId)
3313 : RefBase(),
3314 mThread(thread),
3315 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003316 mCblk(NULL),
3317 // mBuffer
3318 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003319 mFrameCount(0),
3320 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003321 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003322 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003323 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003324 // mChannelCount
3325 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003326{
Steve Block3856b092011-10-20 11:56:00 +01003327 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003328
Steve Blockb8a80522011-12-20 16:23:08 +00003329 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003330 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003331 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003332 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3333 if (sharedBuffer == 0) {
3334 size += bufferSize;
3335 }
3336
3337 if (client != NULL) {
3338 mCblkMemory = client->heap()->allocate(size);
3339 if (mCblkMemory != 0) {
3340 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003341 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003342 new(mCblk) audio_track_cblk_t();
3343 // clear all buffers
3344 mCblk->frameCount = frameCount;
3345 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003346 mChannelCount = channelCount;
3347 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003348 if (sharedBuffer == 0) {
3349 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3350 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3351 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003352 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003353 mCblk->flags = CBLK_UNDERRUN_ON;
3354 } else {
3355 mBuffer = sharedBuffer->pointer();
3356 }
3357 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3358 }
3359 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003360 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003361 client->heap()->dump("AudioTrack");
3362 return;
3363 }
3364 } else {
3365 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003366 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003367 new(mCblk) audio_track_cblk_t();
3368 // clear all buffers
3369 mCblk->frameCount = frameCount;
3370 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003371 mChannelCount = channelCount;
3372 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003373 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3374 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3375 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003376 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003377 mCblk->flags = CBLK_UNDERRUN_ON;
3378 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003379 }
3380}
3381
3382AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3383{
Glenn Kastena0d68332012-01-27 16:47:15 -08003384 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003385 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003386 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003387 } else {
3388 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003389 }
3390 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003391 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003392 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003393 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003394 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003395 // If the client's reference count drops to zero, the associated destructor
3396 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3397 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003398 mClient.clear();
3399 }
3400}
3401
3402void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3403{
Glenn Kastene0feee32011-12-13 11:53:26 -08003404 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003405 mFrameCount = buffer->frameCount;
3406 step();
3407 buffer->frameCount = 0;
3408}
3409
3410bool AudioFlinger::ThreadBase::TrackBase::step() {
3411 bool result;
3412 audio_track_cblk_t* cblk = this->cblk();
3413
3414 result = cblk->stepServer(mFrameCount);
3415 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003416 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003417 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003418 }
3419 return result;
3420}
3421
3422void AudioFlinger::ThreadBase::TrackBase::reset() {
3423 audio_track_cblk_t* cblk = this->cblk();
3424
3425 cblk->user = 0;
3426 cblk->server = 0;
3427 cblk->userBase = 0;
3428 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003429 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01003430 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003431}
3432
Mathias Agopian65ab4712010-07-14 17:59:35 -07003433int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3434 return (int)mCblk->sampleRate;
3435}
3436
Mathias Agopian65ab4712010-07-14 17:59:35 -07003437void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3438 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003439 size_t frameSize = cblk->frameSize;
3440 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3441 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003442
3443 // Check validity of returned pointer in case the track control block would have been corrupted.
3444 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003445 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003446 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 -07003447 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003448 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003449 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003450 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003451 }
3452
3453 return bufferStart;
3454}
3455
3456// ----------------------------------------------------------------------------
3457
3458// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3459AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003460 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003461 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003462 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003463 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003464 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003465 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003466 int frameCount,
3467 const sp<IMemory>& sharedBuffer,
3468 int sessionId)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003469 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003470 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3471 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003472{
3473 if (mCblk != NULL) {
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003474 if (thread != NULL) {
3475 mName = thread->getTrackName_l();
3476 mMainBuffer = thread->mixBuffer();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003477 }
Glenn Kasten23d82a92012-02-03 11:10:00 -08003478 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003479 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003480 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003481 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003482 mStreamType = streamType;
3483 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3484 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003485 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003486 }
3487}
3488
3489AudioFlinger::PlaybackThread::Track::~Track()
3490{
Steve Block3856b092011-10-20 11:56:00 +01003491 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003492 sp<ThreadBase> thread = mThread.promote();
3493 if (thread != 0) {
3494 Mutex::Autolock _l(thread->mLock);
3495 mState = TERMINATED;
3496 }
3497}
3498
3499void AudioFlinger::PlaybackThread::Track::destroy()
3500{
3501 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3502 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08003503 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003504 // we must acquire a strong reference on this Track before locking mLock
3505 // here so that the destructor is called only when exiting this function.
3506 // On the other hand, as long as Track::destroy() is only called by
3507 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3508 // this Track with its member mTrack.
3509 sp<Track> keep(this);
3510 { // scope for mLock
3511 sp<ThreadBase> thread = mThread.promote();
3512 if (thread != 0) {
3513 if (!isOutputTrack()) {
3514 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08003515 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003516
3517 // to track the speaker usage
3518 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003519 }
3520 AudioSystem::releaseOutput(thread->id());
3521 }
3522 Mutex::Autolock _l(thread->mLock);
3523 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3524 playbackThread->destroyTrack_l(this);
3525 }
3526 }
3527}
3528
3529void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3530{
Glenn Kasten83d86532012-01-17 14:39:34 -08003531 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003532 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 -07003533 mName - AudioMixer::TRACK0,
Glenn Kasten44deb052012-02-05 18:09:08 -08003534 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003535 mStreamType,
3536 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003537 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003538 mSessionId,
3539 mFrameCount,
3540 mState,
3541 mMute,
3542 mFillingUpStatus,
3543 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003544 vlr & 0xFFFF,
3545 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003546 mCblk->server,
3547 mCblk->user,
3548 (int)mMainBuffer,
3549 (int)mAuxBuffer);
3550}
3551
John Grossman4ff14ba2012-02-08 16:37:41 -08003552status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
3553 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003554{
3555 audio_track_cblk_t* cblk = this->cblk();
3556 uint32_t framesReady;
3557 uint32_t framesReq = buffer->frameCount;
3558
3559 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003560 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003561 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003562 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003563 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003564 }
3565
3566 framesReady = cblk->framesReady();
3567
Glenn Kastenf6b16782011-12-15 09:51:17 -08003568 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003569 uint32_t s = cblk->server;
3570 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3571
3572 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3573 if (framesReq > framesReady) {
3574 framesReq = framesReady;
3575 }
3576 if (s + framesReq > bufferEnd) {
3577 framesReq = bufferEnd - s;
3578 }
3579
3580 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003581 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003582
3583 buffer->frameCount = framesReq;
3584 return NO_ERROR;
3585 }
3586
3587getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003588 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003589 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003590 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003591 return NOT_ENOUGH_DATA;
3592}
3593
John Grossman4ff14ba2012-02-08 16:37:41 -08003594uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const{
3595 return mCblk->framesReady();
3596}
3597
Mathias Agopian65ab4712010-07-14 17:59:35 -07003598bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003599 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003600
John Grossman4ff14ba2012-02-08 16:37:41 -08003601 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003602 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3603 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003604 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003605 return true;
3606 }
3607 return false;
3608}
3609
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003610status_t AudioFlinger::PlaybackThread::Track::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003611{
3612 status_t status = NO_ERROR;
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003613 ALOGV("start(%d), calling pid %d session %d tid %d",
3614 mName, IPCThreadState::self()->getCallingPid(), mSessionId, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003615 sp<ThreadBase> thread = mThread.promote();
3616 if (thread != 0) {
3617 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003618 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003619 // here the track could be either new, or restarted
3620 // in both cases "unstop" the track
3621 if (mState == PAUSED) {
3622 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003623 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003624 } else {
3625 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003626 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003627 }
3628
3629 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3630 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003631 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003632 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003633
3634 // to track the speaker usage
3635 if (status == NO_ERROR) {
3636 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3637 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003638 }
3639 if (status == NO_ERROR) {
3640 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3641 playbackThread->addTrack_l(this);
3642 } else {
3643 mState = state;
3644 }
3645 } else {
3646 status = BAD_VALUE;
3647 }
3648 return status;
3649}
3650
3651void AudioFlinger::PlaybackThread::Track::stop()
3652{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003653 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003654 sp<ThreadBase> thread = mThread.promote();
3655 if (thread != 0) {
3656 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003657 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003658 if (mState > STOPPED) {
3659 mState = STOPPED;
3660 // If the track is not active (PAUSED and buffers full), flush buffers
3661 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3662 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3663 reset();
3664 }
Steve Block3856b092011-10-20 11:56:00 +01003665 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003666 }
3667 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3668 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003669 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003670 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003671
3672 // to track the speaker usage
3673 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003674 }
3675 }
3676}
3677
3678void AudioFlinger::PlaybackThread::Track::pause()
3679{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003680 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003681 sp<ThreadBase> thread = mThread.promote();
3682 if (thread != 0) {
3683 Mutex::Autolock _l(thread->mLock);
3684 if (mState == ACTIVE || mState == RESUMING) {
3685 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003686 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003687 if (!isOutputTrack()) {
3688 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003689 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003690 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003691
3692 // to track the speaker usage
3693 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003694 }
3695 }
3696 }
3697}
3698
3699void AudioFlinger::PlaybackThread::Track::flush()
3700{
Steve Block3856b092011-10-20 11:56:00 +01003701 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003702 sp<ThreadBase> thread = mThread.promote();
3703 if (thread != 0) {
3704 Mutex::Autolock _l(thread->mLock);
3705 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3706 return;
3707 }
3708 // No point remaining in PAUSED state after a flush => go to
3709 // STOPPED state
3710 mState = STOPPED;
3711
Eric Laurent38ccae22011-03-28 18:37:07 -07003712 // do not reset the track if it is still in the process of being stopped or paused.
3713 // this will be done by prepareTracks_l() when the track is stopped.
3714 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3715 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3716 reset();
3717 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003718 }
3719}
3720
3721void AudioFlinger::PlaybackThread::Track::reset()
3722{
3723 // Do not reset twice to avoid discarding data written just after a flush and before
3724 // the audioflinger thread detects the track is stopped.
3725 if (!mResetDone) {
3726 TrackBase::reset();
3727 // Force underrun condition to avoid false underrun callback until first data is
3728 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003729 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3730 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003731 mFillingUpStatus = FS_FILLING;
3732 mResetDone = true;
3733 }
3734}
3735
3736void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3737{
3738 mMute = muted;
3739}
3740
Mathias Agopian65ab4712010-07-14 17:59:35 -07003741status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3742{
3743 status_t status = DEAD_OBJECT;
3744 sp<ThreadBase> thread = mThread.promote();
3745 if (thread != 0) {
3746 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3747 status = playbackThread->attachAuxEffect(this, EffectId);
3748 }
3749 return status;
3750}
3751
3752void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3753{
3754 mAuxEffectId = EffectId;
3755 mAuxBuffer = buffer;
3756}
3757
John Grossman4ff14ba2012-02-08 16:37:41 -08003758// timed audio tracks
3759
3760sp<AudioFlinger::PlaybackThread::TimedTrack>
3761AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003762 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003763 const sp<Client>& client,
3764 audio_stream_type_t streamType,
3765 uint32_t sampleRate,
3766 audio_format_t format,
3767 uint32_t channelMask,
3768 int frameCount,
3769 const sp<IMemory>& sharedBuffer,
3770 int sessionId) {
3771 if (!client->reserveTimedTrack())
3772 return NULL;
3773
3774 sp<TimedTrack> track = new TimedTrack(
3775 thread, client, streamType, sampleRate, format, channelMask, frameCount,
3776 sharedBuffer, sessionId);
3777
3778 if (track == NULL) {
3779 client->releaseTimedTrack();
3780 return NULL;
3781 }
3782
3783 return track;
3784}
3785
3786AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003787 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003788 const sp<Client>& client,
3789 audio_stream_type_t streamType,
3790 uint32_t sampleRate,
3791 audio_format_t format,
3792 uint32_t channelMask,
3793 int frameCount,
3794 const sp<IMemory>& sharedBuffer,
3795 int sessionId)
3796 : Track(thread, client, streamType, sampleRate, format, channelMask,
3797 frameCount, sharedBuffer, sessionId),
3798 mTimedSilenceBuffer(NULL),
3799 mTimedSilenceBufferSize(0),
3800 mTimedAudioOutputOnTime(false),
3801 mMediaTimeTransformValid(false)
3802{
3803 LocalClock lc;
3804 mLocalTimeFreq = lc.getLocalFreq();
3805
3806 mLocalTimeToSampleTransform.a_zero = 0;
3807 mLocalTimeToSampleTransform.b_zero = 0;
3808 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3809 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3810 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3811 &mLocalTimeToSampleTransform.a_to_b_denom);
3812}
3813
3814AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3815 mClient->releaseTimedTrack();
3816 delete [] mTimedSilenceBuffer;
3817}
3818
3819status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3820 size_t size, sp<IMemory>* buffer) {
3821
3822 Mutex::Autolock _l(mTimedBufferQueueLock);
3823
3824 trimTimedBufferQueue_l();
3825
3826 // lazily initialize the shared memory heap for timed buffers
3827 if (mTimedMemoryDealer == NULL) {
3828 const int kTimedBufferHeapSize = 512 << 10;
3829
3830 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3831 "AudioFlingerTimed");
3832 if (mTimedMemoryDealer == NULL)
3833 return NO_MEMORY;
3834 }
3835
3836 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3837 if (newBuffer == NULL) {
3838 newBuffer = mTimedMemoryDealer->allocate(size);
3839 if (newBuffer == NULL)
3840 return NO_MEMORY;
3841 }
3842
3843 *buffer = newBuffer;
3844 return NO_ERROR;
3845}
3846
3847// caller must hold mTimedBufferQueueLock
3848void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
3849 int64_t mediaTimeNow;
3850 {
3851 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3852 if (!mMediaTimeTransformValid)
3853 return;
3854
3855 int64_t targetTimeNow;
3856 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
3857 ? mCCHelper.getCommonTime(&targetTimeNow)
3858 : mCCHelper.getLocalTime(&targetTimeNow);
3859
3860 if (OK != res)
3861 return;
3862
3863 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
3864 &mediaTimeNow)) {
3865 return;
3866 }
3867 }
3868
3869 size_t trimIndex;
3870 for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
3871 if (mTimedBufferQueue[trimIndex].pts() > mediaTimeNow)
3872 break;
3873 }
3874
3875 if (trimIndex) {
3876 mTimedBufferQueue.removeItemsAt(0, trimIndex);
3877 }
3878}
3879
3880status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
3881 const sp<IMemory>& buffer, int64_t pts) {
3882
3883 {
3884 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3885 if (!mMediaTimeTransformValid)
3886 return INVALID_OPERATION;
3887 }
3888
3889 Mutex::Autolock _l(mTimedBufferQueueLock);
3890
3891 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
3892
3893 return NO_ERROR;
3894}
3895
3896status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
3897 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
3898
3899 ALOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
3900 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
3901 target);
3902
3903 if (!(target == TimedAudioTrack::LOCAL_TIME ||
3904 target == TimedAudioTrack::COMMON_TIME)) {
3905 return BAD_VALUE;
3906 }
3907
3908 Mutex::Autolock lock(mMediaTimeTransformLock);
3909 mMediaTimeTransform = xform;
3910 mMediaTimeTransformTarget = target;
3911 mMediaTimeTransformValid = true;
3912
3913 return NO_ERROR;
3914}
3915
3916#define min(a, b) ((a) < (b) ? (a) : (b))
3917
3918// implementation of getNextBuffer for tracks whose buffers have timestamps
3919status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
3920 AudioBufferProvider::Buffer* buffer, int64_t pts)
3921{
3922 if (pts == AudioBufferProvider::kInvalidPTS) {
3923 buffer->raw = 0;
3924 buffer->frameCount = 0;
3925 return INVALID_OPERATION;
3926 }
3927
John Grossman4ff14ba2012-02-08 16:37:41 -08003928 Mutex::Autolock _l(mTimedBufferQueueLock);
3929
3930 while (true) {
3931
3932 // if we have no timed buffers, then fail
3933 if (mTimedBufferQueue.isEmpty()) {
3934 buffer->raw = 0;
3935 buffer->frameCount = 0;
3936 return NOT_ENOUGH_DATA;
3937 }
3938
3939 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
3940
3941 // calculate the PTS of the head of the timed buffer queue expressed in
3942 // local time
3943 int64_t headLocalPTS;
3944 {
3945 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3946
3947 assert(mMediaTimeTransformValid);
3948
3949 if (mMediaTimeTransform.a_to_b_denom == 0) {
3950 // the transform represents a pause, so yield silence
3951 timedYieldSilence(buffer->frameCount, buffer);
3952 return NO_ERROR;
3953 }
3954
3955 int64_t transformedPTS;
3956 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
3957 &transformedPTS)) {
3958 // the transform failed. this shouldn't happen, but if it does
3959 // then just drop this buffer
3960 ALOGW("timedGetNextBuffer transform failed");
3961 buffer->raw = 0;
3962 buffer->frameCount = 0;
3963 mTimedBufferQueue.removeAt(0);
3964 return NO_ERROR;
3965 }
3966
3967 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
3968 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
3969 &headLocalPTS)) {
3970 buffer->raw = 0;
3971 buffer->frameCount = 0;
3972 return INVALID_OPERATION;
3973 }
3974 } else {
3975 headLocalPTS = transformedPTS;
3976 }
3977 }
3978
3979 // adjust the head buffer's PTS to reflect the portion of the head buffer
3980 // that has already been consumed
3981 int64_t effectivePTS = headLocalPTS +
3982 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
3983
3984 // Calculate the delta in samples between the head of the input buffer
3985 // queue and the start of the next output buffer that will be written.
3986 // If the transformation fails because of over or underflow, it means
3987 // that the sample's position in the output stream is so far out of
3988 // whack that it should just be dropped.
3989 int64_t sampleDelta;
3990 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
3991 ALOGV("*** head buffer is too far from PTS: dropped buffer");
3992 mTimedBufferQueue.removeAt(0);
3993 continue;
3994 }
3995 if (!mLocalTimeToSampleTransform.doForwardTransform(
3996 (effectivePTS - pts) << 32, &sampleDelta)) {
3997 ALOGV("*** too late during sample rate transform: dropped buffer");
3998 mTimedBufferQueue.removeAt(0);
3999 continue;
4000 }
4001
4002 ALOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
4003 __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
4004 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
4005 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
4006
4007 // if the delta between the ideal placement for the next input sample and
4008 // the current output position is within this threshold, then we will
4009 // concatenate the next input samples to the previous output
4010 const int64_t kSampleContinuityThreshold =
4011 (static_cast<int64_t>(sampleRate()) << 32) / 10;
4012
4013 // if this is the first buffer of audio that we're emitting from this track
4014 // then it should be almost exactly on time.
4015 const int64_t kSampleStartupThreshold = 1LL << 32;
4016
4017 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
4018 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
4019 // the next input is close enough to being on time, so concatenate it
4020 // with the last output
4021 timedYieldSamples(buffer);
4022
4023 ALOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4024 return NO_ERROR;
4025 } else if (sampleDelta > 0) {
4026 // the gap between the current output position and the proper start of
4027 // the next input sample is too big, so fill it with silence
4028 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4029
4030 timedYieldSilence(framesUntilNextInput, buffer);
4031 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4032 return NO_ERROR;
4033 } else {
4034 // the next input sample is late
4035 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4036 size_t onTimeSamplePosition =
4037 head.position() + lateFrames * mCblk->frameSize;
4038
4039 if (onTimeSamplePosition > head.buffer()->size()) {
4040 // all the remaining samples in the head are too late, so
4041 // drop it and move on
4042 ALOGV("*** too late: dropped buffer");
4043 mTimedBufferQueue.removeAt(0);
4044 continue;
4045 } else {
4046 // skip over the late samples
4047 head.setPosition(onTimeSamplePosition);
4048
4049 // yield the available samples
4050 timedYieldSamples(buffer);
4051
4052 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4053 return NO_ERROR;
4054 }
4055 }
4056 }
4057}
4058
4059// Yield samples from the timed buffer queue head up to the given output
4060// buffer's capacity.
4061//
4062// Caller must hold mTimedBufferQueueLock
4063void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples(
4064 AudioBufferProvider::Buffer* buffer) {
4065
4066 const TimedBuffer& head = mTimedBufferQueue[0];
4067
4068 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4069 head.position());
4070
4071 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4072 mCblk->frameSize);
4073 size_t framesRequested = buffer->frameCount;
4074 buffer->frameCount = min(framesLeftInHead, framesRequested);
4075
4076 mTimedAudioOutputOnTime = true;
4077}
4078
4079// Yield samples of silence up to the given output buffer's capacity
4080//
4081// Caller must hold mTimedBufferQueueLock
4082void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence(
4083 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4084
4085 // lazily allocate a buffer filled with silence
4086 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4087 delete [] mTimedSilenceBuffer;
4088 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4089 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4090 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4091 }
4092
4093 buffer->raw = mTimedSilenceBuffer;
4094 size_t framesRequested = buffer->frameCount;
4095 buffer->frameCount = min(numFrames, framesRequested);
4096
4097 mTimedAudioOutputOnTime = false;
4098}
4099
4100void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4101 AudioBufferProvider::Buffer* buffer) {
4102
4103 Mutex::Autolock _l(mTimedBufferQueueLock);
4104
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004105 // If the buffer which was just released is part of the buffer at the head
4106 // of the queue, be sure to update the amt of the buffer which has been
4107 // consumed. If the buffer being returned is not part of the head of the
4108 // queue, its either because the buffer is part of the silence buffer, or
4109 // because the head of the timed queue was trimmed after the mixer called
4110 // getNextBuffer but before the mixer called releaseBuffer.
4111 if ((buffer->raw != mTimedSilenceBuffer) && mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004112 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004113
4114 void* start = head.buffer()->pointer();
Glenn Kastenf063b492012-02-17 16:24:10 -08004115 void* end = (char *) head.buffer()->pointer() + head.buffer()->size();
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004116
4117 if ((buffer->raw >= start) && (buffer->raw <= end)) {
4118 head.setPosition(head.position() +
4119 (buffer->frameCount * mCblk->frameSize));
4120 if (static_cast<size_t>(head.position()) >= head.buffer()->size()) {
4121 mTimedBufferQueue.removeAt(0);
4122 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004123 }
4124 }
4125
4126 buffer->raw = 0;
4127 buffer->frameCount = 0;
4128}
4129
4130uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4131 Mutex::Autolock _l(mTimedBufferQueueLock);
4132
4133 uint32_t frames = 0;
4134 for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4135 const TimedBuffer& tb = mTimedBufferQueue[i];
4136 frames += (tb.buffer()->size() - tb.position()) / mCblk->frameSize;
4137 }
4138
4139 return frames;
4140}
4141
4142AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4143 : mPTS(0), mPosition(0) {}
4144
4145AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4146 const sp<IMemory>& buffer, int64_t pts)
4147 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4148
Mathias Agopian65ab4712010-07-14 17:59:35 -07004149// ----------------------------------------------------------------------------
4150
4151// RecordTrack constructor must be called with AudioFlinger::mLock held
4152AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004153 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004154 const sp<Client>& client,
4155 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004156 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004157 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004158 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004159 int sessionId)
4160 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004161 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004162 mOverflow(false)
4163{
4164 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01004165 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07004166 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004167 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07004168 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004169 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004170 } else {
4171 mCblk->frameSize = sizeof(int8_t);
4172 }
4173 }
4174}
4175
4176AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4177{
4178 sp<ThreadBase> thread = mThread.promote();
4179 if (thread != 0) {
4180 AudioSystem::releaseInput(thread->id());
4181 }
4182}
4183
John Grossman4ff14ba2012-02-08 16:37:41 -08004184status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004185{
4186 audio_track_cblk_t* cblk = this->cblk();
4187 uint32_t framesAvail;
4188 uint32_t framesReq = buffer->frameCount;
4189
4190 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004191 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004192 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004193 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004194 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004195 }
4196
4197 framesAvail = cblk->framesAvailable_l();
4198
Glenn Kastenf6b16782011-12-15 09:51:17 -08004199 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004200 uint32_t s = cblk->server;
4201 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4202
4203 if (framesReq > framesAvail) {
4204 framesReq = framesAvail;
4205 }
4206 if (s + framesReq > bufferEnd) {
4207 framesReq = bufferEnd - s;
4208 }
4209
4210 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004211 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004212
4213 buffer->frameCount = framesReq;
4214 return NO_ERROR;
4215 }
4216
4217getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004218 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004219 buffer->frameCount = 0;
4220 return NOT_ENOUGH_DATA;
4221}
4222
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004223status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004224{
4225 sp<ThreadBase> thread = mThread.promote();
4226 if (thread != 0) {
4227 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004228 return recordThread->start(this, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004229 } else {
4230 return BAD_VALUE;
4231 }
4232}
4233
4234void AudioFlinger::RecordThread::RecordTrack::stop()
4235{
4236 sp<ThreadBase> thread = mThread.promote();
4237 if (thread != 0) {
4238 RecordThread *recordThread = (RecordThread *)thread.get();
4239 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004240 TrackBase::reset();
4241 // Force overerrun condition to avoid false overrun callback until first data is
4242 // read from buffer
4243 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004244 }
4245}
4246
4247void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4248{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004249 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004250 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004251 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004252 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004253 mSessionId,
4254 mFrameCount,
4255 mState,
4256 mCblk->sampleRate,
4257 mCblk->server,
4258 mCblk->user);
4259}
4260
4261
4262// ----------------------------------------------------------------------------
4263
4264AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004265 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004266 DuplicatingThread *sourceThread,
4267 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004268 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004269 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004270 int frameCount)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004271 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004272 mActive(false), mSourceThread(sourceThread)
4273{
4274
Mathias Agopian65ab4712010-07-14 17:59:35 -07004275 if (mCblk != NULL) {
4276 mCblk->flags |= CBLK_DIRECTION_OUT;
4277 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004278 mOutBuffer.frameCount = 0;
4279 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01004280 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004281 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4282 mCblk, mBuffer, mCblk->buffers,
4283 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004284 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004285 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004286 }
4287}
4288
4289AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4290{
4291 clearBufferQueue();
4292}
4293
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004294status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004295{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004296 status_t status = Track::start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004297 if (status != NO_ERROR) {
4298 return status;
4299 }
4300
4301 mActive = true;
4302 mRetryCount = 127;
4303 return status;
4304}
4305
4306void AudioFlinger::PlaybackThread::OutputTrack::stop()
4307{
4308 Track::stop();
4309 clearBufferQueue();
4310 mOutBuffer.frameCount = 0;
4311 mActive = false;
4312}
4313
4314bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4315{
4316 Buffer *pInBuffer;
4317 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004318 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004319 bool outputBufferFull = false;
4320 inBuffer.frameCount = frames;
4321 inBuffer.i16 = data;
4322
4323 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4324
4325 if (!mActive && frames != 0) {
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004326 start(0);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004327 sp<ThreadBase> thread = mThread.promote();
4328 if (thread != 0) {
4329 MixerThread *mixerThread = (MixerThread *)thread.get();
4330 if (mCblk->frameCount > frames){
4331 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4332 uint32_t startFrames = (mCblk->frameCount - frames);
4333 pInBuffer = new Buffer;
4334 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4335 pInBuffer->frameCount = startFrames;
4336 pInBuffer->i16 = pInBuffer->mBuffer;
4337 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4338 mBufferQueue.add(pInBuffer);
4339 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004340 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004341 }
4342 }
4343 }
4344 }
4345
4346 while (waitTimeLeftMs) {
4347 // First write pending buffers, then new data
4348 if (mBufferQueue.size()) {
4349 pInBuffer = mBufferQueue.itemAt(0);
4350 } else {
4351 pInBuffer = &inBuffer;
4352 }
4353
4354 if (pInBuffer->frameCount == 0) {
4355 break;
4356 }
4357
4358 if (mOutBuffer.frameCount == 0) {
4359 mOutBuffer.frameCount = pInBuffer->frameCount;
4360 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08004361 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01004362 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004363 outputBufferFull = true;
4364 break;
4365 }
4366 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4367 if (waitTimeLeftMs >= waitTimeMs) {
4368 waitTimeLeftMs -= waitTimeMs;
4369 } else {
4370 waitTimeLeftMs = 0;
4371 }
4372 }
4373
4374 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4375 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4376 mCblk->stepUser(outFrames);
4377 pInBuffer->frameCount -= outFrames;
4378 pInBuffer->i16 += outFrames * channelCount;
4379 mOutBuffer.frameCount -= outFrames;
4380 mOutBuffer.i16 += outFrames * channelCount;
4381
4382 if (pInBuffer->frameCount == 0) {
4383 if (mBufferQueue.size()) {
4384 mBufferQueue.removeAt(0);
4385 delete [] pInBuffer->mBuffer;
4386 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01004387 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004388 } else {
4389 break;
4390 }
4391 }
4392 }
4393
4394 // If we could not write all frames, allocate a buffer and queue it for next time.
4395 if (inBuffer.frameCount) {
4396 sp<ThreadBase> thread = mThread.promote();
4397 if (thread != 0 && !thread->standby()) {
4398 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4399 pInBuffer = new Buffer;
4400 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4401 pInBuffer->frameCount = inBuffer.frameCount;
4402 pInBuffer->i16 = pInBuffer->mBuffer;
4403 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4404 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01004405 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004406 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004407 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004408 }
4409 }
4410 }
4411
4412 // Calling write() with a 0 length buffer, means that no more data will be written:
4413 // If no more buffers are pending, fill output track buffer to make sure it is started
4414 // by output mixer.
4415 if (frames == 0 && mBufferQueue.size() == 0) {
4416 if (mCblk->user < mCblk->frameCount) {
4417 frames = mCblk->frameCount - mCblk->user;
4418 pInBuffer = new Buffer;
4419 pInBuffer->mBuffer = new int16_t[frames * channelCount];
4420 pInBuffer->frameCount = frames;
4421 pInBuffer->i16 = pInBuffer->mBuffer;
4422 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4423 mBufferQueue.add(pInBuffer);
4424 } else if (mActive) {
4425 stop();
4426 }
4427 }
4428
4429 return outputBufferFull;
4430}
4431
4432status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4433{
4434 int active;
4435 status_t result;
4436 audio_track_cblk_t* cblk = mCblk;
4437 uint32_t framesReq = buffer->frameCount;
4438
Steve Block3856b092011-10-20 11:56:00 +01004439// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004440 buffer->frameCount = 0;
4441
4442 uint32_t framesAvail = cblk->framesAvailable();
4443
4444
4445 if (framesAvail == 0) {
4446 Mutex::Autolock _l(cblk->lock);
4447 goto start_loop_here;
4448 while (framesAvail == 0) {
4449 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004450 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004451 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004452 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004453 }
4454 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4455 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004456 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004457 }
4458 // read the server count again
4459 start_loop_here:
4460 framesAvail = cblk->framesAvailable_l();
4461 }
4462 }
4463
4464// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004465// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004466// }
4467
4468 if (framesReq > framesAvail) {
4469 framesReq = framesAvail;
4470 }
4471
4472 uint32_t u = cblk->user;
4473 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4474
4475 if (u + framesReq > bufferEnd) {
4476 framesReq = bufferEnd - u;
4477 }
4478
4479 buffer->frameCount = framesReq;
4480 buffer->raw = (void *)cblk->buffer(u);
4481 return NO_ERROR;
4482}
4483
4484
4485void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4486{
4487 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004488
4489 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004490 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004491 delete [] pBuffer->mBuffer;
4492 delete pBuffer;
4493 }
4494 mBufferQueue.clear();
4495}
4496
4497// ----------------------------------------------------------------------------
4498
4499AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4500 : RefBase(),
4501 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08004502 // 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 -07004503 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08004504 mPid(pid),
4505 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004506{
4507 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4508}
4509
4510// Client destructor must be called with AudioFlinger::mLock held
4511AudioFlinger::Client::~Client()
4512{
4513 mAudioFlinger->removeClient_l(mPid);
4514}
4515
Glenn Kasten435dbe62012-01-30 10:15:48 -08004516sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004517{
4518 return mMemoryDealer;
4519}
4520
John Grossman4ff14ba2012-02-08 16:37:41 -08004521// Reserve one of the limited slots for a timed audio track associated
4522// with this client
4523bool AudioFlinger::Client::reserveTimedTrack()
4524{
4525 const int kMaxTimedTracksPerClient = 4;
4526
4527 Mutex::Autolock _l(mTimedTrackLock);
4528
4529 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4530 ALOGW("can not create timed track - pid %d has exceeded the limit",
4531 mPid);
4532 return false;
4533 }
4534
4535 mTimedTrackCount++;
4536 return true;
4537}
4538
4539// Release a slot for a timed audio track
4540void AudioFlinger::Client::releaseTimedTrack()
4541{
4542 Mutex::Autolock _l(mTimedTrackLock);
4543 mTimedTrackCount--;
4544}
4545
Mathias Agopian65ab4712010-07-14 17:59:35 -07004546// ----------------------------------------------------------------------------
4547
4548AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4549 const sp<IAudioFlingerClient>& client,
4550 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004551 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004552{
4553}
4554
4555AudioFlinger::NotificationClient::~NotificationClient()
4556{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004557}
4558
4559void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4560{
4561 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08004562 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004563}
4564
4565// ----------------------------------------------------------------------------
4566
4567AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4568 : BnAudioTrack(),
4569 mTrack(track)
4570{
4571}
4572
4573AudioFlinger::TrackHandle::~TrackHandle() {
4574 // just stop the track on deletion, associated resources
4575 // will be freed from the main thread once all pending buffers have
4576 // been played. Unless it's not in the active track list, in which
4577 // case we free everything now...
4578 mTrack->destroy();
4579}
4580
Glenn Kasten90716c52012-01-26 13:40:12 -08004581sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4582 return mTrack->getCblk();
4583}
4584
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004585status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4586 return mTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004587}
4588
4589void AudioFlinger::TrackHandle::stop() {
4590 mTrack->stop();
4591}
4592
4593void AudioFlinger::TrackHandle::flush() {
4594 mTrack->flush();
4595}
4596
4597void AudioFlinger::TrackHandle::mute(bool e) {
4598 mTrack->mute(e);
4599}
4600
4601void AudioFlinger::TrackHandle::pause() {
4602 mTrack->pause();
4603}
4604
Mathias Agopian65ab4712010-07-14 17:59:35 -07004605status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4606{
4607 return mTrack->attachAuxEffect(EffectId);
4608}
4609
John Grossman4ff14ba2012-02-08 16:37:41 -08004610status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4611 sp<IMemory>* buffer) {
4612 if (!mTrack->isTimedTrack())
4613 return INVALID_OPERATION;
4614
4615 PlaybackThread::TimedTrack* tt =
4616 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4617 return tt->allocateTimedBuffer(size, buffer);
4618}
4619
4620status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4621 int64_t pts) {
4622 if (!mTrack->isTimedTrack())
4623 return INVALID_OPERATION;
4624
4625 PlaybackThread::TimedTrack* tt =
4626 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4627 return tt->queueTimedBuffer(buffer, pts);
4628}
4629
4630status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4631 const LinearTransform& xform, int target) {
4632
4633 if (!mTrack->isTimedTrack())
4634 return INVALID_OPERATION;
4635
4636 PlaybackThread::TimedTrack* tt =
4637 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4638 return tt->setMediaTimeTransform(
4639 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4640}
4641
Mathias Agopian65ab4712010-07-14 17:59:35 -07004642status_t AudioFlinger::TrackHandle::onTransact(
4643 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4644{
4645 return BnAudioTrack::onTransact(code, data, reply, flags);
4646}
4647
4648// ----------------------------------------------------------------------------
4649
4650sp<IAudioRecord> AudioFlinger::openRecord(
4651 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004652 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004653 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004654 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004655 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004656 int frameCount,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004657 // FIXME dead, remove from IAudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -07004658 uint32_t flags,
4659 int *sessionId,
4660 status_t *status)
4661{
4662 sp<RecordThread::RecordTrack> recordTrack;
4663 sp<RecordHandle> recordHandle;
4664 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004665 status_t lStatus;
4666 RecordThread *thread;
4667 size_t inFrameCount;
4668 int lSessionId;
4669
4670 // check calling permissions
4671 if (!recordingAllowed()) {
4672 lStatus = PERMISSION_DENIED;
4673 goto Exit;
4674 }
4675
4676 // add client to list
4677 { // scope for mLock
4678 Mutex::Autolock _l(mLock);
4679 thread = checkRecordThread_l(input);
4680 if (thread == NULL) {
4681 lStatus = BAD_VALUE;
4682 goto Exit;
4683 }
4684
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004685 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004686
4687 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004688 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004689 lSessionId = *sessionId;
4690 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004691 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004692 if (sessionId != NULL) {
4693 *sessionId = lSessionId;
4694 }
4695 }
4696 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004697 recordTrack = thread->createRecordTrack_l(client,
4698 sampleRate,
4699 format,
4700 channelMask,
4701 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004702 lSessionId,
4703 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004704 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004705 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004706 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4707 // destructor is called by the TrackBase destructor with mLock held
4708 client.clear();
4709 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004710 goto Exit;
4711 }
4712
4713 // return to handle to client
4714 recordHandle = new RecordHandle(recordTrack);
4715 lStatus = NO_ERROR;
4716
4717Exit:
4718 if (status) {
4719 *status = lStatus;
4720 }
4721 return recordHandle;
4722}
4723
4724// ----------------------------------------------------------------------------
4725
4726AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4727 : BnAudioRecord(),
4728 mRecordTrack(recordTrack)
4729{
4730}
4731
4732AudioFlinger::RecordHandle::~RecordHandle() {
4733 stop();
4734}
4735
Glenn Kasten90716c52012-01-26 13:40:12 -08004736sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4737 return mRecordTrack->getCblk();
4738}
4739
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004740status_t AudioFlinger::RecordHandle::start(pid_t tid) {
Steve Block3856b092011-10-20 11:56:00 +01004741 ALOGV("RecordHandle::start()");
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004742 return mRecordTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004743}
4744
4745void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004746 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004747 mRecordTrack->stop();
4748}
4749
Mathias Agopian65ab4712010-07-14 17:59:35 -07004750status_t AudioFlinger::RecordHandle::onTransact(
4751 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4752{
4753 return BnAudioRecord::onTransact(code, data, reply, flags);
4754}
4755
4756// ----------------------------------------------------------------------------
4757
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004758AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4759 AudioStreamIn *input,
4760 uint32_t sampleRate,
4761 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004762 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004763 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004764 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004765 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4766 // mRsmpInIndex and mInputBytes set by readInputParameters()
4767 mReqChannelCount(popcount(channels)),
4768 mReqSampleRate(sampleRate)
4769 // mBytesRead is only meaningful while active, and so is cleared in start()
4770 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004771{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004772 snprintf(mName, kNameLength, "AudioIn_%d", id);
4773
Mathias Agopian65ab4712010-07-14 17:59:35 -07004774 readInputParameters();
4775}
4776
4777
4778AudioFlinger::RecordThread::~RecordThread()
4779{
4780 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004781 delete mResampler;
4782 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004783}
4784
4785void AudioFlinger::RecordThread::onFirstRef()
4786{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004787 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004788}
4789
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004790status_t AudioFlinger::RecordThread::readyToRun()
4791{
4792 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004793 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004794 return status;
4795}
4796
Mathias Agopian65ab4712010-07-14 17:59:35 -07004797bool AudioFlinger::RecordThread::threadLoop()
4798{
4799 AudioBufferProvider::Buffer buffer;
4800 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004801 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004802
Eric Laurent44d98482010-09-30 16:12:31 -07004803 nsecs_t lastWarning = 0;
4804
Eric Laurentfeb0db62011-07-22 09:04:31 -07004805 acquireWakeLock();
4806
Mathias Agopian65ab4712010-07-14 17:59:35 -07004807 // start recording
4808 while (!exitPending()) {
4809
4810 processConfigEvents();
4811
4812 { // scope for mLock
4813 Mutex::Autolock _l(mLock);
4814 checkForNewParameters_l();
4815 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4816 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004817 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004818 mStandby = true;
4819 }
4820
4821 if (exitPending()) break;
4822
Eric Laurentfeb0db62011-07-22 09:04:31 -07004823 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004824 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004825 // go to sleep
4826 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004827 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004828 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004829 continue;
4830 }
4831 if (mActiveTrack != 0) {
4832 if (mActiveTrack->mState == TrackBase::PAUSING) {
4833 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004834 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004835 mStandby = true;
4836 }
4837 mActiveTrack.clear();
4838 mStartStopCond.broadcast();
4839 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4840 if (mReqChannelCount != mActiveTrack->channelCount()) {
4841 mActiveTrack.clear();
4842 mStartStopCond.broadcast();
4843 } else if (mBytesRead != 0) {
4844 // record start succeeds only if first read from audio input
4845 // succeeds
4846 if (mBytesRead > 0) {
4847 mActiveTrack->mState = TrackBase::ACTIVE;
4848 } else {
4849 mActiveTrack.clear();
4850 }
4851 mStartStopCond.broadcast();
4852 }
4853 mStandby = false;
4854 }
4855 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004856 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004857 }
4858
4859 if (mActiveTrack != 0) {
4860 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4861 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004862 unlockEffectChains(effectChains);
4863 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004864 continue;
4865 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004866 for (size_t i = 0; i < effectChains.size(); i ++) {
4867 effectChains[i]->process_l();
4868 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004869
Mathias Agopian65ab4712010-07-14 17:59:35 -07004870 buffer.frameCount = mFrameCount;
John Grossman4ff14ba2012-02-08 16:37:41 -08004871 if (CC_LIKELY(mActiveTrack->getNextBuffer(
4872 &buffer, AudioBufferProvider::kInvalidPTS) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004873 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004874 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004875 // no resampling
4876 while (framesOut) {
4877 size_t framesIn = mFrameCount - mRsmpInIndex;
4878 if (framesIn) {
4879 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4880 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4881 if (framesIn > framesOut)
4882 framesIn = framesOut;
4883 mRsmpInIndex += framesIn;
4884 framesOut -= framesIn;
4885 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004886 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004887 memcpy(dst, src, framesIn * mFrameSize);
4888 } else {
4889 int16_t *src16 = (int16_t *)src;
4890 int16_t *dst16 = (int16_t *)dst;
4891 if (mChannelCount == 1) {
4892 while (framesIn--) {
4893 *dst16++ = *src16;
4894 *dst16++ = *src16++;
4895 }
4896 } else {
4897 while (framesIn--) {
4898 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4899 src16 += 2;
4900 }
4901 }
4902 }
4903 }
4904 if (framesOut && mFrameCount == mRsmpInIndex) {
4905 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004906 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004907 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004908 framesOut = 0;
4909 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004910 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004911 mRsmpInIndex = 0;
4912 }
4913 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004914 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004915 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4916 // Force input into standby so that it tries to
4917 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004918 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004919 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004920 }
4921 mRsmpInIndex = mFrameCount;
4922 framesOut = 0;
4923 buffer.frameCount = 0;
4924 }
4925 }
4926 }
4927 } else {
4928 // resampling
4929
4930 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4931 // alter output frame count as if we were expecting stereo samples
4932 if (mChannelCount == 1 && mReqChannelCount == 1) {
4933 framesOut >>= 1;
4934 }
4935 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4936 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4937 // are 32 bit aligned which should be always true.
4938 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004939 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004940 // the resampler always outputs stereo samples: do post stereo to mono conversion
4941 int16_t *src = (int16_t *)mRsmpOutBuffer;
4942 int16_t *dst = buffer.i16;
4943 while (framesOut--) {
4944 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4945 src += 2;
4946 }
4947 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004948 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004949 }
4950
4951 }
4952 mActiveTrack->releaseBuffer(&buffer);
4953 mActiveTrack->overflow();
4954 }
4955 // client isn't retrieving buffers fast enough
4956 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004957 if (!mActiveTrack->setOverflow()) {
4958 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004959 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004960 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004961 lastWarning = now;
4962 }
4963 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004964 // Release the processor for a while before asking for a new buffer.
4965 // This will give the application more chance to read from the buffer and
4966 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004967 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004968 }
4969 }
Eric Laurentec437d82011-07-26 20:54:46 -07004970 // enable changes in effect chain
4971 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004972 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004973 }
4974
4975 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004976 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004977 }
4978 mActiveTrack.clear();
4979
4980 mStartStopCond.broadcast();
4981
Eric Laurentfeb0db62011-07-22 09:04:31 -07004982 releaseWakeLock();
4983
Steve Block3856b092011-10-20 11:56:00 +01004984 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004985 return false;
4986}
4987
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004988
4989sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4990 const sp<AudioFlinger::Client>& client,
4991 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004992 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004993 int channelMask,
4994 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004995 int sessionId,
4996 status_t *status)
4997{
4998 sp<RecordTrack> track;
4999 status_t lStatus;
5000
5001 lStatus = initCheck();
5002 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005003 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005004 goto Exit;
5005 }
5006
5007 { // scope for mLock
5008 Mutex::Autolock _l(mLock);
5009
5010 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005011 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005012
Glenn Kasten7378ca52012-01-20 13:44:40 -08005013 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005014 lStatus = NO_MEMORY;
5015 goto Exit;
5016 }
5017
5018 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005019 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5020 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005021 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005022 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5023 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005024 }
5025 lStatus = NO_ERROR;
5026
5027Exit:
5028 if (status) {
5029 *status = lStatus;
5030 }
5031 return track;
5032}
5033
Glenn Kasten6dbc1352012-02-02 10:56:47 -08005034status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005035{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08005036 ALOGV("RecordThread::start tid=%d", tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005037 sp <ThreadBase> strongMe = this;
5038 status_t status = NO_ERROR;
5039 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005040 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005041 if (mActiveTrack != 0) {
5042 if (recordTrack != mActiveTrack.get()) {
5043 status = -EBUSY;
5044 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5045 mActiveTrack->mState = TrackBase::ACTIVE;
5046 }
5047 return status;
5048 }
5049
5050 recordTrack->mState = TrackBase::IDLE;
5051 mActiveTrack = recordTrack;
5052 mLock.unlock();
5053 status_t status = AudioSystem::startInput(mId);
5054 mLock.lock();
5055 if (status != NO_ERROR) {
5056 mActiveTrack.clear();
5057 return status;
5058 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005059 mRsmpInIndex = mFrameCount;
5060 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005061 if (mResampler != NULL) {
5062 mResampler->reset();
5063 }
5064 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005065 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005066 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005067 mWaitWorkCV.signal();
5068 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005069 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005070 mActiveTrack.clear();
5071 status = INVALID_OPERATION;
5072 goto startError;
5073 }
5074 mStartStopCond.wait(mLock);
5075 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005076 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005077 status = BAD_VALUE;
5078 goto startError;
5079 }
Steve Block3856b092011-10-20 11:56:00 +01005080 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005081 return status;
5082 }
5083startError:
5084 AudioSystem::stopInput(mId);
5085 return status;
5086}
5087
5088void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005089 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005090 sp <ThreadBase> strongMe = this;
5091 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005092 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005093 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5094 mActiveTrack->mState = TrackBase::PAUSING;
5095 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005096 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005097 return;
5098 }
5099 mStartStopCond.wait(mLock);
5100 // if we have been restarted, recordTrack == mActiveTrack.get() here
5101 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5102 mLock.unlock();
5103 AudioSystem::stopInput(mId);
5104 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005105 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005106 }
5107 }
5108 }
5109}
5110
5111status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5112{
5113 const size_t SIZE = 256;
5114 char buffer[SIZE];
5115 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005116
5117 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5118 result.append(buffer);
5119
5120 if (mActiveTrack != 0) {
5121 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005122 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005123 mActiveTrack->dump(buffer, SIZE);
5124 result.append(buffer);
5125
5126 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5127 result.append(buffer);
5128 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5129 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005130 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005131 result.append(buffer);
5132 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5133 result.append(buffer);
5134 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5135 result.append(buffer);
5136
5137
5138 } else {
5139 result.append("No record client\n");
5140 }
5141 write(fd, result.string(), result.size());
5142
5143 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005144 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005145
5146 return NO_ERROR;
5147}
5148
John Grossman4ff14ba2012-02-08 16:37:41 -08005149status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005150{
5151 size_t framesReq = buffer->frameCount;
5152 size_t framesReady = mFrameCount - mRsmpInIndex;
5153 int channelCount;
5154
5155 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005156 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005157 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005158 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005159 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5160 // Force input into standby so that it tries to
5161 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005162 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005163 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005164 }
Glenn Kastene0feee32011-12-13 11:53:26 -08005165 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005166 buffer->frameCount = 0;
5167 return NOT_ENOUGH_DATA;
5168 }
5169 mRsmpInIndex = 0;
5170 framesReady = mFrameCount;
5171 }
5172
5173 if (framesReq > framesReady) {
5174 framesReq = framesReady;
5175 }
5176
5177 if (mChannelCount == 1 && mReqChannelCount == 2) {
5178 channelCount = 1;
5179 } else {
5180 channelCount = 2;
5181 }
5182 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5183 buffer->frameCount = framesReq;
5184 return NO_ERROR;
5185}
5186
5187void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5188{
5189 mRsmpInIndex += buffer->frameCount;
5190 buffer->frameCount = 0;
5191}
5192
5193bool AudioFlinger::RecordThread::checkForNewParameters_l()
5194{
5195 bool reconfig = false;
5196
5197 while (!mNewParameters.isEmpty()) {
5198 status_t status = NO_ERROR;
5199 String8 keyValuePair = mNewParameters[0];
5200 AudioParameter param = AudioParameter(keyValuePair);
5201 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08005202 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005203 int reqSamplingRate = mReqSampleRate;
5204 int reqChannelCount = mReqChannelCount;
5205
5206 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5207 reqSamplingRate = value;
5208 reconfig = true;
5209 }
5210 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08005211 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005212 reconfig = true;
5213 }
5214 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005215 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005216 reconfig = true;
5217 }
5218 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5219 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08005220 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005221 // if frame count is changed after track creation
5222 if (mActiveTrack != 0) {
5223 status = INVALID_OPERATION;
5224 } else {
5225 reconfig = true;
5226 }
5227 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005228 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5229 // forward device change to effects that have requested to be
5230 // aware of attached audio device.
5231 for (size_t i = 0; i < mEffectChains.size(); i++) {
5232 mEffectChains[i]->setDevice_l(value);
5233 }
5234 // store input device and output device but do not forward output device to audio HAL.
5235 // Note that status is ignored by the caller for output device
5236 // (see AudioFlinger::setParameters()
5237 if (value & AUDIO_DEVICE_OUT_ALL) {
5238 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5239 status = BAD_VALUE;
5240 } else {
5241 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07005242 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5243 if (mTrack != NULL) {
5244 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005245 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005246 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5247 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5248 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005249 }
5250 mDevice |= (uint32_t)value;
5251 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005252 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005253 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005254 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005255 mInput->stream->common.standby(&mInput->stream->common);
5256 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005257 }
5258 if (reconfig) {
5259 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005260 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005261 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005262 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
5263 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005264 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005265 status = NO_ERROR;
5266 }
5267 if (status == NO_ERROR) {
5268 readInputParameters();
5269 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5270 }
5271 }
5272 }
5273
5274 mNewParameters.removeAt(0);
5275
5276 mParamStatus = status;
5277 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07005278 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5279 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08005280 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005281 }
5282 return reconfig;
5283}
5284
5285String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5286{
Dima Zavinfce7a472011-04-19 22:30:36 -07005287 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005288 String8 out_s8 = String8();
5289
5290 Mutex::Autolock _l(mLock);
5291 if (initCheck() != NO_ERROR) {
5292 return out_s8;
5293 }
Dima Zavinfce7a472011-04-19 22:30:36 -07005294
Dima Zavin799a70e2011-04-18 16:57:27 -07005295 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07005296 out_s8 = String8(s);
5297 free(s);
5298 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005299}
5300
5301void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5302 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08005303 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005304
5305 switch (event) {
5306 case AudioSystem::INPUT_OPENED:
5307 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005308 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005309 desc.samplingRate = mSampleRate;
5310 desc.format = mFormat;
5311 desc.frameCount = mFrameCount;
5312 desc.latency = 0;
5313 param2 = &desc;
5314 break;
5315
5316 case AudioSystem::INPUT_CLOSED:
5317 default:
5318 break;
5319 }
5320 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5321}
5322
5323void AudioFlinger::RecordThread::readInputParameters()
5324{
Glenn Kastene9dd0172012-01-27 18:08:45 -08005325 delete mRsmpInBuffer;
5326 // mRsmpInBuffer is always assigned a new[] below
5327 delete mRsmpOutBuffer;
5328 mRsmpOutBuffer = NULL;
5329 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08005330 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005331
Dima Zavin799a70e2011-04-18 16:57:27 -07005332 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005333 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5334 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07005335 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08005336 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07005337 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005338 mFrameCount = mInputBytes / mFrameSize;
5339 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5340
5341 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
5342 {
5343 int channelCount;
5344 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5345 // stereo to mono post process as the resampler always outputs stereo.
5346 if (mChannelCount == 1 && mReqChannelCount == 2) {
5347 channelCount = 1;
5348 } else {
5349 channelCount = 2;
5350 }
5351 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5352 mResampler->setSampleRate(mSampleRate);
5353 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5354 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5355
5356 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5357 if (mChannelCount == 1 && mReqChannelCount == 1) {
5358 mFrameCount >>= 1;
5359 }
5360
5361 }
5362 mRsmpInIndex = mFrameCount;
5363}
5364
5365unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5366{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005367 Mutex::Autolock _l(mLock);
5368 if (initCheck() != NO_ERROR) {
5369 return 0;
5370 }
5371
Dima Zavin799a70e2011-04-18 16:57:27 -07005372 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005373}
5374
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005375uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5376{
5377 Mutex::Autolock _l(mLock);
5378 uint32_t result = 0;
5379 if (getEffectChain_l(sessionId) != 0) {
5380 result = EFFECT_SESSION;
5381 }
5382
5383 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5384 result |= TRACK_SESSION;
5385 }
5386
5387 return result;
5388}
5389
Eric Laurent59bd0da2011-08-01 09:52:20 -07005390AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5391{
5392 Mutex::Autolock _l(mLock);
5393 return mTrack;
5394}
5395
Glenn Kastenaed850d2012-01-26 09:46:34 -08005396AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005397{
5398 Mutex::Autolock _l(mLock);
5399 return mInput;
5400}
5401
5402AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5403{
5404 Mutex::Autolock _l(mLock);
5405 AudioStreamIn *input = mInput;
5406 mInput = NULL;
5407 return input;
5408}
5409
5410// this method must always be called either with ThreadBase mLock held or inside the thread loop
5411audio_stream_t* AudioFlinger::RecordThread::stream()
5412{
5413 if (mInput == NULL) {
5414 return NULL;
5415 }
5416 return &mInput->stream->common;
5417}
5418
5419
Mathias Agopian65ab4712010-07-14 17:59:35 -07005420// ----------------------------------------------------------------------------
5421
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005422audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005423 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005424 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005425 uint32_t *pChannels,
5426 uint32_t *pLatencyMs,
5427 uint32_t flags)
5428{
5429 status_t status;
5430 PlaybackThread *thread = NULL;
5431 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
5432 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005433 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005434 uint32_t channels = pChannels ? *pChannels : 0;
5435 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07005436 audio_stream_out_t *outStream;
5437 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005438
Steve Block3856b092011-10-20 11:56:00 +01005439 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07005440 pDevices ? *pDevices : 0,
5441 samplingRate,
5442 format,
5443 channels,
5444 flags);
5445
5446 if (pDevices == NULL || *pDevices == 0) {
5447 return 0;
5448 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005449
Mathias Agopian65ab4712010-07-14 17:59:35 -07005450 Mutex::Autolock _l(mLock);
5451
Dima Zavin799a70e2011-04-18 16:57:27 -07005452 outHwDev = findSuitableHwDev_l(*pDevices);
5453 if (outHwDev == NULL)
5454 return 0;
5455
Glenn Kasten58f30212012-01-12 12:27:51 -08005456 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005457 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01005458 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005459 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005460 samplingRate,
5461 format,
5462 channels,
5463 status);
5464
5465 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07005466 if (outStream != NULL) {
5467 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005468 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07005469
Dima Zavinfce7a472011-04-19 22:30:36 -07005470 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5471 (format != AUDIO_FORMAT_PCM_16_BIT) ||
5472 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005473 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005474 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005475 } else {
5476 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005477 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005478 }
5479 mPlaybackThreads.add(id, thread);
5480
Glenn Kastena0d68332012-01-27 16:47:15 -08005481 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5482 if (pFormat != NULL) *pFormat = format;
5483 if (pChannels != NULL) *pChannels = channels;
5484 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005485
5486 // notify client processes of the new output creation
5487 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5488 return id;
5489 }
5490
5491 return 0;
5492}
5493
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005494audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
5495 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005496{
5497 Mutex::Autolock _l(mLock);
5498 MixerThread *thread1 = checkMixerThread_l(output1);
5499 MixerThread *thread2 = checkMixerThread_l(output2);
5500
5501 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005502 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005503 return 0;
5504 }
5505
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005506 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005507 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5508 thread->addOutputTrack(thread2);
5509 mPlaybackThreads.add(id, thread);
5510 // notify client processes of the new output creation
5511 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5512 return id;
5513}
5514
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005515status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005516{
5517 // keep strong reference on the playback thread so that
5518 // it is not destroyed while exit() is executed
5519 sp <PlaybackThread> thread;
5520 {
5521 Mutex::Autolock _l(mLock);
5522 thread = checkPlaybackThread_l(output);
5523 if (thread == NULL) {
5524 return BAD_VALUE;
5525 }
5526
Steve Block3856b092011-10-20 11:56:00 +01005527 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005528
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005529 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005530 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005531 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005532 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5533 dupThread->removeOutputTrack((MixerThread *)thread.get());
5534 }
5535 }
5536 }
Glenn Kastena1117922012-01-26 10:53:32 -08005537 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005538 mPlaybackThreads.removeItem(output);
5539 }
5540 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005541 // The thread entity (active unit of execution) is no longer running here,
5542 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005543
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005544 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005545 AudioStreamOut *out = thread->clearOutput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005546 assert(out != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005547 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005548 out->hwDev->close_output_stream(out->hwDev, out->stream);
5549 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005550 }
5551 return NO_ERROR;
5552}
5553
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005554status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005555{
5556 Mutex::Autolock _l(mLock);
5557 PlaybackThread *thread = checkPlaybackThread_l(output);
5558
5559 if (thread == NULL) {
5560 return BAD_VALUE;
5561 }
5562
Steve Block3856b092011-10-20 11:56:00 +01005563 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005564 thread->suspend();
5565
5566 return NO_ERROR;
5567}
5568
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005569status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005570{
5571 Mutex::Autolock _l(mLock);
5572 PlaybackThread *thread = checkPlaybackThread_l(output);
5573
5574 if (thread == NULL) {
5575 return BAD_VALUE;
5576 }
5577
Steve Block3856b092011-10-20 11:56:00 +01005578 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005579
5580 thread->restore();
5581
5582 return NO_ERROR;
5583}
5584
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005585audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005586 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005587 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005588 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005589 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005590{
5591 status_t status;
5592 RecordThread *thread = NULL;
5593 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005594 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005595 uint32_t channels = pChannels ? *pChannels : 0;
5596 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005597 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005598 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005599 audio_stream_in_t *inStream;
5600 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005601
5602 if (pDevices == NULL || *pDevices == 0) {
5603 return 0;
5604 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005605
Mathias Agopian65ab4712010-07-14 17:59:35 -07005606 Mutex::Autolock _l(mLock);
5607
Dima Zavin799a70e2011-04-18 16:57:27 -07005608 inHwDev = findSuitableHwDev_l(*pDevices);
5609 if (inHwDev == NULL)
5610 return 0;
5611
Glenn Kasten58f30212012-01-12 12:27:51 -08005612 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005613 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005614 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005615 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005616 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005617 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005618 samplingRate,
5619 format,
5620 channels,
5621 acoustics,
5622 status);
5623
5624 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5625 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5626 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005627 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005628 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005629 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005630 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005631 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005632 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005633 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005634 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005635 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005636 }
5637
Dima Zavin799a70e2011-04-18 16:57:27 -07005638 if (inStream != NULL) {
5639 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5640
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005641 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005642 // Start record thread
5643 // RecorThread require both input and output device indication to forward to audio
5644 // pre processing modules
5645 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5646 thread = new RecordThread(this,
5647 input,
5648 reqSamplingRate,
5649 reqChannels,
5650 id,
5651 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005652 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005653 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005654 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5655 if (pFormat != NULL) *pFormat = format;
5656 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005657
Dima Zavin799a70e2011-04-18 16:57:27 -07005658 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005659
5660 // notify client processes of the new input creation
5661 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5662 return id;
5663 }
5664
5665 return 0;
5666}
5667
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005668status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005669{
5670 // keep strong reference on the record thread so that
5671 // it is not destroyed while exit() is executed
5672 sp <RecordThread> thread;
5673 {
5674 Mutex::Autolock _l(mLock);
5675 thread = checkRecordThread_l(input);
5676 if (thread == NULL) {
5677 return BAD_VALUE;
5678 }
5679
Steve Block3856b092011-10-20 11:56:00 +01005680 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08005681 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005682 mRecordThreads.removeItem(input);
5683 }
5684 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005685 // The thread entity (active unit of execution) is no longer running here,
5686 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005687
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005688 AudioStreamIn *in = thread->clearInput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005689 assert(in != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005690 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005691 in->hwDev->close_input_stream(in->hwDev, in->stream);
5692 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005693
5694 return NO_ERROR;
5695}
5696
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005697status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005698{
5699 Mutex::Autolock _l(mLock);
5700 MixerThread *dstThread = checkMixerThread_l(output);
5701 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005702 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005703 return BAD_VALUE;
5704 }
5705
Steve Block3856b092011-10-20 11:56:00 +01005706 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005707 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5708
Eric Laurent9f6530f2011-08-30 10:18:54 -07005709 dstThread->setStreamValid(stream, true);
5710
Mathias Agopian65ab4712010-07-14 17:59:35 -07005711 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5712 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08005713 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005714 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005715 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005716 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005717 }
Eric Laurentde070132010-07-13 04:45:46 -07005718 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005719
5720 return NO_ERROR;
5721}
5722
5723
5724int AudioFlinger::newAudioSessionId()
5725{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005726 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005727}
5728
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005729void AudioFlinger::acquireAudioSessionId(int audioSession)
5730{
5731 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005732 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005733 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005734 size_t num = mAudioSessionRefs.size();
5735 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005736 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5737 if (ref->sessionid == audioSession && ref->pid == caller) {
5738 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005739 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005740 return;
5741 }
5742 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005743 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5744 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005745}
5746
5747void AudioFlinger::releaseAudioSessionId(int audioSession)
5748{
5749 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005750 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005751 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005752 size_t num = mAudioSessionRefs.size();
5753 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005754 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5755 if (ref->sessionid == audioSession && ref->pid == caller) {
5756 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005757 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005758 if (ref->cnt == 0) {
5759 mAudioSessionRefs.removeAt(i);
5760 delete ref;
5761 purgeStaleEffects_l();
5762 }
5763 return;
5764 }
5765 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005766 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005767}
5768
5769void AudioFlinger::purgeStaleEffects_l() {
5770
Steve Block3856b092011-10-20 11:56:00 +01005771 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005772
5773 Vector< sp<EffectChain> > chains;
5774
5775 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5776 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5777 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5778 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005779 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5780 chains.push(ec);
5781 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005782 }
5783 }
5784 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5785 sp<RecordThread> t = mRecordThreads.valueAt(i);
5786 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5787 sp<EffectChain> ec = t->mEffectChains[j];
5788 chains.push(ec);
5789 }
5790 }
5791
5792 for (size_t i = 0; i < chains.size(); i++) {
5793 sp<EffectChain> ec = chains[i];
5794 int sessionid = ec->sessionId();
5795 sp<ThreadBase> t = ec->mThread.promote();
5796 if (t == 0) {
5797 continue;
5798 }
5799 size_t numsessionrefs = mAudioSessionRefs.size();
5800 bool found = false;
5801 for (size_t k = 0; k < numsessionrefs; k++) {
5802 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5803 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005804 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005805 sessionid, ref->pid, ref->cnt);
5806 found = true;
5807 break;
5808 }
5809 }
5810 if (!found) {
5811 // remove all effects from the chain
5812 while (ec->mEffects.size()) {
5813 sp<EffectModule> effect = ec->mEffects[0];
5814 effect->unPin();
5815 Mutex::Autolock _l (t->mLock);
5816 t->removeEffect_l(effect);
5817 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5818 sp<EffectHandle> handle = effect->mHandles[j].promote();
5819 if (handle != 0) {
5820 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005821 if (handle->mHasControl && handle->mEnabled) {
5822 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5823 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005824 }
5825 }
5826 AudioSystem::unregisterEffect(effect->id());
5827 }
5828 }
5829 }
5830 return;
5831}
5832
Mathias Agopian65ab4712010-07-14 17:59:35 -07005833// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005834AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005835{
Glenn Kastena1117922012-01-26 10:53:32 -08005836 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005837}
5838
5839// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005840AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005841{
5842 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08005843 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005844}
5845
5846// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005847AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005848{
Glenn Kastena1117922012-01-26 10:53:32 -08005849 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005850}
5851
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005852uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005853{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005854 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005855}
5856
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005857AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5858{
5859 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5860 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005861 AudioStreamOut *output = thread->getOutput();
5862 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005863 return thread;
5864 }
5865 }
5866 return NULL;
5867}
5868
5869uint32_t AudioFlinger::primaryOutputDevice_l()
5870{
5871 PlaybackThread *thread = primaryPlaybackThread_l();
5872
5873 if (thread == NULL) {
5874 return 0;
5875 }
5876
5877 return thread->device();
5878}
5879
5880
Mathias Agopian65ab4712010-07-14 17:59:35 -07005881// ----------------------------------------------------------------------------
5882// Effect management
5883// ----------------------------------------------------------------------------
5884
5885
Glenn Kastenf587ba52012-01-26 16:25:10 -08005886status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005887{
5888 Mutex::Autolock _l(mLock);
5889 return EffectQueryNumberEffects(numEffects);
5890}
5891
Glenn Kastenf587ba52012-01-26 16:25:10 -08005892status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005893{
5894 Mutex::Autolock _l(mLock);
5895 return EffectQueryEffect(index, descriptor);
5896}
5897
Glenn Kasten5e92a782012-01-30 07:40:52 -08005898status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08005899 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005900{
5901 Mutex::Autolock _l(mLock);
5902 return EffectGetDescriptor(pUuid, descriptor);
5903}
5904
5905
Mathias Agopian65ab4712010-07-14 17:59:35 -07005906sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5907 effect_descriptor_t *pDesc,
5908 const sp<IEffectClient>& effectClient,
5909 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005910 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005911 int sessionId,
5912 status_t *status,
5913 int *id,
5914 int *enabled)
5915{
5916 status_t lStatus = NO_ERROR;
5917 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005918 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005919
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005920 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005921 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005922
5923 if (pDesc == NULL) {
5924 lStatus = BAD_VALUE;
5925 goto Exit;
5926 }
5927
Eric Laurent84e9a102010-09-23 16:10:16 -07005928 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005929 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005930 lStatus = PERMISSION_DENIED;
5931 goto Exit;
5932 }
5933
Dima Zavinfce7a472011-04-19 22:30:36 -07005934 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005935 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08005936 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005937 lStatus = PERMISSION_DENIED;
5938 goto Exit;
5939 }
5940
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005941 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005942 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005943 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005944 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005945 lStatus = BAD_VALUE;
5946 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005947 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005948 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005949 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005950 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005951 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005952 }
5953 }
5954
Mathias Agopian65ab4712010-07-14 17:59:35 -07005955 {
5956 Mutex::Autolock _l(mLock);
5957
Mathias Agopian65ab4712010-07-14 17:59:35 -07005958
5959 if (!EffectIsNullUuid(&pDesc->uuid)) {
5960 // if uuid is specified, request effect descriptor
5961 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5962 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005963 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005964 goto Exit;
5965 }
5966 } else {
5967 // if uuid is not specified, look for an available implementation
5968 // of the required type in effect factory
5969 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005970 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005971 lStatus = BAD_VALUE;
5972 goto Exit;
5973 }
5974 uint32_t numEffects = 0;
5975 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005976 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005977 bool found = false;
5978
5979 lStatus = EffectQueryNumberEffects(&numEffects);
5980 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005981 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005982 goto Exit;
5983 }
5984 for (uint32_t i = 0; i < numEffects; i++) {
5985 lStatus = EffectQueryEffect(i, &desc);
5986 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005987 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005988 continue;
5989 }
5990 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5991 // If matching type found save effect descriptor. If the session is
5992 // 0 and the effect is not auxiliary, continue enumeration in case
5993 // an auxiliary version of this effect type is available
5994 found = true;
5995 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005996 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005997 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5998 break;
5999 }
6000 }
6001 }
6002 if (!found) {
6003 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00006004 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006005 goto Exit;
6006 }
6007 // For same effect type, chose auxiliary version over insert version if
6008 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07006009 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006010 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
6011 memcpy(&desc, &d, sizeof(effect_descriptor_t));
6012 }
6013 }
6014
6015 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07006016 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006017 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6018 lStatus = INVALID_OPERATION;
6019 goto Exit;
6020 }
6021
Eric Laurent59255e42011-07-27 19:49:51 -07006022 // check recording permission for visualizer
6023 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
6024 !recordingAllowed()) {
6025 lStatus = PERMISSION_DENIED;
6026 goto Exit;
6027 }
6028
Mathias Agopian65ab4712010-07-14 17:59:35 -07006029 // return effect descriptor
6030 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
6031
6032 // If output is not specified try to find a matching audio session ID in one of the
6033 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07006034 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
6035 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006036 // Note: io is never 0 when creating an effect on an input
6037 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006038 // look for the thread where the specified audio session is present
6039 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6040 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006041 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07006042 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07006043 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006044 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006045 if (io == 0) {
6046 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6047 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6048 io = mRecordThreads.keyAt(i);
6049 break;
6050 }
6051 }
6052 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006053 // If no output thread contains the requested session ID, default to
6054 // first output. The effect chain will be moved to the correct output
6055 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006056 if (io == 0 && mPlaybackThreads.size()) {
6057 io = mPlaybackThreads.keyAt(0);
6058 }
Steve Block3856b092011-10-20 11:56:00 +01006059 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006060 }
6061 ThreadBase *thread = checkRecordThread_l(io);
6062 if (thread == NULL) {
6063 thread = checkPlaybackThread_l(io);
6064 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00006065 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006066 lStatus = BAD_VALUE;
6067 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07006068 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006069 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006070
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006071 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006072
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006073 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07006074 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6075 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006076 if (handle != 0 && id != NULL) {
6077 *id = handle->id();
6078 }
6079 }
6080
6081Exit:
6082 if(status) {
6083 *status = lStatus;
6084 }
6085 return handle;
6086}
6087
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006088status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
6089 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07006090{
Steve Block3856b092011-10-20 11:56:00 +01006091 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07006092 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006093 Mutex::Autolock _l(mLock);
6094 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006095 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006096 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006097 }
Eric Laurentde070132010-07-13 04:45:46 -07006098 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6099 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006100 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006101 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006102 }
Eric Laurentde070132010-07-13 04:45:46 -07006103 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6104 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006105 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006106 return BAD_VALUE;
6107 }
6108
6109 Mutex::Autolock _dl(dstThread->mLock);
6110 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07006111 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07006112
Mathias Agopian65ab4712010-07-14 17:59:35 -07006113 return NO_ERROR;
6114}
6115
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006116// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07006117status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07006118 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07006119 AudioFlinger::PlaybackThread *dstThread,
6120 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07006121{
Steve Block3856b092011-10-20 11:56:00 +01006122 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006123 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07006124
Eric Laurent59255e42011-07-27 19:49:51 -07006125 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006126 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006127 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006128 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07006129 return INVALID_OPERATION;
6130 }
6131
Eric Laurent39e94f82010-07-28 01:32:47 -07006132 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07006133 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07006134 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07006135 // removed.
6136 srcThread->removeEffectChain_l(chain);
6137
6138 // transfer all effects one by one so that new effect chain is created on new thread with
6139 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006140 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07006141 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006142 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07006143 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6144 while (effect != 0) {
6145 srcThread->removeEffect_l(effect);
6146 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07006147 // removeEffect_l() has stopped the effect if it was active so it must be restarted
6148 if (effect->state() == EffectModule::ACTIVE ||
6149 effect->state() == EffectModule::STOPPING) {
6150 effect->start();
6151 }
Eric Laurent39e94f82010-07-28 01:32:47 -07006152 // if the move request is not received from audio policy manager, the effect must be
6153 // re-registered with the new strategy and output
6154 if (dstChain == 0) {
6155 dstChain = effect->chain().promote();
6156 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006157 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07006158 srcThread->addEffect_l(effect);
6159 return NO_INIT;
6160 }
6161 strategy = dstChain->strategy();
6162 }
6163 if (reRegister) {
6164 AudioSystem::unregisterEffect(effect->id());
6165 AudioSystem::registerEffect(&effect->desc(),
6166 dstOutput,
6167 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07006168 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07006169 effect->id());
6170 }
Eric Laurentde070132010-07-13 04:45:46 -07006171 effect = chain->getEffectFromId_l(0);
6172 }
6173
6174 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006175}
6176
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006177
Mathias Agopian65ab4712010-07-14 17:59:35 -07006178// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006179sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07006180 const sp<AudioFlinger::Client>& client,
6181 const sp<IEffectClient>& effectClient,
6182 int32_t priority,
6183 int sessionId,
6184 effect_descriptor_t *desc,
6185 int *enabled,
6186 status_t *status
6187 )
6188{
6189 sp<EffectModule> effect;
6190 sp<EffectHandle> handle;
6191 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006192 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07006193 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006194 bool effectCreated = false;
6195 bool effectRegistered = false;
6196
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006197 lStatus = initCheck();
6198 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006199 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006200 goto Exit;
6201 }
6202
6203 // Do not allow effects with session ID 0 on direct output or duplicating threads
6204 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07006205 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006206 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07006207 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006208 lStatus = BAD_VALUE;
6209 goto Exit;
6210 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006211 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08006212 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006213 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006214 desc->name, desc->flags, mType);
6215 lStatus = BAD_VALUE;
6216 goto Exit;
6217 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006218
Steve Block3856b092011-10-20 11:56:00 +01006219 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006220
6221 { // scope for mLock
6222 Mutex::Autolock _l(mLock);
6223
6224 // check for existing effect chain with the requested audio session
6225 chain = getEffectChain_l(sessionId);
6226 if (chain == 0) {
6227 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006228 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006229 chain = new EffectChain(this, sessionId);
6230 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07006231 chain->setStrategy(getStrategyForSession_l(sessionId));
6232 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006233 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07006234 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006235 }
6236
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08006237 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006238
6239 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006240 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006241 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07006242 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006243 if (lStatus != NO_ERROR) {
6244 goto Exit;
6245 }
6246 effectRegistered = true;
6247 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07006248 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006249 lStatus = effect->status();
6250 if (lStatus != NO_ERROR) {
6251 goto Exit;
6252 }
Eric Laurentcab11242010-07-15 12:50:15 -07006253 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006254 if (lStatus != NO_ERROR) {
6255 goto Exit;
6256 }
6257 effectCreated = true;
6258
6259 effect->setDevice(mDevice);
6260 effect->setMode(mAudioFlinger->getMode());
6261 }
6262 // create effect handle and connect it to effect module
6263 handle = new EffectHandle(effect, client, effectClient, priority);
6264 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08006265 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006266 *enabled = (int)effect->isEnabled();
6267 }
6268 }
6269
6270Exit:
6271 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07006272 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006273 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07006274 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006275 }
6276 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07006277 AudioSystem::unregisterEffect(effect->id());
6278 }
6279 if (chainCreated) {
6280 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006281 }
6282 handle.clear();
6283 }
6284
6285 if(status) {
6286 *status = lStatus;
6287 }
6288 return handle;
6289}
6290
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006291sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6292{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006293 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08006294 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006295}
6296
Eric Laurentde070132010-07-13 04:45:46 -07006297// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6298// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006299status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07006300{
6301 // check for existing effect chain with the requested audio session
6302 int sessionId = effect->sessionId();
6303 sp<EffectChain> chain = getEffectChain_l(sessionId);
6304 bool chainCreated = false;
6305
6306 if (chain == 0) {
6307 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006308 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006309 chain = new EffectChain(this, sessionId);
6310 addEffectChain_l(chain);
6311 chain->setStrategy(getStrategyForSession_l(sessionId));
6312 chainCreated = true;
6313 }
Steve Block3856b092011-10-20 11:56:00 +01006314 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006315
6316 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006317 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07006318 this, effect->desc().name, chain.get());
6319 return BAD_VALUE;
6320 }
6321
6322 status_t status = chain->addEffect_l(effect);
6323 if (status != NO_ERROR) {
6324 if (chainCreated) {
6325 removeEffectChain_l(chain);
6326 }
6327 return status;
6328 }
6329
6330 effect->setDevice(mDevice);
6331 effect->setMode(mAudioFlinger->getMode());
6332 return NO_ERROR;
6333}
6334
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006335void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07006336
Steve Block3856b092011-10-20 11:56:00 +01006337 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006338 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07006339 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6340 detachAuxEffect_l(effect->id());
6341 }
6342
6343 sp<EffectChain> chain = effect->chain().promote();
6344 if (chain != 0) {
6345 // remove effect chain if removing last effect
6346 if (chain->removeEffect_l(effect) == 0) {
6347 removeEffectChain_l(chain);
6348 }
6349 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00006350 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006351 }
6352}
6353
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006354void AudioFlinger::ThreadBase::lockEffectChains_l(
6355 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
6356{
6357 effectChains = mEffectChains;
6358 for (size_t i = 0; i < mEffectChains.size(); i++) {
6359 mEffectChains[i]->lock();
6360 }
6361}
6362
6363void AudioFlinger::ThreadBase::unlockEffectChains(
6364 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
6365{
6366 for (size_t i = 0; i < effectChains.size(); i++) {
6367 effectChains[i]->unlock();
6368 }
6369}
6370
6371sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6372{
6373 Mutex::Autolock _l(mLock);
6374 return getEffectChain_l(sessionId);
6375}
6376
6377sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6378{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006379 size_t size = mEffectChains.size();
6380 for (size_t i = 0; i < size; i++) {
6381 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08006382 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006383 }
6384 }
Glenn Kasten090f0192012-01-30 13:00:02 -08006385 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006386}
6387
Glenn Kastenf78aee72012-01-04 11:00:47 -08006388void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006389{
6390 Mutex::Autolock _l(mLock);
6391 size_t size = mEffectChains.size();
6392 for (size_t i = 0; i < size; i++) {
6393 mEffectChains[i]->setMode_l(mode);
6394 }
6395}
6396
6397void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006398 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08006399 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07006400
Mathias Agopian65ab4712010-07-14 17:59:35 -07006401 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006402 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006403 // delete the effect module if removing last handle on it
6404 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006405 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006406 removeEffect_l(effect);
6407 AudioSystem::unregisterEffect(effect->id());
6408 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006409 }
6410}
6411
6412status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6413{
6414 int session = chain->sessionId();
6415 int16_t *buffer = mMixBuffer;
6416 bool ownsBuffer = false;
6417
Steve Block3856b092011-10-20 11:56:00 +01006418 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006419 if (session > 0) {
6420 // Only one effect chain can be present in direct output thread and it uses
6421 // the mix buffer as input
6422 if (mType != DIRECT) {
6423 size_t numSamples = mFrameCount * mChannelCount;
6424 buffer = new int16_t[numSamples];
6425 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01006426 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006427 ownsBuffer = true;
6428 }
6429
6430 // Attach all tracks with same session ID to this chain.
6431 for (size_t i = 0; i < mTracks.size(); ++i) {
6432 sp<Track> track = mTracks[i];
6433 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006434 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006435 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006436 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006437 }
6438 }
6439
6440 // indicate all active tracks in the chain
6441 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6442 sp<Track> track = mActiveTracks[i].promote();
6443 if (track == 0) continue;
6444 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006445 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07006446 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006447 }
6448 }
6449 }
6450
6451 chain->setInBuffer(buffer, ownsBuffer);
6452 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006453 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006454 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006455 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6456 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006457 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006458 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6459 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006460 // Effect chain for other sessions are inserted at beginning of effect
6461 // chains list to be processed before output mix effects. Relative order between other
6462 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006463 size_t size = mEffectChains.size();
6464 size_t i = 0;
6465 for (i = 0; i < size; i++) {
6466 if (mEffectChains[i]->sessionId() < session) break;
6467 }
6468 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006469 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006470
6471 return NO_ERROR;
6472}
6473
6474size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6475{
6476 int session = chain->sessionId();
6477
Steve Block3856b092011-10-20 11:56:00 +01006478 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006479
6480 for (size_t i = 0; i < mEffectChains.size(); i++) {
6481 if (chain == mEffectChains[i]) {
6482 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006483 // detach all active tracks from the chain
6484 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6485 sp<Track> track = mActiveTracks[i].promote();
6486 if (track == 0) continue;
6487 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006488 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006489 chain.get(), session);
6490 chain->decActiveTrackCnt();
6491 }
6492 }
6493
Mathias Agopian65ab4712010-07-14 17:59:35 -07006494 // detach all tracks with same session ID from this chain
6495 for (size_t i = 0; i < mTracks.size(); ++i) {
6496 sp<Track> track = mTracks[i];
6497 if (session == track->sessionId()) {
6498 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006499 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006500 }
6501 }
Eric Laurentde070132010-07-13 04:45:46 -07006502 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006503 }
6504 }
6505 return mEffectChains.size();
6506}
6507
Eric Laurentde070132010-07-13 04:45:46 -07006508status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6509 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006510{
6511 Mutex::Autolock _l(mLock);
6512 return attachAuxEffect_l(track, EffectId);
6513}
6514
Eric Laurentde070132010-07-13 04:45:46 -07006515status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6516 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006517{
6518 status_t status = NO_ERROR;
6519
6520 if (EffectId == 0) {
6521 track->setAuxBuffer(0, NULL);
6522 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006523 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6524 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006525 if (effect != 0) {
6526 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6527 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6528 } else {
6529 status = INVALID_OPERATION;
6530 }
6531 } else {
6532 status = BAD_VALUE;
6533 }
6534 }
6535 return status;
6536}
6537
6538void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6539{
6540 for (size_t i = 0; i < mTracks.size(); ++i) {
6541 sp<Track> track = mTracks[i];
6542 if (track->auxEffectId() == effectId) {
6543 attachAuxEffect_l(track, 0);
6544 }
6545 }
6546}
6547
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006548status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6549{
6550 // only one chain per input thread
6551 if (mEffectChains.size() != 0) {
6552 return INVALID_OPERATION;
6553 }
Steve Block3856b092011-10-20 11:56:00 +01006554 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006555
6556 chain->setInBuffer(NULL);
6557 chain->setOutBuffer(NULL);
6558
Eric Laurent59255e42011-07-27 19:49:51 -07006559 checkSuspendOnAddEffectChain_l(chain);
6560
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006561 mEffectChains.add(chain);
6562
6563 return NO_ERROR;
6564}
6565
6566size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6567{
Steve Block3856b092011-10-20 11:56:00 +01006568 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006569 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006570 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6571 chain.get(), mEffectChains.size(), this);
6572 if (mEffectChains.size() == 1) {
6573 mEffectChains.removeAt(0);
6574 }
6575 return 0;
6576}
6577
Mathias Agopian65ab4712010-07-14 17:59:35 -07006578// ----------------------------------------------------------------------------
6579// EffectModule implementation
6580// ----------------------------------------------------------------------------
6581
6582#undef LOG_TAG
6583#define LOG_TAG "AudioFlinger::EffectModule"
6584
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006585AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006586 const wp<AudioFlinger::EffectChain>& chain,
6587 effect_descriptor_t *desc,
6588 int id,
6589 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006590 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006591 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006592{
Steve Block3856b092011-10-20 11:56:00 +01006593 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006594 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006595 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006596 return;
6597 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006598
6599 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6600
6601 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006602 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006603
6604 if (mStatus != NO_ERROR) {
6605 return;
6606 }
6607 lStatus = init();
6608 if (lStatus < 0) {
6609 mStatus = lStatus;
6610 goto Error;
6611 }
6612
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006613 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6614 mPinned = true;
6615 }
Steve Block3856b092011-10-20 11:56:00 +01006616 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006617 return;
6618Error:
6619 EffectRelease(mEffectInterface);
6620 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006621 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006622}
6623
6624AudioFlinger::EffectModule::~EffectModule()
6625{
Steve Block3856b092011-10-20 11:56:00 +01006626 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006627 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006628 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6629 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6630 sp<ThreadBase> thread = mThread.promote();
6631 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006632 audio_stream_t *stream = thread->stream();
6633 if (stream != NULL) {
6634 stream->remove_audio_effect(stream, mEffectInterface);
6635 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006636 }
6637 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006638 // release effect engine
6639 EffectRelease(mEffectInterface);
6640 }
6641}
6642
Glenn Kasten435dbe62012-01-30 10:15:48 -08006643status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006644{
6645 status_t status;
6646
6647 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006648 int priority = handle->priority();
6649 size_t size = mHandles.size();
6650 sp<EffectHandle> h;
6651 size_t i;
6652 for (i = 0; i < size; i++) {
6653 h = mHandles[i].promote();
6654 if (h == 0) continue;
6655 if (h->priority() <= priority) break;
6656 }
6657 // if inserted in first place, move effect control from previous owner to this handle
6658 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006659 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006660 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006661 enabled = h->enabled();
6662 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006663 }
Eric Laurent59255e42011-07-27 19:49:51 -07006664 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006665 status = NO_ERROR;
6666 } else {
6667 status = ALREADY_EXISTS;
6668 }
Steve Block3856b092011-10-20 11:56:00 +01006669 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006670 mHandles.insertAt(handle, i);
6671 return status;
6672}
6673
6674size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6675{
6676 Mutex::Autolock _l(mLock);
6677 size_t size = mHandles.size();
6678 size_t i;
6679 for (i = 0; i < size; i++) {
6680 if (mHandles[i] == handle) break;
6681 }
6682 if (i == size) {
6683 return size;
6684 }
Steve Block3856b092011-10-20 11:56:00 +01006685 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006686
6687 bool enabled = false;
6688 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006689 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006690 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006691 enabled = hdl->enabled();
6692 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006693 mHandles.removeAt(i);
6694 size = mHandles.size();
6695 // if removed from first place, move effect control from this handle to next in line
6696 if (i == 0 && size != 0) {
6697 sp<EffectHandle> h = mHandles[0].promote();
6698 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006699 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006700 }
6701 }
6702
Eric Laurentec437d82011-07-26 20:54:46 -07006703 // Prevent calls to process() and other functions on effect interface from now on.
6704 // The effect engine will be released by the destructor when the last strong reference on
6705 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006706 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006707 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006708 }
6709
Mathias Agopian65ab4712010-07-14 17:59:35 -07006710 return size;
6711}
6712
Eric Laurent59255e42011-07-27 19:49:51 -07006713sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6714{
6715 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08006716 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07006717}
6718
Glenn Kasten58123c32012-02-03 10:32:24 -08006719void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006720{
Glenn Kasten90bebef2012-01-27 15:24:38 -08006721 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006722 // keep a strong reference on this EffectModule to avoid calling the
6723 // destructor before we exit
6724 sp<EffectModule> keep(this);
6725 {
6726 sp<ThreadBase> thread = mThread.promote();
6727 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006728 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006729 }
6730 }
6731}
6732
6733void AudioFlinger::EffectModule::updateState() {
6734 Mutex::Autolock _l(mLock);
6735
6736 switch (mState) {
6737 case RESTART:
6738 reset_l();
6739 // FALL THROUGH
6740
6741 case STARTING:
6742 // clear auxiliary effect input buffer for next accumulation
6743 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6744 memset(mConfig.inputCfg.buffer.raw,
6745 0,
6746 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6747 }
6748 start_l();
6749 mState = ACTIVE;
6750 break;
6751 case STOPPING:
6752 stop_l();
6753 mDisableWaitCnt = mMaxDisableWaitCnt;
6754 mState = STOPPED;
6755 break;
6756 case STOPPED:
6757 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6758 // turn off sequence.
6759 if (--mDisableWaitCnt == 0) {
6760 reset_l();
6761 mState = IDLE;
6762 }
6763 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006764 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006765 break;
6766 }
6767}
6768
6769void AudioFlinger::EffectModule::process()
6770{
6771 Mutex::Autolock _l(mLock);
6772
Eric Laurentec437d82011-07-26 20:54:46 -07006773 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006774 mConfig.inputCfg.buffer.raw == NULL ||
6775 mConfig.outputCfg.buffer.raw == NULL) {
6776 return;
6777 }
6778
Eric Laurent8f45bd72010-08-31 13:50:07 -07006779 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006780 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6781 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006782 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006783 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006784 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006785 }
6786
6787 // do the actual processing in the effect engine
6788 int ret = (*mEffectInterface)->process(mEffectInterface,
6789 &mConfig.inputCfg.buffer,
6790 &mConfig.outputCfg.buffer);
6791
6792 // force transition to IDLE state when engine is ready
6793 if (mState == STOPPED && ret == -ENODATA) {
6794 mDisableWaitCnt = 1;
6795 }
6796
6797 // clear auxiliary effect input buffer for next accumulation
6798 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006799 memset(mConfig.inputCfg.buffer.raw, 0,
6800 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006801 }
6802 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006803 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6804 // If an insert effect is idle and input buffer is different from output buffer,
6805 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006806 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006807 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006808 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6809 int16_t *in = mConfig.inputCfg.buffer.s16;
6810 int16_t *out = mConfig.outputCfg.buffer.s16;
6811 for (size_t i = 0; i < frameCnt; i++) {
6812 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006813 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006814 }
6815 }
6816}
6817
6818void AudioFlinger::EffectModule::reset_l()
6819{
6820 if (mEffectInterface == NULL) {
6821 return;
6822 }
6823 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6824}
6825
6826status_t AudioFlinger::EffectModule::configure()
6827{
6828 uint32_t channels;
6829 if (mEffectInterface == NULL) {
6830 return NO_INIT;
6831 }
6832
6833 sp<ThreadBase> thread = mThread.promote();
6834 if (thread == 0) {
6835 return DEAD_OBJECT;
6836 }
6837
6838 // TODO: handle configuration of effects replacing track process
6839 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006840 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006841 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006842 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006843 }
6844
6845 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006846 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006847 } else {
6848 mConfig.inputCfg.channels = channels;
6849 }
6850 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006851 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6852 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006853 mConfig.inputCfg.samplingRate = thread->sampleRate();
6854 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6855 mConfig.inputCfg.bufferProvider.cookie = NULL;
6856 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6857 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6858 mConfig.outputCfg.bufferProvider.cookie = NULL;
6859 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6860 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6861 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6862 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006863 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006864 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006865 // - in other sessions:
6866 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6867 // other effect: overwrites output buffer: input buffer == output buffer
6868 // Auxiliary effect:
6869 // accumulates in output buffer: input buffer != output buffer
6870 // Therefore: accumulate <=> input buffer != output buffer
6871 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6872 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6873 } else {
6874 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6875 }
6876 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6877 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6878 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6879 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6880
Steve Block3856b092011-10-20 11:56:00 +01006881 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006882 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6883
Mathias Agopian65ab4712010-07-14 17:59:35 -07006884 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006885 uint32_t size = sizeof(int);
6886 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006887 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006888 sizeof(effect_config_t),
6889 &mConfig,
6890 &size,
6891 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006892 if (status == 0) {
6893 status = cmdStatus;
6894 }
6895
6896 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6897 (1000 * mConfig.outputCfg.buffer.frameCount);
6898
6899 return status;
6900}
6901
6902status_t AudioFlinger::EffectModule::init()
6903{
6904 Mutex::Autolock _l(mLock);
6905 if (mEffectInterface == NULL) {
6906 return NO_INIT;
6907 }
6908 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006909 uint32_t size = sizeof(status_t);
6910 status_t status = (*mEffectInterface)->command(mEffectInterface,
6911 EFFECT_CMD_INIT,
6912 0,
6913 NULL,
6914 &size,
6915 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006916 if (status == 0) {
6917 status = cmdStatus;
6918 }
6919 return status;
6920}
6921
Eric Laurentec35a142011-10-05 17:42:25 -07006922status_t AudioFlinger::EffectModule::start()
6923{
6924 Mutex::Autolock _l(mLock);
6925 return start_l();
6926}
6927
Mathias Agopian65ab4712010-07-14 17:59:35 -07006928status_t AudioFlinger::EffectModule::start_l()
6929{
6930 if (mEffectInterface == NULL) {
6931 return NO_INIT;
6932 }
6933 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006934 uint32_t size = sizeof(status_t);
6935 status_t status = (*mEffectInterface)->command(mEffectInterface,
6936 EFFECT_CMD_ENABLE,
6937 0,
6938 NULL,
6939 &size,
6940 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006941 if (status == 0) {
6942 status = cmdStatus;
6943 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006944 if (status == 0 &&
6945 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6946 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6947 sp<ThreadBase> thread = mThread.promote();
6948 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006949 audio_stream_t *stream = thread->stream();
6950 if (stream != NULL) {
6951 stream->add_audio_effect(stream, mEffectInterface);
6952 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006953 }
6954 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006955 return status;
6956}
6957
Eric Laurentec437d82011-07-26 20:54:46 -07006958status_t AudioFlinger::EffectModule::stop()
6959{
6960 Mutex::Autolock _l(mLock);
6961 return stop_l();
6962}
6963
Mathias Agopian65ab4712010-07-14 17:59:35 -07006964status_t AudioFlinger::EffectModule::stop_l()
6965{
6966 if (mEffectInterface == NULL) {
6967 return NO_INIT;
6968 }
6969 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006970 uint32_t size = sizeof(status_t);
6971 status_t status = (*mEffectInterface)->command(mEffectInterface,
6972 EFFECT_CMD_DISABLE,
6973 0,
6974 NULL,
6975 &size,
6976 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006977 if (status == 0) {
6978 status = cmdStatus;
6979 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006980 if (status == 0 &&
6981 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6982 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6983 sp<ThreadBase> thread = mThread.promote();
6984 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006985 audio_stream_t *stream = thread->stream();
6986 if (stream != NULL) {
6987 stream->remove_audio_effect(stream, mEffectInterface);
6988 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006989 }
6990 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006991 return status;
6992}
6993
Eric Laurent25f43952010-07-28 05:40:18 -07006994status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6995 uint32_t cmdSize,
6996 void *pCmdData,
6997 uint32_t *replySize,
6998 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006999{
7000 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007001// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007002
Eric Laurentec437d82011-07-26 20:54:46 -07007003 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007004 return NO_INIT;
7005 }
Eric Laurent25f43952010-07-28 05:40:18 -07007006 status_t status = (*mEffectInterface)->command(mEffectInterface,
7007 cmdCode,
7008 cmdSize,
7009 pCmdData,
7010 replySize,
7011 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007012 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07007013 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007014 for (size_t i = 1; i < mHandles.size(); i++) {
7015 sp<EffectHandle> h = mHandles[i].promote();
7016 if (h != 0) {
7017 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
7018 }
7019 }
7020 }
7021 return status;
7022}
7023
7024status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
7025{
Eric Laurentdb7c0792011-08-10 10:37:50 -07007026
Mathias Agopian65ab4712010-07-14 17:59:35 -07007027 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007028 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007029
7030 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007031 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
7032 if (enabled && status != NO_ERROR) {
7033 return status;
7034 }
7035
Mathias Agopian65ab4712010-07-14 17:59:35 -07007036 switch (mState) {
7037 // going from disabled to enabled
7038 case IDLE:
7039 mState = STARTING;
7040 break;
7041 case STOPPED:
7042 mState = RESTART;
7043 break;
7044 case STOPPING:
7045 mState = ACTIVE;
7046 break;
7047
7048 // going from enabled to disabled
7049 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007050 mState = STOPPED;
7051 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007052 case STARTING:
7053 mState = IDLE;
7054 break;
7055 case ACTIVE:
7056 mState = STOPPING;
7057 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007058 case DESTROYED:
7059 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007060 }
7061 for (size_t i = 1; i < mHandles.size(); i++) {
7062 sp<EffectHandle> h = mHandles[i].promote();
7063 if (h != 0) {
7064 h->setEnabled(enabled);
7065 }
7066 }
7067 }
7068 return NO_ERROR;
7069}
7070
Glenn Kastenc59c0042012-02-02 14:06:11 -08007071bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007072{
7073 switch (mState) {
7074 case RESTART:
7075 case STARTING:
7076 case ACTIVE:
7077 return true;
7078 case IDLE:
7079 case STOPPING:
7080 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07007081 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07007082 default:
7083 return false;
7084 }
7085}
7086
Glenn Kastenc59c0042012-02-02 14:06:11 -08007087bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07007088{
7089 switch (mState) {
7090 case RESTART:
7091 case ACTIVE:
7092 case STOPPING:
7093 case STOPPED:
7094 return true;
7095 case IDLE:
7096 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07007097 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007098 default:
7099 return false;
7100 }
7101}
7102
Mathias Agopian65ab4712010-07-14 17:59:35 -07007103status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7104{
7105 Mutex::Autolock _l(mLock);
7106 status_t status = NO_ERROR;
7107
7108 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7109 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07007110 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07007111 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7112 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007113 status_t cmdStatus;
7114 uint32_t volume[2];
7115 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07007116 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007117 volume[0] = *left;
7118 volume[1] = *right;
7119 if (controller) {
7120 pVolume = volume;
7121 }
Eric Laurent25f43952010-07-28 05:40:18 -07007122 status = (*mEffectInterface)->command(mEffectInterface,
7123 EFFECT_CMD_SET_VOLUME,
7124 size,
7125 volume,
7126 &size,
7127 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007128 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7129 *left = volume[0];
7130 *right = volume[1];
7131 }
7132 }
7133 return status;
7134}
7135
7136status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7137{
7138 Mutex::Autolock _l(mLock);
7139 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007140 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7141 // audio pre processing modules on RecordThread can receive both output and
7142 // input device indication in the same call
7143 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7144 if (dev) {
7145 status_t cmdStatus;
7146 uint32_t size = sizeof(status_t);
7147
7148 status = (*mEffectInterface)->command(mEffectInterface,
7149 EFFECT_CMD_SET_DEVICE,
7150 sizeof(uint32_t),
7151 &dev,
7152 &size,
7153 &cmdStatus);
7154 if (status == NO_ERROR) {
7155 status = cmdStatus;
7156 }
7157 }
7158 dev = device & AUDIO_DEVICE_IN_ALL;
7159 if (dev) {
7160 status_t cmdStatus;
7161 uint32_t size = sizeof(status_t);
7162
7163 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7164 EFFECT_CMD_SET_INPUT_DEVICE,
7165 sizeof(uint32_t),
7166 &dev,
7167 &size,
7168 &cmdStatus);
7169 if (status2 == NO_ERROR) {
7170 status2 = cmdStatus;
7171 }
7172 if (status == NO_ERROR) {
7173 status = status2;
7174 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007175 }
7176 }
7177 return status;
7178}
7179
Glenn Kastenf78aee72012-01-04 11:00:47 -08007180status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007181{
7182 Mutex::Autolock _l(mLock);
7183 status_t status = NO_ERROR;
7184 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007185 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007186 uint32_t size = sizeof(status_t);
7187 status = (*mEffectInterface)->command(mEffectInterface,
7188 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08007189 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07007190 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07007191 &size,
7192 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007193 if (status == NO_ERROR) {
7194 status = cmdStatus;
7195 }
7196 }
7197 return status;
7198}
7199
Eric Laurent59255e42011-07-27 19:49:51 -07007200void AudioFlinger::EffectModule::setSuspended(bool suspended)
7201{
7202 Mutex::Autolock _l(mLock);
7203 mSuspended = suspended;
7204}
Glenn Kastena3a85482012-01-04 11:01:11 -08007205
7206bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07007207{
7208 Mutex::Autolock _l(mLock);
7209 return mSuspended;
7210}
7211
Mathias Agopian65ab4712010-07-14 17:59:35 -07007212status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7213{
7214 const size_t SIZE = 256;
7215 char buffer[SIZE];
7216 String8 result;
7217
7218 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7219 result.append(buffer);
7220
7221 bool locked = tryLock(mLock);
7222 // failed to lock - AudioFlinger is probably deadlocked
7223 if (!locked) {
7224 result.append("\t\tCould not lock Fx mutex:\n");
7225 }
7226
7227 result.append("\t\tSession Status State Engine:\n");
7228 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7229 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7230 result.append(buffer);
7231
7232 result.append("\t\tDescriptor:\n");
7233 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7234 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7235 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7236 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7237 result.append(buffer);
7238 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7239 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7240 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7241 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7242 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07007243 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007244 mDescriptor.apiVersion,
7245 mDescriptor.flags);
7246 result.append(buffer);
7247 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7248 mDescriptor.name);
7249 result.append(buffer);
7250 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7251 mDescriptor.implementor);
7252 result.append(buffer);
7253
7254 result.append("\t\t- Input configuration:\n");
7255 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7256 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7257 (uint32_t)mConfig.inputCfg.buffer.raw,
7258 mConfig.inputCfg.buffer.frameCount,
7259 mConfig.inputCfg.samplingRate,
7260 mConfig.inputCfg.channels,
7261 mConfig.inputCfg.format);
7262 result.append(buffer);
7263
7264 result.append("\t\t- Output configuration:\n");
7265 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7266 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7267 (uint32_t)mConfig.outputCfg.buffer.raw,
7268 mConfig.outputCfg.buffer.frameCount,
7269 mConfig.outputCfg.samplingRate,
7270 mConfig.outputCfg.channels,
7271 mConfig.outputCfg.format);
7272 result.append(buffer);
7273
7274 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7275 result.append(buffer);
7276 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7277 for (size_t i = 0; i < mHandles.size(); ++i) {
7278 sp<EffectHandle> handle = mHandles[i].promote();
7279 if (handle != 0) {
7280 handle->dump(buffer, SIZE);
7281 result.append(buffer);
7282 }
7283 }
7284
7285 result.append("\n");
7286
7287 write(fd, result.string(), result.length());
7288
7289 if (locked) {
7290 mLock.unlock();
7291 }
7292
7293 return NO_ERROR;
7294}
7295
7296// ----------------------------------------------------------------------------
7297// EffectHandle implementation
7298// ----------------------------------------------------------------------------
7299
7300#undef LOG_TAG
7301#define LOG_TAG "AudioFlinger::EffectHandle"
7302
7303AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7304 const sp<AudioFlinger::Client>& client,
7305 const sp<IEffectClient>& effectClient,
7306 int32_t priority)
7307 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007308 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007309 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007310{
Steve Block3856b092011-10-20 11:56:00 +01007311 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007312
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007313 if (client == 0) {
7314 return;
7315 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007316 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7317 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7318 if (mCblkMemory != 0) {
7319 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7320
Glenn Kastena0d68332012-01-27 16:47:15 -08007321 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007322 new(mCblk) effect_param_cblk_t();
7323 mBuffer = (uint8_t *)mCblk + bufOffset;
7324 }
7325 } else {
Steve Block29357bc2012-01-06 19:20:56 +00007326 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007327 return;
7328 }
7329}
7330
7331AudioFlinger::EffectHandle::~EffectHandle()
7332{
Steve Block3856b092011-10-20 11:56:00 +01007333 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007334 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01007335 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007336}
7337
7338status_t AudioFlinger::EffectHandle::enable()
7339{
Steve Block3856b092011-10-20 11:56:00 +01007340 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007341 if (!mHasControl) return INVALID_OPERATION;
7342 if (mEffect == 0) return DEAD_OBJECT;
7343
Eric Laurentdb7c0792011-08-10 10:37:50 -07007344 if (mEnabled) {
7345 return NO_ERROR;
7346 }
7347
Eric Laurent59255e42011-07-27 19:49:51 -07007348 mEnabled = true;
7349
7350 sp<ThreadBase> thread = mEffect->thread().promote();
7351 if (thread != 0) {
7352 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7353 }
7354
7355 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7356 if (mEffect->suspended()) {
7357 return NO_ERROR;
7358 }
7359
Eric Laurentdb7c0792011-08-10 10:37:50 -07007360 status_t status = mEffect->setEnabled(true);
7361 if (status != NO_ERROR) {
7362 if (thread != 0) {
7363 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7364 }
7365 mEnabled = false;
7366 }
7367 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007368}
7369
7370status_t AudioFlinger::EffectHandle::disable()
7371{
Steve Block3856b092011-10-20 11:56:00 +01007372 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007373 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07007374 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007375
Eric Laurentdb7c0792011-08-10 10:37:50 -07007376 if (!mEnabled) {
7377 return NO_ERROR;
7378 }
Eric Laurent59255e42011-07-27 19:49:51 -07007379 mEnabled = false;
7380
7381 if (mEffect->suspended()) {
7382 return NO_ERROR;
7383 }
7384
7385 status_t status = mEffect->setEnabled(false);
7386
7387 sp<ThreadBase> thread = mEffect->thread().promote();
7388 if (thread != 0) {
7389 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7390 }
7391
7392 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007393}
7394
7395void AudioFlinger::EffectHandle::disconnect()
7396{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007397 disconnect(true);
7398}
7399
Glenn Kasten58123c32012-02-03 10:32:24 -08007400void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007401{
Glenn Kasten58123c32012-02-03 10:32:24 -08007402 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007403 if (mEffect == 0) {
7404 return;
7405 }
Glenn Kasten58123c32012-02-03 10:32:24 -08007406 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07007407
Eric Laurenta85a74a2011-10-19 11:44:54 -07007408 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007409 sp<ThreadBase> thread = mEffect->thread().promote();
7410 if (thread != 0) {
7411 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7412 }
Eric Laurent59255e42011-07-27 19:49:51 -07007413 }
7414
Mathias Agopian65ab4712010-07-14 17:59:35 -07007415 // release sp on module => module destructor can be called now
7416 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007417 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08007418 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08007419 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007420 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7421 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08007422 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007423 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07007424 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7425 mClient.clear();
7426 }
7427}
7428
Eric Laurent25f43952010-07-28 05:40:18 -07007429status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7430 uint32_t cmdSize,
7431 void *pCmdData,
7432 uint32_t *replySize,
7433 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007434{
Steve Block3856b092011-10-20 11:56:00 +01007435// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07007436// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007437
7438 // only get parameter command is permitted for applications not controlling the effect
7439 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7440 return INVALID_OPERATION;
7441 }
7442 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007443 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007444
7445 // handle commands that are not forwarded transparently to effect engine
7446 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7447 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7448 // no risk to block the whole media server process or mixer threads is we are stuck here
7449 Mutex::Autolock _l(mCblk->lock);
7450 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7451 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7452 mCblk->serverIndex = 0;
7453 mCblk->clientIndex = 0;
7454 return BAD_VALUE;
7455 }
7456 status_t status = NO_ERROR;
7457 while (mCblk->serverIndex < mCblk->clientIndex) {
7458 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007459 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007460 int *p = (int *)(mBuffer + mCblk->serverIndex);
7461 int size = *p++;
7462 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007463 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007464 break;
7465 }
7466 effect_param_t *param = (effect_param_t *)p;
7467 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007468 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007469 mCblk->serverIndex += size;
7470 continue;
7471 }
Eric Laurent25f43952010-07-28 05:40:18 -07007472 uint32_t psize = sizeof(effect_param_t) +
7473 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7474 param->vsize;
7475 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7476 psize,
7477 p,
7478 &rsize,
7479 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007480 // stop at first error encountered
7481 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007482 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007483 *(int *)pReplyData = reply;
7484 break;
7485 } else if (reply != NO_ERROR) {
7486 *(int *)pReplyData = reply;
7487 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007488 }
7489 mCblk->serverIndex += size;
7490 }
7491 mCblk->serverIndex = 0;
7492 mCblk->clientIndex = 0;
7493 return status;
7494 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007495 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007496 return enable();
7497 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007498 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007499 return disable();
7500 }
7501
7502 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7503}
7504
Eric Laurent59255e42011-07-27 19:49:51 -07007505void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007506{
Steve Block3856b092011-10-20 11:56:00 +01007507 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007508
7509 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007510 mEnabled = enabled;
7511
Mathias Agopian65ab4712010-07-14 17:59:35 -07007512 if (signal && mEffectClient != 0) {
7513 mEffectClient->controlStatusChanged(hasControl);
7514 }
7515}
7516
Eric Laurent25f43952010-07-28 05:40:18 -07007517void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7518 uint32_t cmdSize,
7519 void *pCmdData,
7520 uint32_t replySize,
7521 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007522{
7523 if (mEffectClient != 0) {
7524 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7525 }
7526}
7527
7528
7529
7530void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7531{
7532 if (mEffectClient != 0) {
7533 mEffectClient->enableStatusChanged(enabled);
7534 }
7535}
7536
7537status_t AudioFlinger::EffectHandle::onTransact(
7538 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7539{
7540 return BnEffect::onTransact(code, data, reply, flags);
7541}
7542
7543
7544void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7545{
Glenn Kastena0d68332012-01-27 16:47:15 -08007546 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007547
7548 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08007549 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007550 mPriority,
7551 mHasControl,
7552 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007553 mCblk ? mCblk->clientIndex : 0,
7554 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007555 );
7556
7557 if (locked) {
7558 mCblk->lock.unlock();
7559 }
7560}
7561
7562#undef LOG_TAG
7563#define LOG_TAG "AudioFlinger::EffectChain"
7564
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007565AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007566 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007567 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007568 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7569 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007570{
Dima Zavinfce7a472011-04-19 22:30:36 -07007571 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007572 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007573 return;
7574 }
7575 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7576 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007577}
7578
7579AudioFlinger::EffectChain::~EffectChain()
7580{
7581 if (mOwnInBuffer) {
7582 delete mInBuffer;
7583 }
7584
7585}
7586
Eric Laurent59255e42011-07-27 19:49:51 -07007587// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007588sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007589{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007590 size_t size = mEffects.size();
7591
7592 for (size_t i = 0; i < size; i++) {
7593 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007594 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007595 }
7596 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007597 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007598}
7599
Eric Laurent59255e42011-07-27 19:49:51 -07007600// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007601sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007602{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007603 size_t size = mEffects.size();
7604
7605 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007606 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7607 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007608 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007609 }
7610 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007611 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007612}
7613
Eric Laurent59255e42011-07-27 19:49:51 -07007614// getEffectFromType_l() must be called with ThreadBase::mLock held
7615sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7616 const effect_uuid_t *type)
7617{
Eric Laurent59255e42011-07-27 19:49:51 -07007618 size_t size = mEffects.size();
7619
7620 for (size_t i = 0; i < size; i++) {
7621 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007622 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007623 }
7624 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007625 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007626}
7627
Mathias Agopian65ab4712010-07-14 17:59:35 -07007628// Must be called with EffectChain::mLock locked
7629void AudioFlinger::EffectChain::process_l()
7630{
Eric Laurentdac69112010-09-28 14:09:57 -07007631 sp<ThreadBase> thread = mThread.promote();
7632 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007633 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007634 return;
7635 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007636 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7637 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007638 // always process effects unless no more tracks are on the session and the effect tail
7639 // has been rendered
7640 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007641 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007642 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007643
Eric Laurent544fe9b2011-11-11 15:42:52 -08007644 if (!tracksOnSession && mTailBufferCount == 0) {
7645 doProcess = false;
7646 }
7647
7648 if (activeTrackCnt() == 0) {
7649 // if no track is active and the effect tail has not been rendered,
7650 // the input buffer must be cleared here as the mixer process will not do it
7651 if (tracksOnSession || mTailBufferCount > 0) {
7652 size_t numSamples = thread->frameCount() * thread->channelCount();
7653 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7654 if (mTailBufferCount > 0) {
7655 mTailBufferCount--;
7656 }
7657 }
7658 }
Eric Laurentdac69112010-09-28 14:09:57 -07007659 }
7660
Mathias Agopian65ab4712010-07-14 17:59:35 -07007661 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007662 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007663 for (size_t i = 0; i < size; i++) {
7664 mEffects[i]->process();
7665 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007666 }
7667 for (size_t i = 0; i < size; i++) {
7668 mEffects[i]->updateState();
7669 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007670}
7671
Eric Laurentcab11242010-07-15 12:50:15 -07007672// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007673status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007674{
7675 effect_descriptor_t desc = effect->desc();
7676 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7677
7678 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007679 effect->setChain(this);
7680 sp<ThreadBase> thread = mThread.promote();
7681 if (thread == 0) {
7682 return NO_INIT;
7683 }
7684 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007685
7686 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7687 // Auxiliary effects are inserted at the beginning of mEffects vector as
7688 // they are processed first and accumulated in chain input buffer
7689 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007690
Mathias Agopian65ab4712010-07-14 17:59:35 -07007691 // the input buffer for auxiliary effect contains mono samples in
7692 // 32 bit format. This is to avoid saturation in AudoMixer
7693 // accumulation stage. Saturation is done in EffectModule::process() before
7694 // calling the process in effect engine
7695 size_t numSamples = thread->frameCount();
7696 int32_t *buffer = new int32_t[numSamples];
7697 memset(buffer, 0, numSamples * sizeof(int32_t));
7698 effect->setInBuffer((int16_t *)buffer);
7699 // auxiliary effects output samples to chain input buffer for further processing
7700 // by insert effects
7701 effect->setOutBuffer(mInBuffer);
7702 } else {
7703 // Insert effects are inserted at the end of mEffects vector as they are processed
7704 // after track and auxiliary effects.
7705 // Insert effect order as a function of indicated preference:
7706 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7707 // another effect is present
7708 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7709 // last effect claiming first position
7710 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7711 // first effect claiming last position
7712 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7713 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7714 // already present
7715
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007716 size_t size = mEffects.size();
7717 size_t idx_insert = size;
7718 ssize_t idx_insert_first = -1;
7719 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007720
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007721 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007722 effect_descriptor_t d = mEffects[i]->desc();
7723 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7724 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7725 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7726 // check invalid effect chaining combinations
7727 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7728 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007729 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007730 return INVALID_OPERATION;
7731 }
7732 // remember position of first insert effect and by default
7733 // select this as insert position for new effect
7734 if (idx_insert == size) {
7735 idx_insert = i;
7736 }
7737 // remember position of last insert effect claiming
7738 // first position
7739 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7740 idx_insert_first = i;
7741 }
7742 // remember position of first insert effect claiming
7743 // last position
7744 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7745 idx_insert_last == -1) {
7746 idx_insert_last = i;
7747 }
7748 }
7749 }
7750
7751 // modify idx_insert from first position if needed
7752 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7753 if (idx_insert_last != -1) {
7754 idx_insert = idx_insert_last;
7755 } else {
7756 idx_insert = size;
7757 }
7758 } else {
7759 if (idx_insert_first != -1) {
7760 idx_insert = idx_insert_first + 1;
7761 }
7762 }
7763
7764 // always read samples from chain input buffer
7765 effect->setInBuffer(mInBuffer);
7766
7767 // if last effect in the chain, output samples to chain
7768 // output buffer, otherwise to chain input buffer
7769 if (idx_insert == size) {
7770 if (idx_insert != 0) {
7771 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7772 mEffects[idx_insert-1]->configure();
7773 }
7774 effect->setOutBuffer(mOutBuffer);
7775 } else {
7776 effect->setOutBuffer(mInBuffer);
7777 }
7778 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007779
Steve Block3856b092011-10-20 11:56:00 +01007780 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007781 }
7782 effect->configure();
7783 return NO_ERROR;
7784}
7785
Eric Laurentcab11242010-07-15 12:50:15 -07007786// removeEffect_l() must be called with PlaybackThread::mLock held
7787size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007788{
7789 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007790 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007791 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7792
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007793 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007794 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007795 // calling stop here will remove pre-processing effect from the audio HAL.
7796 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7797 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007798 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7799 mEffects[i]->state() == EffectModule::STOPPING) {
7800 mEffects[i]->stop();
7801 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007802 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7803 delete[] effect->inBuffer();
7804 } else {
7805 if (i == size - 1 && i != 0) {
7806 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7807 mEffects[i - 1]->configure();
7808 }
7809 }
7810 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007811 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007812 break;
7813 }
7814 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007815
7816 return mEffects.size();
7817}
7818
Eric Laurentcab11242010-07-15 12:50:15 -07007819// setDevice_l() must be called with PlaybackThread::mLock held
7820void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007821{
7822 size_t size = mEffects.size();
7823 for (size_t i = 0; i < size; i++) {
7824 mEffects[i]->setDevice(device);
7825 }
7826}
7827
Eric Laurentcab11242010-07-15 12:50:15 -07007828// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007829void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007830{
7831 size_t size = mEffects.size();
7832 for (size_t i = 0; i < size; i++) {
7833 mEffects[i]->setMode(mode);
7834 }
7835}
7836
Eric Laurentcab11242010-07-15 12:50:15 -07007837// setVolume_l() must be called with PlaybackThread::mLock held
7838bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007839{
7840 uint32_t newLeft = *left;
7841 uint32_t newRight = *right;
7842 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007843 int ctrlIdx = -1;
7844 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007845
Eric Laurentcab11242010-07-15 12:50:15 -07007846 // first update volume controller
7847 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007848 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007849 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7850 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007851 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007852 break;
7853 }
7854 }
7855
7856 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007857 if (hasControl) {
7858 *left = mNewLeftVolume;
7859 *right = mNewRightVolume;
7860 }
7861 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007862 }
7863
7864 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007865 mLeftVolume = newLeft;
7866 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007867
7868 // second get volume update from volume controller
7869 if (ctrlIdx >= 0) {
7870 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007871 mNewLeftVolume = newLeft;
7872 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007873 }
7874 // then indicate volume to all other effects in chain.
7875 // Pass altered volume to effects before volume controller
7876 // and requested volume to effects after controller
7877 uint32_t lVol = newLeft;
7878 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007879
Mathias Agopian65ab4712010-07-14 17:59:35 -07007880 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007881 if ((int)i == ctrlIdx) continue;
7882 // this also works for ctrlIdx == -1 when there is no volume controller
7883 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007884 lVol = *left;
7885 rVol = *right;
7886 }
7887 mEffects[i]->setVolume(&lVol, &rVol, false);
7888 }
7889 *left = newLeft;
7890 *right = newRight;
7891
7892 return hasControl;
7893}
7894
Mathias Agopian65ab4712010-07-14 17:59:35 -07007895status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7896{
7897 const size_t SIZE = 256;
7898 char buffer[SIZE];
7899 String8 result;
7900
7901 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7902 result.append(buffer);
7903
7904 bool locked = tryLock(mLock);
7905 // failed to lock - AudioFlinger is probably deadlocked
7906 if (!locked) {
7907 result.append("\tCould not lock mutex:\n");
7908 }
7909
Eric Laurentcab11242010-07-15 12:50:15 -07007910 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7911 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007912 mEffects.size(),
7913 (uint32_t)mInBuffer,
7914 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007915 mActiveTrackCnt);
7916 result.append(buffer);
7917 write(fd, result.string(), result.size());
7918
7919 for (size_t i = 0; i < mEffects.size(); ++i) {
7920 sp<EffectModule> effect = mEffects[i];
7921 if (effect != 0) {
7922 effect->dump(fd, args);
7923 }
7924 }
7925
7926 if (locked) {
7927 mLock.unlock();
7928 }
7929
7930 return NO_ERROR;
7931}
7932
Eric Laurent59255e42011-07-27 19:49:51 -07007933// must be called with ThreadBase::mLock held
7934void AudioFlinger::EffectChain::setEffectSuspended_l(
7935 const effect_uuid_t *type, bool suspend)
7936{
7937 sp<SuspendedEffectDesc> desc;
7938 // use effect type UUID timelow as key as there is no real risk of identical
7939 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007940 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007941 if (suspend) {
7942 if (index >= 0) {
7943 desc = mSuspendedEffects.valueAt(index);
7944 } else {
7945 desc = new SuspendedEffectDesc();
7946 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7947 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007948 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007949 }
7950 if (desc->mRefCount++ == 0) {
7951 sp<EffectModule> effect = getEffectIfEnabled(type);
7952 if (effect != 0) {
7953 desc->mEffect = effect;
7954 effect->setSuspended(true);
7955 effect->setEnabled(false);
7956 }
7957 }
7958 } else {
7959 if (index < 0) {
7960 return;
7961 }
7962 desc = mSuspendedEffects.valueAt(index);
7963 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007964 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007965 desc->mRefCount = 1;
7966 }
7967 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007968 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007969 if (desc->mEffect != 0) {
7970 sp<EffectModule> effect = desc->mEffect.promote();
7971 if (effect != 0) {
7972 effect->setSuspended(false);
7973 sp<EffectHandle> handle = effect->controlHandle();
7974 if (handle != 0) {
7975 effect->setEnabled(handle->enabled());
7976 }
7977 }
7978 desc->mEffect.clear();
7979 }
7980 mSuspendedEffects.removeItemsAt(index);
7981 }
7982 }
7983}
7984
7985// must be called with ThreadBase::mLock held
7986void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7987{
7988 sp<SuspendedEffectDesc> desc;
7989
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007990 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07007991 if (suspend) {
7992 if (index >= 0) {
7993 desc = mSuspendedEffects.valueAt(index);
7994 } else {
7995 desc = new SuspendedEffectDesc();
7996 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007997 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007998 }
7999 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08008000 Vector< sp<EffectModule> > effects;
8001 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07008002 for (size_t i = 0; i < effects.size(); i++) {
8003 setEffectSuspended_l(&effects[i]->desc().type, true);
8004 }
8005 }
8006 } else {
8007 if (index < 0) {
8008 return;
8009 }
8010 desc = mSuspendedEffects.valueAt(index);
8011 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008012 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008013 desc->mRefCount = 1;
8014 }
8015 if (--desc->mRefCount == 0) {
8016 Vector<const effect_uuid_t *> types;
8017 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
8018 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
8019 continue;
8020 }
8021 types.add(&mSuspendedEffects.valueAt(i)->mType);
8022 }
8023 for (size_t i = 0; i < types.size(); i++) {
8024 setEffectSuspended_l(types[i], false);
8025 }
Steve Block3856b092011-10-20 11:56:00 +01008026 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008027 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
8028 }
8029 }
8030}
8031
Eric Laurent6bffdb82011-09-23 08:40:41 -07008032
8033// The volume effect is used for automated tests only
8034#ifndef OPENSL_ES_H_
8035static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
8036 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
8037const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
8038#endif //OPENSL_ES_H_
8039
Eric Laurentdb7c0792011-08-10 10:37:50 -07008040bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
8041{
8042 // auxiliary effects and visualizer are never suspended on output mix
8043 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8044 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07008045 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8046 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008047 return false;
8048 }
8049 return true;
8050}
8051
Glenn Kastend0539712012-01-30 12:56:03 -08008052void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07008053{
Glenn Kastend0539712012-01-30 12:56:03 -08008054 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07008055 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08008056 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8057 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07008058 }
Eric Laurent59255e42011-07-27 19:49:51 -07008059 }
Eric Laurent59255e42011-07-27 19:49:51 -07008060}
8061
8062sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8063 const effect_uuid_t *type)
8064{
Glenn Kasten090f0192012-01-30 13:00:02 -08008065 sp<EffectModule> effect = getEffectFromType_l(type);
8066 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008067}
8068
8069void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8070 bool enabled)
8071{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008072 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008073 if (enabled) {
8074 if (index < 0) {
8075 // if the effect is not suspend check if all effects are suspended
8076 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8077 if (index < 0) {
8078 return;
8079 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07008080 if (!isEffectEligibleForSuspend(effect->desc())) {
8081 return;
8082 }
Eric Laurent59255e42011-07-27 19:49:51 -07008083 setEffectSuspended_l(&effect->desc().type, enabled);
8084 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07008085 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008086 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07008087 return;
8088 }
Eric Laurent59255e42011-07-27 19:49:51 -07008089 }
Steve Block3856b092011-10-20 11:56:00 +01008090 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07008091 effect->desc().type.timeLow);
8092 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8093 // if effect is requested to suspended but was not yet enabled, supend it now.
8094 if (desc->mEffect == 0) {
8095 desc->mEffect = effect;
8096 effect->setEnabled(false);
8097 effect->setSuspended(true);
8098 }
8099 } else {
8100 if (index < 0) {
8101 return;
8102 }
Steve Block3856b092011-10-20 11:56:00 +01008103 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07008104 effect->desc().type.timeLow);
8105 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8106 desc->mEffect.clear();
8107 effect->setSuspended(false);
8108 }
8109}
8110
Mathias Agopian65ab4712010-07-14 17:59:35 -07008111#undef LOG_TAG
8112#define LOG_TAG "AudioFlinger"
8113
8114// ----------------------------------------------------------------------------
8115
8116status_t AudioFlinger::onTransact(
8117 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8118{
8119 return BnAudioFlinger::onTransact(code, data, reply, flags);
8120}
8121
Mathias Agopian65ab4712010-07-14 17:59:35 -07008122}; // namespace android