blob: 767c348ba898168047b99d517f9beade81442517 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070034#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035
Dima Zavinfce7a472011-04-19 22:30:36 -070036#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080038#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039
Gloria Wang9ee159b2011-02-24 14:51:45 -080040#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080041#include <media/IMediaDeathNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042
43#include <private/media/AudioTrackShared.h>
44#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070045
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070047#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080051#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
Mathias Agopian65ab4712010-07-14 17:59:35 -070053#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070054#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070055#include <audio_effects/effect_ns.h>
56#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Glenn Kasten3b21c502011-12-15 09:52:39 -080058#include <audio_utils/primitives.h>
59
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070060#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070061#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070062// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
63
John Grossman4ff14ba2012-02-08 16:37:41 -080064#include <common_time/cc_helper.h>
65#include <common_time/local_clock.h>
66
Mathias Agopian65ab4712010-07-14 17:59:35 -070067// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070068
Eric Laurentde070132010-07-13 04:45:46 -070069
Mathias Agopian65ab4712010-07-14 17:59:35 -070070namespace android {
71
Glenn Kastenec1d6b52011-12-12 09:04:45 -080072static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
73static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070074
Mathias Agopian65ab4712010-07-14 17:59:35 -070075static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -080076static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070077
78// retry counts for buffer fill timeout
79// 50 * ~20msecs = 1 second
80static const int8_t kMaxTrackRetries = 50;
81static const int8_t kMaxTrackStartupRetries = 50;
82// allow less retry attempts on direct output thread.
83// direct outputs can be a scarce resource in audio hardware and should
84// be released as quickly as possible.
85static const int8_t kMaxTrackRetriesDirect = 2;
86
87static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -080088static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
Glenn Kasten7dede872011-12-13 11:04:14 -080090// don't warn about blocked writes or record buffer overflows more often than this
91static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -070092
Eric Laurent7c7f10b2011-06-17 21:29:58 -070093// RecordThread loop sleep time upon application overrun or audio HAL read error
94static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070095
Glenn Kasten7dede872011-12-13 11:04:14 -080096// maximum time to wait for setParameters to complete
97static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -070098
Eric Laurent7cafbb32011-11-22 18:50:29 -080099// minimum sleep time for the mixer thread loop when tracks are active but in underrun
100static const uint32_t kMinThreadSleepTimeUs = 5000;
101// maximum divider applied to the active sleep time in the mixer thread loop
102static const uint32_t kMaxThreadSleepTimeShift = 2;
103
John Grossman4ff14ba2012-02-08 16:37:41 -0800104nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800105
Mathias Agopian65ab4712010-07-14 17:59:35 -0700106// ----------------------------------------------------------------------------
107
Gloria Wang9ee159b2011-02-24 14:51:45 -0800108// To collect the amplifier usage
109static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800110 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
111 if (service == NULL) {
112 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800113 return;
114 }
115
116 service->addBatteryData(params);
117}
118
Dima Zavin799a70e2011-04-18 16:57:27 -0700119static int load_audio_interface(const char *if_name, const hw_module_t **mod,
120 audio_hw_device_t **dev)
121{
122 int rc;
123
124 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
125 if (rc)
126 goto out;
127
128 rc = audio_hw_device_open(*mod, dev);
Steve Block29357bc2012-01-06 19:20:56 +0000129 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin799a70e2011-04-18 16:57:27 -0700130 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
131 if (rc)
132 goto out;
133
134 return 0;
135
136out:
137 *mod = NULL;
138 *dev = NULL;
139 return rc;
140}
141
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800142static const char * const audio_interfaces[] = {
Dima Zavin799a70e2011-04-18 16:57:27 -0700143 "primary",
144 "a2dp",
145 "usb",
146};
147#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
148
Mathias Agopian65ab4712010-07-14 17:59:35 -0700149// ----------------------------------------------------------------------------
150
151AudioFlinger::AudioFlinger()
152 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800153 mPrimaryHardwareDev(NULL),
154 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
155 mMasterVolume(1.0f),
156 mMasterVolumeSupportLvl(MVS_NONE),
157 mMasterMute(false),
158 mNextUniqueId(1),
159 mMode(AUDIO_MODE_INVALID),
160 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700161{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700162}
163
164void AudioFlinger::onFirstRef()
165{
Dima Zavin799a70e2011-04-18 16:57:27 -0700166 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700167
Eric Laurent93575202011-01-18 18:39:02 -0800168 Mutex::Autolock _l(mLock);
169
Dima Zavin799a70e2011-04-18 16:57:27 -0700170 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800171 char val_str[PROPERTY_VALUE_MAX] = { 0 };
172 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
173 uint32_t int_val;
174 if (1 == sscanf(val_str, "%u", &int_val)) {
175 mStandbyTimeInNsecs = milliseconds(int_val);
176 ALOGI("Using %u mSec as standby time.", int_val);
177 } else {
178 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
179 ALOGI("Using default %u mSec as standby time.",
180 (uint32_t)(mStandbyTimeInNsecs / 1000000));
181 }
182 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700183
Dima Zavin799a70e2011-04-18 16:57:27 -0700184 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
185 const hw_module_t *mod;
186 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700187
Dima Zavin799a70e2011-04-18 16:57:27 -0700188 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
189 if (rc)
190 continue;
191
Steve Blockdf64d152012-01-04 20:05:49 +0000192 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Dima Zavin799a70e2011-04-18 16:57:27 -0700193 mod->name, mod->id);
194 mAudioHwDevs.push(dev);
195
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800196 if (mPrimaryHardwareDev == NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700197 mPrimaryHardwareDev = dev;
Steve Blockdf64d152012-01-04 20:05:49 +0000198 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700199 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700200 }
201 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700202
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800203 if (mPrimaryHardwareDev == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000204 ALOGE("Primary audio interface not found");
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800205 // proceed, all later accesses to mPrimaryHardwareDev verify it's safe with initCheck()
Dima Zavin799a70e2011-04-18 16:57:27 -0700206 }
207
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800208 // Currently (mPrimaryHardwareDev == NULL) == (mAudioHwDevs.size() == 0), but the way the
209 // primary HW dev is selected can change so these conditions might not always be equivalent.
210 // When that happens, re-visit all the code that assumes this.
211
212 AutoMutex lock(mHardwareLock);
213
John Grossman4ff14ba2012-02-08 16:37:41 -0800214 // Determine the level of master volume support the primary audio HAL has,
215 // and set the initial master volume at the same time.
216 float initialVolume = 1.0;
217 mMasterVolumeSupportLvl = MVS_NONE;
218 if (0 == mPrimaryHardwareDev->init_check(mPrimaryHardwareDev)) {
219 audio_hw_device_t *dev = mPrimaryHardwareDev;
220
221 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
222 if ((NULL != dev->get_master_volume) &&
223 (NO_ERROR == dev->get_master_volume(dev, &initialVolume))) {
224 mMasterVolumeSupportLvl = MVS_FULL;
225 } else {
226 mMasterVolumeSupportLvl = MVS_SETONLY;
227 initialVolume = 1.0;
228 }
229
230 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
231 if ((NULL == dev->set_master_volume) ||
232 (NO_ERROR != dev->set_master_volume(dev, initialVolume))) {
233 mMasterVolumeSupportLvl = MVS_NONE;
234 }
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800235 mHardwareStatus = AUDIO_HW_IDLE;
John Grossman4ff14ba2012-02-08 16:37:41 -0800236 }
237
238 // Set the mode for each audio HAL, and try to set the initial volume (if
239 // supported) for all of the non-primary audio HALs.
Dima Zavin799a70e2011-04-18 16:57:27 -0700240 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
241 audio_hw_device_t *dev = mAudioHwDevs[i];
242
243 mHardwareStatus = AUDIO_HW_INIT;
244 rc = dev->init_check(dev);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800245 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700246 if (rc == 0) {
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800247 mMode = AUDIO_MODE_NORMAL; // assigned multiple times with same value
Dima Zavin799a70e2011-04-18 16:57:27 -0700248 mHardwareStatus = AUDIO_HW_SET_MODE;
249 dev->set_mode(dev, mMode);
John Grossman4ff14ba2012-02-08 16:37:41 -0800250
251 if ((dev != mPrimaryHardwareDev) &&
252 (NULL != dev->set_master_volume)) {
253 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
254 dev->set_master_volume(dev, initialVolume);
255 }
256
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800257 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700258 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700259 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800260
261 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
262 ? initialVolume
263 : 1.0;
264 mMasterVolume = initialVolume;
265 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700266}
267
268AudioFlinger::~AudioFlinger()
269{
Dima Zavin799a70e2011-04-18 16:57:27 -0700270
Mathias Agopian65ab4712010-07-14 17:59:35 -0700271 while (!mRecordThreads.isEmpty()) {
272 // closeInput() will remove first entry from mRecordThreads
273 closeInput(mRecordThreads.keyAt(0));
274 }
275 while (!mPlaybackThreads.isEmpty()) {
276 // closeOutput() will remove first entry from mPlaybackThreads
277 closeOutput(mPlaybackThreads.keyAt(0));
278 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700279
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800280 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
281 // no mHardwareLock needed, as there are no other references to this
282 audio_hw_device_close(mAudioHwDevs[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700283 }
284}
285
Dima Zavin799a70e2011-04-18 16:57:27 -0700286audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
287{
288 /* first matching HW device is returned */
289 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
290 audio_hw_device_t *dev = mAudioHwDevs[i];
291 if ((dev->get_supported_devices(dev) & devices) == devices)
292 return dev;
293 }
294 return NULL;
295}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700296
297status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
298{
299 const size_t SIZE = 256;
300 char buffer[SIZE];
301 String8 result;
302
303 result.append("Clients:\n");
304 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800305 sp<Client> client = mClients.valueAt(i).promote();
306 if (client != 0) {
307 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
308 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700309 }
310 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700311
312 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800313 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700314 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
315 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800316 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700317 result.append(buffer);
318 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700319 write(fd, result.string(), result.size());
320 return NO_ERROR;
321}
322
323
324status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
325{
326 const size_t SIZE = 256;
327 char buffer[SIZE];
328 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800329 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700330
John Grossman4ff14ba2012-02-08 16:37:41 -0800331 snprintf(buffer, SIZE, "Hardware status: %d\n"
332 "Standby Time mSec: %u\n",
333 hardwareStatus,
334 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700335 result.append(buffer);
336 write(fd, result.string(), result.size());
337 return NO_ERROR;
338}
339
340status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
341{
342 const size_t SIZE = 256;
343 char buffer[SIZE];
344 String8 result;
345 snprintf(buffer, SIZE, "Permission Denial: "
346 "can't dump AudioFlinger from pid=%d, uid=%d\n",
347 IPCThreadState::self()->getCallingPid(),
348 IPCThreadState::self()->getCallingUid());
349 result.append(buffer);
350 write(fd, result.string(), result.size());
351 return NO_ERROR;
352}
353
354static bool tryLock(Mutex& mutex)
355{
356 bool locked = false;
357 for (int i = 0; i < kDumpLockRetries; ++i) {
358 if (mutex.tryLock() == NO_ERROR) {
359 locked = true;
360 break;
361 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800362 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700363 }
364 return locked;
365}
366
367status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
368{
Glenn Kasten44deb052012-02-05 18:09:08 -0800369 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700370 dumpPermissionDenial(fd, args);
371 } else {
372 // get state of hardware lock
373 bool hardwareLocked = tryLock(mHardwareLock);
374 if (!hardwareLocked) {
375 String8 result(kHardwareLockedString);
376 write(fd, result.string(), result.size());
377 } else {
378 mHardwareLock.unlock();
379 }
380
381 bool locked = tryLock(mLock);
382
383 // failed to lock - AudioFlinger is probably deadlocked
384 if (!locked) {
385 String8 result(kDeadlockedString);
386 write(fd, result.string(), result.size());
387 }
388
389 dumpClients(fd, args);
390 dumpInternals(fd, args);
391
392 // dump playback threads
393 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
394 mPlaybackThreads.valueAt(i)->dump(fd, args);
395 }
396
397 // dump record threads
398 for (size_t i = 0; i < mRecordThreads.size(); i++) {
399 mRecordThreads.valueAt(i)->dump(fd, args);
400 }
401
Dima Zavin799a70e2011-04-18 16:57:27 -0700402 // dump all hardware devs
403 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
404 audio_hw_device_t *dev = mAudioHwDevs[i];
405 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700406 }
407 if (locked) mLock.unlock();
408 }
409 return NO_ERROR;
410}
411
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800412sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
413{
414 // If pid is already in the mClients wp<> map, then use that entry
415 // (for which promote() is always != 0), otherwise create a new entry and Client.
416 sp<Client> client = mClients.valueFor(pid).promote();
417 if (client == 0) {
418 client = new Client(this, pid);
419 mClients.add(pid, client);
420 }
421
422 return client;
423}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700424
425// IAudioFlinger interface
426
427
428sp<IAudioTrack> AudioFlinger::createTrack(
429 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800430 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700431 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800432 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700433 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700434 int frameCount,
Glenn Kasten5cf034d2012-02-21 10:35:56 -0800435 // FIXME dead, remove from IAudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700436 uint32_t flags,
437 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800438 audio_io_handle_t output,
John Grossman4ff14ba2012-02-08 16:37:41 -0800439 bool isTimed,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700440 int *sessionId,
441 status_t *status)
442{
443 sp<PlaybackThread::Track> track;
444 sp<TrackHandle> trackHandle;
445 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700446 status_t lStatus;
447 int lSessionId;
448
Glenn Kasten263709e2012-01-06 08:40:01 -0800449 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
450 // but if someone uses binder directly they could bypass that and cause us to crash
451 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000452 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700453 lStatus = BAD_VALUE;
454 goto Exit;
455 }
456
457 {
458 Mutex::Autolock _l(mLock);
459 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700460 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700461 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000462 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700463 lStatus = BAD_VALUE;
464 goto Exit;
465 }
466
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800467 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700468
Steve Block3856b092011-10-20 11:56:00 +0100469 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700470 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700471 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700472 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
473 if (mPlaybackThreads.keyAt(i) != output) {
474 // prevent same audio session on different output threads
475 uint32_t sessions = t->hasAudioSession(*sessionId);
476 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000477 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700478 lStatus = BAD_VALUE;
479 goto Exit;
480 }
481 // check if an effect with same session ID is waiting for a track to be created
482 if (sessions & PlaybackThread::EFFECT_SESSION) {
483 effectThread = t.get();
484 }
Eric Laurentde070132010-07-13 04:45:46 -0700485 }
486 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700487 lSessionId = *sessionId;
488 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700489 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700490 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700491 if (sessionId != NULL) {
492 *sessionId = lSessionId;
493 }
494 }
Steve Block3856b092011-10-20 11:56:00 +0100495 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700496
497 track = thread->createTrack_l(client, streamType, sampleRate, format,
John Grossman4ff14ba2012-02-08 16:37:41 -0800498 channelMask, frameCount, sharedBuffer, lSessionId, isTimed, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700499
500 // move effect chain to this output thread if an effect on same session was waiting
501 // for a track to be created
502 if (lStatus == NO_ERROR && effectThread != NULL) {
503 Mutex::Autolock _dl(thread->mLock);
504 Mutex::Autolock _sl(effectThread->mLock);
505 moveEffectChain_l(lSessionId, effectThread, thread, true);
506 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700507 }
508 if (lStatus == NO_ERROR) {
509 trackHandle = new TrackHandle(track);
510 } else {
511 // remove local strong reference to Client before deleting the Track so that the Client
512 // destructor is called by the TrackBase destructor with mLock held
513 client.clear();
514 track.clear();
515 }
516
517Exit:
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;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800726 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
727 (NULL != mPrimaryHardwareDev->get_master_volume),
728 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800729
730 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
731 mHardwareStatus = AUDIO_HW_IDLE;
732 return ret_val;
733 }
734
735 return mMasterVolume;
736}
737
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800738status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
739 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700740{
741 // check calling permissions
742 if (!settingsAllowed()) {
743 return PERMISSION_DENIED;
744 }
745
Glenn Kasten263709e2012-01-06 08:40:01 -0800746 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000747 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700748 return BAD_VALUE;
749 }
750
751 AutoMutex lock(mLock);
752 PlaybackThread *thread = NULL;
753 if (output) {
754 thread = checkPlaybackThread_l(output);
755 if (thread == NULL) {
756 return BAD_VALUE;
757 }
758 }
759
760 mStreamTypes[stream].volume = value;
761
762 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800763 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700764 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
765 }
766 } else {
767 thread->setStreamVolume(stream, value);
768 }
769
770 return NO_ERROR;
771}
772
Glenn Kastenfff6d712012-01-12 16:38:12 -0800773status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700774{
775 // check calling permissions
776 if (!settingsAllowed()) {
777 return PERMISSION_DENIED;
778 }
779
Glenn Kasten263709e2012-01-06 08:40:01 -0800780 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700781 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000782 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700783 return BAD_VALUE;
784 }
785
Eric Laurent93575202011-01-18 18:39:02 -0800786 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700787 mStreamTypes[stream].mute = muted;
788 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
789 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
790
791 return NO_ERROR;
792}
793
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800794float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700795{
Glenn Kasten263709e2012-01-06 08:40:01 -0800796 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700797 return 0.0f;
798 }
799
800 AutoMutex lock(mLock);
801 float volume;
802 if (output) {
803 PlaybackThread *thread = checkPlaybackThread_l(output);
804 if (thread == NULL) {
805 return 0.0f;
806 }
807 volume = thread->streamVolume(stream);
808 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800809 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700810 }
811
812 return volume;
813}
814
Glenn Kastenfff6d712012-01-12 16:38:12 -0800815bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700816{
Glenn Kasten263709e2012-01-06 08:40:01 -0800817 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700818 return true;
819 }
820
Glenn Kasten6637baa2012-01-09 09:40:36 -0800821 AutoMutex lock(mLock);
822 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700823}
824
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800825status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700826{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800827 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700828 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
829 // check calling permissions
830 if (!settingsAllowed()) {
831 return PERMISSION_DENIED;
832 }
833
Mathias Agopian65ab4712010-07-14 17:59:35 -0700834 // ioHandle == 0 means the parameters are global to the audio hardware interface
835 if (ioHandle == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700836 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800837 {
838 AutoMutex lock(mHardwareLock);
839 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700840 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
841 audio_hw_device_t *dev = mAudioHwDevs[i];
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800842 status_t result = dev->set_parameters(dev, keyValuePairs.string());
Dima Zavin799a70e2011-04-18 16:57:27 -0700843 final_result = result ?: final_result;
844 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800846 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700847 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
848 AudioParameter param = AudioParameter(keyValuePairs);
849 String8 value;
850 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
851 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700852 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
853 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700854 for (size_t i = 0; i < mRecordThreads.size(); i++) {
855 sp<RecordThread> thread = mRecordThreads.valueAt(i);
856 RecordThread::RecordTrack *track = thread->track();
857 if (track != NULL) {
858 audio_devices_t device = (audio_devices_t)(
859 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700860 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700861 thread->setEffectSuspended(FX_IID_AEC,
862 suspend,
863 track->sessionId());
864 thread->setEffectSuspended(FX_IID_NS,
865 suspend,
866 track->sessionId());
867 }
868 }
Eric Laurentbee53372011-08-29 12:42:48 -0700869 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700870 }
871 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700872 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700873 }
874
875 // hold a strong ref on thread in case closeOutput() or closeInput() is called
876 // and the thread is exited once the lock is released
877 sp<ThreadBase> thread;
878 {
879 Mutex::Autolock _l(mLock);
880 thread = checkPlaybackThread_l(ioHandle);
881 if (thread == NULL) {
882 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800883 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700884 // indicate output device change to all input threads for pre processing
885 AudioParameter param = AudioParameter(keyValuePairs);
886 int value;
887 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
888 for (size_t i = 0; i < mRecordThreads.size(); i++) {
889 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
890 }
891 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700892 }
893 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800894 if (thread != 0) {
895 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700896 }
897 return BAD_VALUE;
898}
899
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800900String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700901{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800902// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700903// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
904
905 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700906 String8 out_s8;
907
Dima Zavin799a70e2011-04-18 16:57:27 -0700908 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800909 char *s;
910 {
911 AutoMutex lock(mHardwareLock);
912 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700913 audio_hw_device_t *dev = mAudioHwDevs[i];
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800914 s = dev->get_parameters(dev, keys.string());
915 mHardwareStatus = AUDIO_HW_IDLE;
916 }
John Grossmanef7740b2012-02-09 11:28:36 -0800917 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700918 free(s);
919 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700920 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700921 }
922
923 Mutex::Autolock _l(mLock);
924
925 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
926 if (playbackThread != NULL) {
927 return playbackThread->getParameters(keys);
928 }
929 RecordThread *recordThread = checkRecordThread_l(ioHandle);
930 if (recordThread != NULL) {
931 return recordThread->getParameters(keys);
932 }
933 return String8("");
934}
935
Glenn Kastenf587ba52012-01-26 16:25:10 -0800936size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700937{
Eric Laurenta1884f92011-08-23 08:25:03 -0700938 status_t ret = initCheck();
939 if (ret != NO_ERROR) {
940 return 0;
941 }
942
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800943 AutoMutex lock(mHardwareLock);
944 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
945 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
946 mHardwareStatus = AUDIO_HW_IDLE;
947 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700948}
949
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800950unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700951{
952 if (ioHandle == 0) {
953 return 0;
954 }
955
956 Mutex::Autolock _l(mLock);
957
958 RecordThread *recordThread = checkRecordThread_l(ioHandle);
959 if (recordThread != NULL) {
960 return recordThread->getInputFramesLost();
961 }
962 return 0;
963}
964
965status_t AudioFlinger::setVoiceVolume(float value)
966{
Eric Laurenta1884f92011-08-23 08:25:03 -0700967 status_t ret = initCheck();
968 if (ret != NO_ERROR) {
969 return ret;
970 }
971
Mathias Agopian65ab4712010-07-14 17:59:35 -0700972 // check calling permissions
973 if (!settingsAllowed()) {
974 return PERMISSION_DENIED;
975 }
976
977 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800978 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700979 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700980 mHardwareStatus = AUDIO_HW_IDLE;
981
982 return ret;
983}
984
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800985status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
986 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700987{
988 status_t status;
989
990 Mutex::Autolock _l(mLock);
991
992 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
993 if (playbackThread != NULL) {
994 return playbackThread->getRenderPosition(halFrames, dspFrames);
995 }
996
997 return BAD_VALUE;
998}
999
1000void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1001{
1002
1003 Mutex::Autolock _l(mLock);
1004
Glenn Kastenbb001922012-02-03 11:10:26 -08001005 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001006 if (mNotificationClients.indexOfKey(pid) < 0) {
1007 sp<NotificationClient> notificationClient = new NotificationClient(this,
1008 client,
1009 pid);
Steve Block3856b092011-10-20 11:56:00 +01001010 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001011
1012 mNotificationClients.add(pid, notificationClient);
1013
1014 sp<IBinder> binder = client->asBinder();
1015 binder->linkToDeath(notificationClient);
1016
1017 // the config change is always sent from playback or record threads to avoid deadlock
1018 // with AudioSystem::gLock
1019 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1020 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1021 }
1022
1023 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1024 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1025 }
1026 }
1027}
1028
1029void AudioFlinger::removeNotificationClient(pid_t pid)
1030{
1031 Mutex::Autolock _l(mLock);
1032
Glenn Kastena3b09252012-01-20 09:19:01 -08001033 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001034
Steve Block3856b092011-10-20 11:56:00 +01001035 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001036 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001037 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001038 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001039 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001040 ALOGV(" pid %d @ %d", ref->mPid, i);
1041 if (ref->mPid == pid) {
1042 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001043 mAudioSessionRefs.removeAt(i);
1044 delete ref;
1045 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001046 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001047 } else {
1048 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001049 }
1050 }
1051 if (removed) {
1052 purgeStaleEffects_l();
1053 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001054}
1055
1056// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001057void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001058{
1059 size_t size = mNotificationClients.size();
1060 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001061 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1062 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001063 }
1064}
1065
1066// removeClient_l() must be called with AudioFlinger::mLock held
1067void AudioFlinger::removeClient_l(pid_t pid)
1068{
Steve Block3856b092011-10-20 11:56:00 +01001069 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001070 mClients.removeItem(pid);
1071}
1072
1073
1074// ----------------------------------------------------------------------------
1075
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001076AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1077 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001079 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001080 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
1081 // mChannelMask
1082 mChannelCount(0),
1083 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1084 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001085 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001086 mDevice(device),
1087 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001088{
1089}
1090
1091AudioFlinger::ThreadBase::~ThreadBase()
1092{
1093 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001094 // do not lock the mutex in destructor
1095 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001096 if (mPowerManager != 0) {
1097 sp<IBinder> binder = mPowerManager->asBinder();
1098 binder->unlinkToDeath(mDeathRecipient);
1099 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001100}
1101
1102void AudioFlinger::ThreadBase::exit()
1103{
Steve Block3856b092011-10-20 11:56:00 +01001104 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001105 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001106 // This lock prevents the following race in thread (uniprocessor for illustration):
1107 // if (!exitPending()) {
1108 // // context switch from here to exit()
1109 // // exit() calls requestExit(), what exitPending() observes
1110 // // exit() calls signal(), which is dropped since no waiters
1111 // // context switch back from exit() to here
1112 // mWaitWorkCV.wait(...);
1113 // // now thread is hung
1114 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001115 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001116 requestExit();
1117 mWaitWorkCV.signal();
1118 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001119 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1120 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001121 requestExitAndWait();
1122}
1123
Mathias Agopian65ab4712010-07-14 17:59:35 -07001124status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1125{
1126 status_t status;
1127
Steve Block3856b092011-10-20 11:56:00 +01001128 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001129 Mutex::Autolock _l(mLock);
1130
1131 mNewParameters.add(keyValuePairs);
1132 mWaitWorkCV.signal();
1133 // wait condition with timeout in case the thread loop has exited
1134 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001135 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001136 status = mParamStatus;
1137 mWaitWorkCV.signal();
1138 } else {
1139 status = TIMED_OUT;
1140 }
1141 return status;
1142}
1143
1144void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1145{
1146 Mutex::Autolock _l(mLock);
1147 sendConfigEvent_l(event, param);
1148}
1149
1150// sendConfigEvent_l() must be called with ThreadBase::mLock held
1151void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1152{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001153 ConfigEvent configEvent;
1154 configEvent.mEvent = event;
1155 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001156 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001157 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001158 mWaitWorkCV.signal();
1159}
1160
1161void AudioFlinger::ThreadBase::processConfigEvents()
1162{
1163 mLock.lock();
1164 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001165 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001166 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001167 mConfigEvents.removeAt(0);
1168 // release mLock before locking AudioFlinger mLock: lock order is always
1169 // AudioFlinger then ThreadBase to avoid cross deadlock
1170 mLock.unlock();
1171 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001172 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001173 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001174 mLock.lock();
1175 }
1176 mLock.unlock();
1177}
1178
1179status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1180{
1181 const size_t SIZE = 256;
1182 char buffer[SIZE];
1183 String8 result;
1184
1185 bool locked = tryLock(mLock);
1186 if (!locked) {
1187 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1188 write(fd, buffer, strlen(buffer));
1189 }
1190
1191 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1192 result.append(buffer);
1193 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1194 result.append(buffer);
1195 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1196 result.append(buffer);
1197 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1198 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001199 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1200 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001201 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1202 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001203 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001204 result.append(buffer);
1205
1206 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1207 result.append(buffer);
1208 result.append(" Index Command");
1209 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1210 snprintf(buffer, SIZE, "\n %02d ", i);
1211 result.append(buffer);
1212 result.append(mNewParameters[i]);
1213 }
1214
1215 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1216 result.append(buffer);
1217 snprintf(buffer, SIZE, " Index event param\n");
1218 result.append(buffer);
1219 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001220 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001221 result.append(buffer);
1222 }
1223 result.append("\n");
1224
1225 write(fd, result.string(), result.size());
1226
1227 if (locked) {
1228 mLock.unlock();
1229 }
1230 return NO_ERROR;
1231}
1232
Eric Laurent1d2bff02011-07-24 17:49:51 -07001233status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1234{
1235 const size_t SIZE = 256;
1236 char buffer[SIZE];
1237 String8 result;
1238
1239 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1240 write(fd, buffer, strlen(buffer));
1241
1242 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1243 sp<EffectChain> chain = mEffectChains[i];
1244 if (chain != 0) {
1245 chain->dump(fd, args);
1246 }
1247 }
1248 return NO_ERROR;
1249}
1250
Eric Laurentfeb0db62011-07-22 09:04:31 -07001251void AudioFlinger::ThreadBase::acquireWakeLock()
1252{
1253 Mutex::Autolock _l(mLock);
1254 acquireWakeLock_l();
1255}
1256
1257void AudioFlinger::ThreadBase::acquireWakeLock_l()
1258{
1259 if (mPowerManager == 0) {
1260 // use checkService() to avoid blocking if power service is not up yet
1261 sp<IBinder> binder =
1262 defaultServiceManager()->checkService(String16("power"));
1263 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001264 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001265 } else {
1266 mPowerManager = interface_cast<IPowerManager>(binder);
1267 binder->linkToDeath(mDeathRecipient);
1268 }
1269 }
1270 if (mPowerManager != 0) {
1271 sp<IBinder> binder = new BBinder();
1272 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1273 binder,
1274 String16(mName));
1275 if (status == NO_ERROR) {
1276 mWakeLockToken = binder;
1277 }
Steve Block3856b092011-10-20 11:56:00 +01001278 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001279 }
1280}
1281
1282void AudioFlinger::ThreadBase::releaseWakeLock()
1283{
1284 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001285 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001286}
1287
1288void AudioFlinger::ThreadBase::releaseWakeLock_l()
1289{
1290 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001291 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001292 if (mPowerManager != 0) {
1293 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1294 }
1295 mWakeLockToken.clear();
1296 }
1297}
1298
1299void AudioFlinger::ThreadBase::clearPowerManager()
1300{
1301 Mutex::Autolock _l(mLock);
1302 releaseWakeLock_l();
1303 mPowerManager.clear();
1304}
1305
1306void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1307{
1308 sp<ThreadBase> thread = mThread.promote();
1309 if (thread != 0) {
1310 thread->clearPowerManager();
1311 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001312 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001313}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001314
Eric Laurent59255e42011-07-27 19:49:51 -07001315void AudioFlinger::ThreadBase::setEffectSuspended(
1316 const effect_uuid_t *type, bool suspend, int sessionId)
1317{
1318 Mutex::Autolock _l(mLock);
1319 setEffectSuspended_l(type, suspend, sessionId);
1320}
1321
1322void AudioFlinger::ThreadBase::setEffectSuspended_l(
1323 const effect_uuid_t *type, bool suspend, int sessionId)
1324{
Glenn Kasten090f0192012-01-30 13:00:02 -08001325 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001326 if (chain != 0) {
1327 if (type != NULL) {
1328 chain->setEffectSuspended_l(type, suspend);
1329 } else {
1330 chain->setEffectSuspendedAll_l(suspend);
1331 }
1332 }
1333
1334 updateSuspendedSessions_l(type, suspend, sessionId);
1335}
1336
1337void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1338{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001339 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001340 if (index < 0) {
1341 return;
1342 }
1343
1344 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1345 mSuspendedSessions.editValueAt(index);
1346
1347 for (size_t i = 0; i < sessionEffects.size(); i++) {
1348 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1349 for (int j = 0; j < desc->mRefCount; j++) {
1350 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1351 chain->setEffectSuspendedAll_l(true);
1352 } else {
Steve Block3856b092011-10-20 11:56:00 +01001353 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001354 desc->mType.timeLow);
1355 chain->setEffectSuspended_l(&desc->mType, true);
1356 }
1357 }
1358 }
1359}
1360
Eric Laurent59255e42011-07-27 19:49:51 -07001361void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1362 bool suspend,
1363 int sessionId)
1364{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001365 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001366
1367 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1368
1369 if (suspend) {
1370 if (index >= 0) {
1371 sessionEffects = mSuspendedSessions.editValueAt(index);
1372 } else {
1373 mSuspendedSessions.add(sessionId, sessionEffects);
1374 }
1375 } else {
1376 if (index < 0) {
1377 return;
1378 }
1379 sessionEffects = mSuspendedSessions.editValueAt(index);
1380 }
1381
1382
1383 int key = EffectChain::kKeyForSuspendAll;
1384 if (type != NULL) {
1385 key = type->timeLow;
1386 }
1387 index = sessionEffects.indexOfKey(key);
1388
1389 sp <SuspendedSessionDesc> desc;
1390 if (suspend) {
1391 if (index >= 0) {
1392 desc = sessionEffects.valueAt(index);
1393 } else {
1394 desc = new SuspendedSessionDesc();
1395 if (type != NULL) {
1396 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1397 }
1398 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001399 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001400 }
1401 desc->mRefCount++;
1402 } else {
1403 if (index < 0) {
1404 return;
1405 }
1406 desc = sessionEffects.valueAt(index);
1407 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001408 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001409 sessionEffects.removeItemsAt(index);
1410 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001411 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001412 sessionId);
1413 mSuspendedSessions.removeItem(sessionId);
1414 }
1415 }
1416 }
1417 if (!sessionEffects.isEmpty()) {
1418 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1419 }
1420}
1421
1422void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1423 bool enabled,
1424 int sessionId)
1425{
1426 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001427 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1428}
Eric Laurent59255e42011-07-27 19:49:51 -07001429
Eric Laurenta85a74a2011-10-19 11:44:54 -07001430void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1431 bool enabled,
1432 int sessionId)
1433{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001434 if (mType != RECORD) {
1435 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1436 // another session. This gives the priority to well behaved effect control panels
1437 // and applications not using global effects.
1438 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1439 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1440 }
1441 }
Eric Laurent59255e42011-07-27 19:49:51 -07001442
1443 sp<EffectChain> chain = getEffectChain_l(sessionId);
1444 if (chain != 0) {
1445 chain->checkSuspendOnEffectEnabled(effect, enabled);
1446 }
1447}
1448
Mathias Agopian65ab4712010-07-14 17:59:35 -07001449// ----------------------------------------------------------------------------
1450
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001451AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1452 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001453 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001454 uint32_t device,
1455 type_t type)
1456 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001457 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1458 // Assumes constructor is called by AudioFlinger with it's mLock held,
1459 // but it would be safer to explicitly pass initial masterMute as parameter
1460 mMasterMute(audioFlinger->masterMute_l()),
1461 // mStreamTypes[] initialized in constructor body
1462 mOutput(output),
1463 // Assumes constructor is called by AudioFlinger with it's mLock held,
1464 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001465 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001466 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1467 // mMixerStatus
Glenn Kasten66fcab92012-02-24 14:59:21 -08001468 mPrevMixerStatus(MIXER_IDLE),
1469 standbyDelay(AudioFlinger::mStandbyTimeInNsecs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001470{
Glenn Kasten480b4682012-02-28 12:30:08 -08001471 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001472
Mathias Agopian65ab4712010-07-14 17:59:35 -07001473 readOutputParameters();
1474
Glenn Kasten263709e2012-01-06 08:40:01 -08001475 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001476 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1477 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1478 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001479 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1480 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001481 // initialized by stream_type_t default constructor
1482 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001483 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001484 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1485 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001486}
1487
1488AudioFlinger::PlaybackThread::~PlaybackThread()
1489{
1490 delete [] mMixBuffer;
1491}
1492
1493status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1494{
1495 dumpInternals(fd, args);
1496 dumpTracks(fd, args);
1497 dumpEffectChains(fd, args);
1498 return NO_ERROR;
1499}
1500
1501status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1502{
1503 const size_t SIZE = 256;
1504 char buffer[SIZE];
1505 String8 result;
1506
1507 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1508 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001509 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 -07001510 for (size_t i = 0; i < mTracks.size(); ++i) {
1511 sp<Track> track = mTracks[i];
1512 if (track != 0) {
1513 track->dump(buffer, SIZE);
1514 result.append(buffer);
1515 }
1516 }
1517
1518 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1519 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001520 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 -07001521 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001522 sp<Track> track = mActiveTracks[i].promote();
1523 if (track != 0) {
1524 track->dump(buffer, SIZE);
1525 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001526 }
1527 }
1528 write(fd, result.string(), result.size());
1529 return NO_ERROR;
1530}
1531
Mathias Agopian65ab4712010-07-14 17:59:35 -07001532status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1533{
1534 const size_t SIZE = 256;
1535 char buffer[SIZE];
1536 String8 result;
1537
1538 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1539 result.append(buffer);
1540 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1541 result.append(buffer);
1542 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1543 result.append(buffer);
1544 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1545 result.append(buffer);
1546 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1547 result.append(buffer);
1548 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1549 result.append(buffer);
1550 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1551 result.append(buffer);
1552 write(fd, result.string(), result.size());
1553
1554 dumpBase(fd, args);
1555
1556 return NO_ERROR;
1557}
1558
1559// Thread virtuals
1560status_t AudioFlinger::PlaybackThread::readyToRun()
1561{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001562 status_t status = initCheck();
1563 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001564 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001565 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001566 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001567 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001568 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001569}
1570
1571void AudioFlinger::PlaybackThread::onFirstRef()
1572{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001573 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001574}
1575
1576// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1577sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1578 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001579 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001580 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001581 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001582 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001583 int frameCount,
1584 const sp<IMemory>& sharedBuffer,
1585 int sessionId,
John Grossman4ff14ba2012-02-08 16:37:41 -08001586 bool isTimed,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001587 status_t *status)
1588{
1589 sp<Track> track;
1590 status_t lStatus;
1591
1592 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001593 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1594 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001595 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001596 "for output %p with format %d",
1597 sampleRate, format, channelMask, mOutput, mFormat);
1598 lStatus = BAD_VALUE;
1599 goto Exit;
1600 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001601 }
1602 } else {
1603 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1604 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001605 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001606 lStatus = BAD_VALUE;
1607 goto Exit;
1608 }
1609 }
1610
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001611 lStatus = initCheck();
1612 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001613 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001614 goto Exit;
1615 }
1616
1617 { // scope for mLock
1618 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001619
1620 // all tracks in same audio session must share the same routing strategy otherwise
1621 // conflicts will happen when tracks are moved from one output to another by audio policy
1622 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001623 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001624 for (size_t i = 0; i < mTracks.size(); ++i) {
1625 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001626 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001627 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001628 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001629 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001630 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001631 lStatus = BAD_VALUE;
1632 goto Exit;
1633 }
1634 }
1635 }
1636
John Grossman4ff14ba2012-02-08 16:37:41 -08001637 if (!isTimed) {
1638 track = new Track(this, client, streamType, sampleRate, format,
1639 channelMask, frameCount, sharedBuffer, sessionId);
1640 } else {
1641 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1642 channelMask, frameCount, sharedBuffer, sessionId);
1643 }
1644 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001645 lStatus = NO_MEMORY;
1646 goto Exit;
1647 }
1648 mTracks.add(track);
1649
1650 sp<EffectChain> chain = getEffectChain_l(sessionId);
1651 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001652 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001653 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001654 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001655 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001656 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001657
1658 // invalidate track immediately if the stream type was moved to another thread since
1659 // createTrack() was called by the client process.
1660 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001661 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001662 this, streamType);
1663 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1664 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001665 }
1666 lStatus = NO_ERROR;
1667
1668Exit:
1669 if(status) {
1670 *status = lStatus;
1671 }
1672 return track;
1673}
1674
1675uint32_t AudioFlinger::PlaybackThread::latency() const
1676{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001677 Mutex::Autolock _l(mLock);
1678 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001679 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001680 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001681 return 0;
1682 }
1683}
1684
Glenn Kasten6637baa2012-01-09 09:40:36 -08001685void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001686{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001687 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001688 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001689}
1690
Glenn Kasten6637baa2012-01-09 09:40:36 -08001691void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001692{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001693 Mutex::Autolock _l(mLock);
1694 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695}
1696
Glenn Kasten6637baa2012-01-09 09:40:36 -08001697void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001698{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001699 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001700 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001701}
1702
Glenn Kasten6637baa2012-01-09 09:40:36 -08001703void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001704{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001705 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001706 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001707}
1708
Glenn Kastenfff6d712012-01-12 16:38:12 -08001709float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001710{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001711 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001712 return mStreamTypes[stream].volume;
1713}
1714
Mathias Agopian65ab4712010-07-14 17:59:35 -07001715// addTrack_l() must be called with ThreadBase::mLock held
1716status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1717{
1718 status_t status = ALREADY_EXISTS;
1719
1720 // set retry count for buffer fill
1721 track->mRetryCount = kMaxTrackStartupRetries;
1722 if (mActiveTracks.indexOf(track) < 0) {
1723 // the track is newly added, make sure it fills up all its
1724 // buffers before playing. This is to ensure the client will
1725 // effectively get the latency it requested.
1726 track->mFillingUpStatus = Track::FS_FILLING;
1727 track->mResetDone = false;
1728 mActiveTracks.add(track);
1729 if (track->mainBuffer() != mMixBuffer) {
1730 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1731 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001732 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001733 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001734 }
1735 }
1736
1737 status = NO_ERROR;
1738 }
1739
Steve Block3856b092011-10-20 11:56:00 +01001740 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001741 mWaitWorkCV.broadcast();
1742
1743 return status;
1744}
1745
1746// destroyTrack_l() must be called with ThreadBase::mLock held
1747void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1748{
1749 track->mState = TrackBase::TERMINATED;
1750 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001751 removeTrack_l(track);
1752 }
1753}
1754
1755void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1756{
1757 mTracks.remove(track);
1758 deleteTrackName_l(track->name());
1759 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1760 if (chain != 0) {
1761 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001762 }
1763}
1764
1765String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1766{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001767 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001768 char *s;
1769
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001770 Mutex::Autolock _l(mLock);
1771 if (initCheck() != NO_ERROR) {
1772 return out_s8;
1773 }
1774
Dima Zavin799a70e2011-04-18 16:57:27 -07001775 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001776 out_s8 = String8(s);
1777 free(s);
1778 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001779}
1780
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001781// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001782void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1783 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001784 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001785
Steve Block3856b092011-10-20 11:56:00 +01001786 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001787
1788 switch (event) {
1789 case AudioSystem::OUTPUT_OPENED:
1790 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001791 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001792 desc.samplingRate = mSampleRate;
1793 desc.format = mFormat;
1794 desc.frameCount = mFrameCount;
1795 desc.latency = latency();
1796 param2 = &desc;
1797 break;
1798
1799 case AudioSystem::STREAM_CONFIG_CHANGED:
1800 param2 = &param;
1801 case AudioSystem::OUTPUT_CLOSED:
1802 default:
1803 break;
1804 }
1805 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1806}
1807
1808void AudioFlinger::PlaybackThread::readOutputParameters()
1809{
Dima Zavin799a70e2011-04-18 16:57:27 -07001810 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001811 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1812 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001813 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001814 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001815 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001816
1817 // FIXME - Current mixer implementation only supports stereo output: Always
1818 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001819 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001820 mMixBuffer = new int16_t[mFrameCount * 2];
1821 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1822
Eric Laurentde070132010-07-13 04:45:46 -07001823 // force reconfiguration of effect chains and engines to take new buffer size and audio
1824 // parameters into account
1825 // Note that mLock is not held when readOutputParameters() is called from the constructor
1826 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1827 // matter.
1828 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1829 Vector< sp<EffectChain> > effectChains = mEffectChains;
1830 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001831 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001832 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833}
1834
1835status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1836{
Glenn Kastena0d68332012-01-27 16:47:15 -08001837 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001838 return BAD_VALUE;
1839 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001840 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001841 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001842 return INVALID_OPERATION;
1843 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001844 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001845
Dima Zavin799a70e2011-04-18 16:57:27 -07001846 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001847}
1848
Eric Laurent39e94f82010-07-28 01:32:47 -07001849uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001850{
1851 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001852 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001854 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001855 }
1856
1857 for (size_t i = 0; i < mTracks.size(); ++i) {
1858 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001859 if (sessionId == track->sessionId() &&
1860 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001861 result |= TRACK_SESSION;
1862 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001863 }
1864 }
1865
Eric Laurent39e94f82010-07-28 01:32:47 -07001866 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001867}
1868
Eric Laurentde070132010-07-13 04:45:46 -07001869uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1870{
Dima Zavinfce7a472011-04-19 22:30:36 -07001871 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001872 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001873 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1874 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001875 }
1876 for (size_t i = 0; i < mTracks.size(); i++) {
1877 sp<Track> track = mTracks[i];
1878 if (sessionId == track->sessionId() &&
1879 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001880 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07001881 }
1882 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001883 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001884}
1885
Mathias Agopian65ab4712010-07-14 17:59:35 -07001886
Glenn Kastenaed850d2012-01-26 09:46:34 -08001887AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001888{
1889 Mutex::Autolock _l(mLock);
1890 return mOutput;
1891}
1892
1893AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1894{
1895 Mutex::Autolock _l(mLock);
1896 AudioStreamOut *output = mOutput;
1897 mOutput = NULL;
1898 return output;
1899}
1900
1901// this method must always be called either with ThreadBase mLock held or inside the thread loop
1902audio_stream_t* AudioFlinger::PlaybackThread::stream()
1903{
1904 if (mOutput == NULL) {
1905 return NULL;
1906 }
1907 return &mOutput->stream->common;
1908}
1909
Eric Laurent162b40b2011-12-05 09:47:19 -08001910uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1911{
1912 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1913 // decoding and transfer time. So sleeping for half of the latency would likely cause
1914 // underruns
1915 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1916 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1917 } else {
1918 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1919 }
1920}
1921
Mathias Agopian65ab4712010-07-14 17:59:35 -07001922// ----------------------------------------------------------------------------
1923
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001924AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001925 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten000f0e32012-03-01 17:10:56 -08001926 : PlaybackThread(audioFlinger, output, id, device, type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001927{
Glenn Kasten000f0e32012-03-01 17:10:56 -08001928 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001929 // FIXME - Current mixer implementation only supports stereo output
1930 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001931 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001932 }
1933}
1934
1935AudioFlinger::MixerThread::~MixerThread()
1936{
1937 delete mAudioMixer;
1938}
1939
Glenn Kasten83efdd02012-02-24 07:21:32 -08001940class CpuStats {
1941public:
1942 void sample();
1943#ifdef DEBUG_CPU_USAGE
1944private:
1945 ThreadCpuUsage mCpu;
1946#endif
1947};
1948
1949void CpuStats::sample() {
1950#ifdef DEBUG_CPU_USAGE
1951 const CentralTendencyStatistics& stats = mCpu.statistics();
1952 mCpu.sampleAndEnable();
1953 unsigned n = stats.n();
1954 // mCpu.elapsed() is expensive, so don't call it every loop
1955 if ((n & 127) == 1) {
1956 long long elapsed = mCpu.elapsed();
1957 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1958 double perLoop = elapsed / (double) n;
1959 double perLoop100 = perLoop * 0.01;
1960 double mean = stats.mean();
1961 double stddev = stats.stddev();
1962 double minimum = stats.minimum();
1963 double maximum = stats.maximum();
1964 mCpu.resetStatistics();
1965 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",
1966 elapsed * .000000001, n, perLoop * .000001,
1967 mean * .001,
1968 stddev * .001,
1969 minimum * .001,
1970 maximum * .001,
1971 mean / perLoop100,
1972 stddev / perLoop100,
1973 minimum / perLoop100,
1974 maximum / perLoop100);
1975 }
1976 }
1977#endif
1978};
1979
Glenn Kasten37d825e2012-02-24 07:21:48 -08001980void AudioFlinger::PlaybackThread::checkSilentMode_l()
1981{
1982 if (!mMasterMute) {
1983 char value[PROPERTY_VALUE_MAX];
1984 if (property_get("ro.audio.silent", value, "0") > 0) {
1985 char *endptr;
1986 unsigned long ul = strtoul(value, &endptr, 0);
1987 if (*endptr == '\0' && ul != 0) {
1988 ALOGD("Silence is golden");
1989 // The setprop command will not allow a property to be changed after
1990 // the first time it is set, so we don't have to worry about un-muting.
1991 setMasterMute_l(true);
1992 }
1993 }
1994 }
1995}
1996
Glenn Kasten000f0e32012-03-01 17:10:56 -08001997bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001998{
1999 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002000
Glenn Kasten000f0e32012-03-01 17:10:56 -08002001 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002002
2003 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002004 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002005if (mType == MIXER) {
2006 longStandbyExit = false;
2007}
Glenn Kasten688a6402012-02-29 07:57:06 -08002008
Glenn Kasten000f0e32012-03-01 17:10:56 -08002009 // DUPLICATING
2010 // FIXME could this be made local to while loop?
2011 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002012
Glenn Kasten66fcab92012-02-24 14:59:21 -08002013 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002014 sleepTime = idleSleepTime;
2015
2016if (mType == MIXER) {
2017 sleepTimeShift = 0;
2018}
2019
2020 // MIXER
Glenn Kasten83efdd02012-02-24 07:21:32 -08002021 CpuStats cpuStats;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002022
Eric Laurentfeb0db62011-07-22 09:04:31 -07002023 acquireWakeLock();
2024
Mathias Agopian65ab4712010-07-14 17:59:35 -07002025 while (!exitPending())
2026 {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002027if (mType == MIXER) {
Glenn Kasten83efdd02012-02-24 07:21:32 -08002028 cpuStats.sample();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002029}
Glenn Kasten688a6402012-02-29 07:57:06 -08002030
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002031 Vector< sp<EffectChain> > effectChains;
2032
Mathias Agopian65ab4712010-07-14 17:59:35 -07002033 processConfigEvents();
2034
Glenn Kastenfec279f2012-03-08 07:47:15 -08002035 mMixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002036 { // scope for mLock
2037
2038 Mutex::Autolock _l(mLock);
2039
2040 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002041 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002042 }
2043
Glenn Kastenfa26a852012-03-06 11:28:04 -08002044 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002045
Mathias Agopian65ab4712010-07-14 17:59:35 -07002046 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002047 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002048 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002049 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002050
2051 threadLoop_standby();
2052
Mathias Agopian65ab4712010-07-14 17:59:35 -07002053 mStandby = true;
2054 mBytesWritten = 0;
2055 }
2056
Glenn Kasten3e074702012-02-28 18:40:35 -08002057 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002058 // we're about to wait, flush the binder command buffer
2059 IPCThreadState::self()->flushCommands();
2060
Glenn Kastenfa26a852012-03-06 11:28:04 -08002061 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002062
Mathias Agopian65ab4712010-07-14 17:59:35 -07002063 if (exitPending()) break;
2064
Eric Laurentfeb0db62011-07-22 09:04:31 -07002065 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002066 // wait until we have something to do...
Glenn Kastenc0b52832012-02-24 11:18:09 -08002067 ALOGV("Thread %p type %d TID %d going to sleep", this, mType, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002068 mWaitWorkCV.wait(mLock);
Glenn Kastenc0b52832012-02-24 11:18:09 -08002069 ALOGV("Thread %p type %d TID %d waking up", this, mType, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002070 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002071
Eric Laurent27741442012-01-17 19:20:12 -08002072 mPrevMixerStatus = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002073
Glenn Kasten37d825e2012-02-24 07:21:48 -08002074 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002075
Glenn Kasten000f0e32012-03-01 17:10:56 -08002076 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002077 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002078 if (mType == MIXER) {
2079 sleepTimeShift = 0;
2080 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002081
Mathias Agopian65ab4712010-07-14 17:59:35 -07002082 continue;
2083 }
2084 }
2085
Glenn Kastenfec279f2012-03-08 07:47:15 -08002086 mixer_state newMixerStatus = prepareTracks_l(&tracksToRemove);
2087 // Shift in the new status; this could be a queue if it's
2088 // useful to filter the mixer status over several cycles.
2089 mPrevMixerStatus = mMixerStatus;
2090 mMixerStatus = newMixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002091
2092 // prevent any changes in effect chain list and in each effect chain
2093 // during mixing and effect process as the audio buffers could be deleted
2094 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002095 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002096 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002097
Glenn Kastenfec279f2012-03-08 07:47:15 -08002098 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002099 threadLoop_mix();
2100 } else {
2101 threadLoop_sleepTime();
2102 }
2103
2104 if (mSuspended > 0) {
2105 sleepTime = suspendSleepTimeUs();
2106 }
2107
2108 // only process effects if we're going to write
2109 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002110 for (size_t i = 0; i < effectChains.size(); i ++) {
2111 effectChains[i]->process_l();
2112 }
2113 }
2114
2115 // enable changes in effect chain
2116 unlockEffectChains(effectChains);
2117
2118 // sleepTime == 0 means we must write to audio hardware
2119 if (sleepTime == 0) {
2120
2121 threadLoop_write();
2122
2123if (mType == MIXER) {
2124 // write blocked detection
2125 nsecs_t now = systemTime();
2126 nsecs_t delta = now - mLastWriteTime;
2127 if (!mStandby && delta > maxPeriod) {
2128 mNumDelayedWrites++;
2129 if ((now - lastWarning) > kWarningThrottleNs) {
2130 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2131 ns2ms(delta), mNumDelayedWrites, this);
2132 lastWarning = now;
2133 }
2134 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2135 // a different threshold. Or completely removed for what it is worth anyway...
2136 if (mStandby) {
2137 longStandbyExit = true;
2138 }
2139 }
2140}
2141
2142 mStandby = false;
2143 } else {
2144 usleep(sleepTime);
2145 }
2146
2147 // finally let go of removed track(s), without the lock held
2148 // since we can't guarantee the destructors won't acquire that
2149 // same lock.
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002150 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002151
Glenn Kastenfa26a852012-03-06 11:28:04 -08002152 // FIXME I don't understand the need for this here;
2153 // it was in the original code but maybe the
2154 // assignment in saveOutputTracks() makes this unnecessary?
2155 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002156
2157 // Effect chains will be actually deleted here if they were removed from
2158 // mEffectChains list during mixing or effects processing
2159 effectChains.clear();
2160
2161 // FIXME Note that the above .clear() is no longer necessary since effectChains
2162 // is now local to this block, but will keep it for now (at least until merge done).
2163 }
2164
2165if (mType == MIXER || mType == DIRECT) {
2166 // put output stream into standby mode
2167 if (!mStandby) {
2168 mOutput->stream->common.standby(&mOutput->stream->common);
2169 }
2170}
2171if (mType == DUPLICATING) {
2172 // for DuplicatingThread, standby mode is handled by the outputTracks
2173}
2174
2175 releaseWakeLock();
2176
2177 ALOGV("Thread %p type %d exiting", this, mType);
2178 return false;
2179}
2180
2181// shared by MIXER and DIRECT, overridden by DUPLICATING
2182void AudioFlinger::PlaybackThread::threadLoop_write()
2183{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002184 // FIXME rewrite to reduce number of system calls
2185 mLastWriteTime = systemTime();
2186 mInWrite = true;
2187 mBytesWritten += mixBufferSize;
2188 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2189 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2190 mNumWrites++;
2191 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002192}
2193
2194// shared by MIXER and DIRECT, overridden by DUPLICATING
2195void AudioFlinger::PlaybackThread::threadLoop_standby()
2196{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002197 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2198 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002199}
2200
2201void AudioFlinger::MixerThread::threadLoop_mix()
2202{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002203 // obtain the presentation timestamp of the next output buffer
2204 int64_t pts;
2205 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002206
Glenn Kasten952eeb22012-03-06 11:30:57 -08002207 if (NULL != mOutput->stream->get_next_write_timestamp) {
2208 status = mOutput->stream->get_next_write_timestamp(
2209 mOutput->stream, &pts);
2210 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002211
Glenn Kasten952eeb22012-03-06 11:30:57 -08002212 if (status != NO_ERROR) {
2213 pts = AudioBufferProvider::kInvalidPTS;
2214 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002215
Glenn Kasten952eeb22012-03-06 11:30:57 -08002216 // mix buffers...
2217 mAudioMixer->process(pts);
2218 // increase sleep time progressively when application underrun condition clears.
2219 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2220 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2221 // such that we would underrun the audio HAL.
2222 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2223 sleepTimeShift--;
2224 }
2225 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002226 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002227 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002228}
2229
2230void AudioFlinger::MixerThread::threadLoop_sleepTime()
2231{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002232 // If no tracks are ready, sleep once for the duration of an output
2233 // buffer size, then write 0s to the output
2234 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002235 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002236 sleepTime = activeSleepTime >> sleepTimeShift;
2237 if (sleepTime < kMinThreadSleepTimeUs) {
2238 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002239 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002240 // reduce sleep time in case of consecutive application underruns to avoid
2241 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2242 // duration we would end up writing less data than needed by the audio HAL if
2243 // the condition persists.
2244 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2245 sleepTimeShift++;
2246 }
2247 } else {
2248 sleepTime = idleSleepTime;
2249 }
2250 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002251 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002252 memset (mMixBuffer, 0, mixBufferSize);
2253 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002254 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002255 }
2256 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002257}
2258
2259// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002260AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002261 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002262{
2263
Glenn Kasten29c23c32012-01-26 13:37:52 -08002264 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002265 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002266 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002267 size_t mixedTracks = 0;
2268 size_t tracksWithEffect = 0;
2269
2270 float masterVolume = mMasterVolume;
2271 bool masterMute = mMasterMute;
2272
Eric Laurent571d49c2010-08-11 05:20:11 -07002273 if (masterMute) {
2274 masterVolume = 0;
2275 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002276 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002277 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002278 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002279 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002280 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002281 masterVolume = (float)((v + (1 << 23)) >> 24);
2282 chain.clear();
2283 }
2284
2285 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002286 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002287 if (t == 0) continue;
2288
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002289 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002290 Track* const track = t.get();
2291 audio_track_cblk_t* cblk = track->cblk();
2292
2293 // The first time a track is added we wait
2294 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002295 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002296 // make sure that we have enough frames to mix one full buffer.
2297 // enforce this condition only once to enable draining the buffer in case the client
2298 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002299 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002300 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002301 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002302 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002303 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002304 if (t->sampleRate() == (int)mSampleRate) {
2305 minFrames = mFrameCount;
2306 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002307 // +1 for rounding and +1 for additional sample needed for interpolation
2308 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2309 // add frames already consumed but not yet released by the resampler
2310 // because cblk->framesReady() will include these frames
2311 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2312 // the minimum track buffer size is normally twice the number of frames necessary
2313 // to fill one buffer and the resampler should not leave more than one buffer worth
2314 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002315 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002316 }
2317 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002318 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002319 !track->isPaused() && !track->isTerminated())
2320 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002321 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002322
2323 mixedTracks++;
2324
2325 // track->mainBuffer() != mMixBuffer means there is an effect chain
2326 // connected to the track
2327 chain.clear();
2328 if (track->mainBuffer() != mMixBuffer) {
2329 chain = getEffectChain_l(track->sessionId());
2330 // Delegate volume control to effect in track effect chain if needed
2331 if (chain != 0) {
2332 tracksWithEffect++;
2333 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002334 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002335 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002336 }
2337 }
2338
2339
2340 int param = AudioMixer::VOLUME;
2341 if (track->mFillingUpStatus == Track::FS_FILLED) {
2342 // no ramp for the first volume setting
2343 track->mFillingUpStatus = Track::FS_ACTIVE;
2344 if (track->mState == TrackBase::RESUMING) {
2345 track->mState = TrackBase::ACTIVE;
2346 param = AudioMixer::RAMP_VOLUME;
2347 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002348 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002349 } else if (cblk->server != 0) {
2350 // If the track is stopped before the first frame was mixed,
2351 // do not apply ramp
2352 param = AudioMixer::RAMP_VOLUME;
2353 }
2354
2355 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002356 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002357 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002358 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002359 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002360 if (track->isPausing()) {
2361 track->setPaused();
2362 }
2363 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002364
Mathias Agopian65ab4712010-07-14 17:59:35 -07002365 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002366 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002367 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002368 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002369 vl = vlr & 0xFFFF;
2370 vr = vlr >> 16;
2371 // track volumes come from shared memory, so can't be trusted and must be clamped
2372 if (vl > MAX_GAIN_INT) {
2373 ALOGV("Track left volume out of range: %04X", vl);
2374 vl = MAX_GAIN_INT;
2375 }
2376 if (vr > MAX_GAIN_INT) {
2377 ALOGV("Track right volume out of range: %04X", vr);
2378 vr = MAX_GAIN_INT;
2379 }
2380 // now apply the master volume and stream type volume
2381 vl = (uint32_t)(v * vl) << 12;
2382 vr = (uint32_t)(v * vr) << 12;
2383 // assuming master volume and stream type volume each go up to 1.0,
2384 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002385
Glenn Kasten05632a52012-01-03 14:22:33 -08002386 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2387 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002388 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002389 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002390 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002391 }
2392 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002393 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002394 // Delegate volume control to effect in track effect chain if needed
2395 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2396 // Do not ramp volume if volume is controlled by effect
2397 param = AudioMixer::VOLUME;
2398 track->mHasVolumeController = true;
2399 } else {
2400 // force no volume ramp when volume controller was just disabled or removed
2401 // from effect chain to avoid volume spike
2402 if (track->mHasVolumeController) {
2403 param = AudioMixer::VOLUME;
2404 }
2405 track->mHasVolumeController = false;
2406 }
2407
2408 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002409 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002410 vl = (vl + (1 << 11)) >> 12;
2411 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2412 vr = (vr + (1 << 11)) >> 12;
2413 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002414
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002415 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 -07002416
Mathias Agopian65ab4712010-07-14 17:59:35 -07002417 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002418 mAudioMixer->setBufferProvider(name, track);
2419 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002420
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002421 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2422 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2423 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002424 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002425 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002426 AudioMixer::TRACK,
2427 AudioMixer::FORMAT, (void *)track->format());
2428 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002429 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002430 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002431 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002432 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002433 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002434 AudioMixer::RESAMPLE,
2435 AudioMixer::SAMPLE_RATE,
2436 (void *)(cblk->sampleRate));
2437 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002438 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002439 AudioMixer::TRACK,
2440 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2441 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002442 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002443 AudioMixer::TRACK,
2444 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2445
2446 // reset retry count
2447 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002448 // If one track is ready, set the mixer ready if:
2449 // - the mixer was not ready during previous round OR
2450 // - no other track is not ready
2451 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2452 mixerStatus != MIXER_TRACKS_ENABLED) {
2453 mixerStatus = MIXER_TRACKS_READY;
2454 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002455 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002456 //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 -07002457 if (track->isStopped()) {
2458 track->reset();
2459 }
2460 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2461 // We have consumed all the buffers of this track.
2462 // Remove it from the list of active tracks.
2463 tracksToRemove->add(track);
2464 } else {
2465 // No buffers for this track. Give it a few chances to
2466 // fill a buffer, then remove it from active list.
2467 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002468 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002469 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002470 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002471 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002472 // If one track is not ready, mark the mixer also not ready if:
2473 // - the mixer was ready during previous round OR
2474 // - no other track is ready
2475 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2476 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002477 mixerStatus = MIXER_TRACKS_ENABLED;
2478 }
2479 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002480 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002481 }
2482 }
2483
2484 // remove all the tracks that need to be...
2485 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002486 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002487 for (size_t i=0 ; i<count ; i++) {
2488 const sp<Track>& track = tracksToRemove->itemAt(i);
2489 mActiveTracks.remove(track);
2490 if (track->mainBuffer() != mMixBuffer) {
2491 chain = getEffectChain_l(track->sessionId());
2492 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002493 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002494 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002495 }
2496 }
2497 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002498 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002499 }
2500 }
2501 }
2502
2503 // mix buffer must be cleared if all tracks are connected to an
2504 // effect chain as in this case the mixer will not write to
2505 // mix buffer and track effects will accumulate into it
2506 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2507 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2508 }
2509
2510 return mixerStatus;
2511}
2512
Glenn Kasten66fcab92012-02-24 14:59:21 -08002513/*
2514The derived values that are cached:
2515 - mixBufferSize from frame count * frame size
2516 - activeSleepTime from activeSleepTimeUs()
2517 - idleSleepTime from idleSleepTimeUs()
2518 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2519 - maxPeriod from frame count and sample rate (MIXER only)
2520
2521The parameters that affect these derived values are:
2522 - frame count
2523 - frame size
2524 - sample rate
2525 - device type: A2DP or not
2526 - device latency
2527 - format: PCM or not
2528 - active sleep time
2529 - idle sleep time
2530*/
2531
2532void AudioFlinger::PlaybackThread::cacheParameters_l()
2533{
2534 mixBufferSize = mFrameCount * mFrameSize;
2535 activeSleepTime = activeSleepTimeUs();
2536 idleSleepTime = idleSleepTimeUs();
2537}
2538
Glenn Kastenfff6d712012-01-12 16:38:12 -08002539void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002540{
Steve Block3856b092011-10-20 11:56:00 +01002541 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002542 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002543 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002544
Mathias Agopian65ab4712010-07-14 17:59:35 -07002545 size_t size = mTracks.size();
2546 for (size_t i = 0; i < size; i++) {
2547 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08002548 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002549 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002550 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002551 }
2552 }
2553}
2554
Glenn Kastenfff6d712012-01-12 16:38:12 -08002555void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002556{
Steve Block3856b092011-10-20 11:56:00 +01002557 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002558 this, streamType, valid);
2559 Mutex::Autolock _l(mLock);
2560
2561 mStreamTypes[streamType].valid = valid;
2562}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002563
2564// getTrackName_l() must be called with ThreadBase::mLock held
2565int AudioFlinger::MixerThread::getTrackName_l()
2566{
2567 return mAudioMixer->getTrackName();
2568}
2569
2570// deleteTrackName_l() must be called with ThreadBase::mLock held
2571void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2572{
Steve Block3856b092011-10-20 11:56:00 +01002573 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002574 mAudioMixer->deleteTrackName(name);
2575}
2576
2577// checkForNewParameters_l() must be called with ThreadBase::mLock held
2578bool AudioFlinger::MixerThread::checkForNewParameters_l()
2579{
2580 bool reconfig = false;
2581
2582 while (!mNewParameters.isEmpty()) {
2583 status_t status = NO_ERROR;
2584 String8 keyValuePair = mNewParameters[0];
2585 AudioParameter param = AudioParameter(keyValuePair);
2586 int value;
2587
2588 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2589 reconfig = true;
2590 }
2591 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002592 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002593 status = BAD_VALUE;
2594 } else {
2595 reconfig = true;
2596 }
2597 }
2598 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002599 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002600 status = BAD_VALUE;
2601 } else {
2602 reconfig = true;
2603 }
2604 }
2605 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2606 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002607 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002608 // if frame count is changed after track creation
2609 if (!mTracks.isEmpty()) {
2610 status = INVALID_OPERATION;
2611 } else {
2612 reconfig = true;
2613 }
2614 }
2615 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002616 // when changing the audio output device, call addBatteryData to notify
2617 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002618 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002619 uint32_t params = 0;
2620 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002621 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002622 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2623 }
2624
2625 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002626 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002627 // check if any other device (except speaker) is on
2628 if (value & deviceWithoutSpeaker ) {
2629 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2630 }
2631
2632 if (params != 0) {
2633 addBatteryData(params);
2634 }
2635 }
2636
Mathias Agopian65ab4712010-07-14 17:59:35 -07002637 // forward device change to effects that have requested to be
2638 // aware of attached audio device.
2639 mDevice = (uint32_t)value;
2640 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002641 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002642 }
2643 }
2644
2645 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002646 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002647 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002648 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002649 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002650 mStandby = true;
2651 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002652 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002653 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002654 }
2655 if (status == NO_ERROR && reconfig) {
2656 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002657 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2658 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002659 readOutputParameters();
2660 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2661 for (size_t i = 0; i < mTracks.size() ; i++) {
2662 int name = getTrackName_l();
2663 if (name < 0) break;
2664 mTracks[i]->mName = name;
2665 // limit track sample rate to 2 x new output sample rate
2666 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2667 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2668 }
2669 }
2670 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2671 }
2672 }
2673
2674 mNewParameters.removeAt(0);
2675
2676 mParamStatus = status;
2677 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002678 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2679 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002680 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002681 }
2682 return reconfig;
2683}
2684
2685status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2686{
2687 const size_t SIZE = 256;
2688 char buffer[SIZE];
2689 String8 result;
2690
2691 PlaybackThread::dumpInternals(fd, args);
2692
2693 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2694 result.append(buffer);
2695 write(fd, result.string(), result.size());
2696 return NO_ERROR;
2697}
2698
Mathias Agopian65ab4712010-07-14 17:59:35 -07002699uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2700{
Eric Laurent60e18242010-07-29 06:50:24 -07002701 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002702}
2703
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002704uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2705{
2706 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2707}
2708
Glenn Kasten66fcab92012-02-24 14:59:21 -08002709void AudioFlinger::MixerThread::cacheParameters_l()
2710{
2711 PlaybackThread::cacheParameters_l();
2712
2713 // FIXME: Relaxed timing because of a certain device that can't meet latency
2714 // Should be reduced to 2x after the vendor fixes the driver issue
2715 // increase threshold again due to low power audio mode. The way this warning
2716 // threshold is calculated and its usefulness should be reconsidered anyway.
2717 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
2718}
2719
Mathias Agopian65ab4712010-07-14 17:59:35 -07002720// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002721AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2722 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002723 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002724 // mLeftVolFloat, mRightVolFloat
2725 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002726{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002727}
2728
2729AudioFlinger::DirectOutputThread::~DirectOutputThread()
2730{
2731}
2732
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002733AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
2734 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08002735)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002736{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002737 sp<Track> trackToRemove;
2738
Glenn Kastenfec279f2012-03-08 07:47:15 -08002739 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002740
Glenn Kasten952eeb22012-03-06 11:30:57 -08002741 // find out which tracks need to be processed
2742 if (mActiveTracks.size() != 0) {
2743 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08002744 // The track died recently
2745 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002746
Glenn Kasten952eeb22012-03-06 11:30:57 -08002747 Track* const track = t.get();
2748 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002749
Glenn Kasten952eeb22012-03-06 11:30:57 -08002750 // The first time a track is added we wait
2751 // for all its buffers to be filled before processing it
2752 if (cblk->framesReady() && track->isReady() &&
2753 !track->isPaused() && !track->isTerminated())
2754 {
2755 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002756
Glenn Kasten952eeb22012-03-06 11:30:57 -08002757 if (track->mFillingUpStatus == Track::FS_FILLED) {
2758 track->mFillingUpStatus = Track::FS_ACTIVE;
2759 mLeftVolFloat = mRightVolFloat = 0;
2760 mLeftVolShort = mRightVolShort = 0;
2761 if (track->mState == TrackBase::RESUMING) {
2762 track->mState = TrackBase::ACTIVE;
2763 rampVolume = true;
2764 }
2765 } else if (cblk->server != 0) {
2766 // If the track is stopped before the first frame was mixed,
2767 // do not apply ramp
2768 rampVolume = true;
2769 }
2770 // compute volume for this track
2771 float left, right;
2772 if (track->isMuted() || mMasterMute || track->isPausing() ||
2773 mStreamTypes[track->streamType()].mute) {
2774 left = right = 0;
2775 if (track->isPausing()) {
2776 track->setPaused();
2777 }
2778 } else {
2779 float typeVolume = mStreamTypes[track->streamType()].volume;
2780 float v = mMasterVolume * typeVolume;
2781 uint32_t vlr = cblk->getVolumeLR();
2782 float v_clamped = v * (vlr & 0xFFFF);
2783 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2784 left = v_clamped/MAX_GAIN;
2785 v_clamped = v * (vlr >> 16);
2786 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2787 right = v_clamped/MAX_GAIN;
2788 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002789
Glenn Kasten952eeb22012-03-06 11:30:57 -08002790 if (left != mLeftVolFloat || right != mRightVolFloat) {
2791 mLeftVolFloat = left;
2792 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002793
Glenn Kasten952eeb22012-03-06 11:30:57 -08002794 // If audio HAL implements volume control,
2795 // force software volume to nominal value
2796 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
2797 left = 1.0f;
2798 right = 1.0f;
2799 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002800
Glenn Kasten952eeb22012-03-06 11:30:57 -08002801 // Convert volumes from float to 8.24
2802 uint32_t vl = (uint32_t)(left * (1 << 24));
2803 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002804
Glenn Kasten952eeb22012-03-06 11:30:57 -08002805 // Delegate volume control to effect in track effect chain if needed
2806 // only one effect chain can be present on DirectOutputThread, so if
2807 // there is one, the track is connected to it
2808 if (!mEffectChains.isEmpty()) {
2809 // Do not ramp volume if volume is controlled by effect
2810 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002811 rampVolume = false;
2812 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002813 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002814
Glenn Kasten952eeb22012-03-06 11:30:57 -08002815 // Convert volumes from 8.24 to 4.12 format
2816 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2817 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2818 leftVol = (uint16_t)v_clamped;
2819 v_clamped = (vr + (1 << 11)) >> 12;
2820 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2821 rightVol = (uint16_t)v_clamped;
2822 } else {
2823 leftVol = mLeftVolShort;
2824 rightVol = mRightVolShort;
2825 rampVolume = false;
2826 }
2827
2828 // reset retry count
2829 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002830 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002831 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002832 } else {
2833 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2834 if (track->isStopped()) {
2835 track->reset();
2836 }
2837 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2838 // We have consumed all the buffers of this track.
2839 // Remove it from the list of active tracks.
2840 trackToRemove = track;
2841 } else {
2842 // No buffers for this track. Give it a few chances to
2843 // fill a buffer, then remove it from active list.
2844 if (--(track->mRetryCount) <= 0) {
2845 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2846 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002847 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002848 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002849 }
2850 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002851 }
2852 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002853
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002854 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08002855 // remove all the tracks that need to be...
2856 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002857 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002858 mActiveTracks.remove(trackToRemove);
2859 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002860 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08002861 trackToRemove->sessionId());
2862 mEffectChains[0]->decActiveTrackCnt();
2863 }
2864 if (trackToRemove->isTerminated()) {
2865 removeTrack_l(trackToRemove);
2866 }
2867 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002868
Glenn Kastenfec279f2012-03-08 07:47:15 -08002869 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002870}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002871
Glenn Kasten000f0e32012-03-01 17:10:56 -08002872void AudioFlinger::DirectOutputThread::threadLoop_mix()
2873{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002874 AudioBufferProvider::Buffer buffer;
2875 size_t frameCount = mFrameCount;
2876 int8_t *curBuf = (int8_t *)mMixBuffer;
2877 // output audio to hardware
2878 while (frameCount) {
2879 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002880 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002881 if (CC_UNLIKELY(buffer.raw == NULL)) {
2882 memset(curBuf, 0, frameCount * mFrameSize);
2883 break;
2884 }
2885 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2886 frameCount -= buffer.frameCount;
2887 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002888 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002889 }
2890 sleepTime = 0;
2891 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002892 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08002893
2894 // apply volume
2895
2896 // Do not apply volume on compressed audio
2897 if (!audio_is_linear_pcm(mFormat)) {
2898 return;
2899 }
2900
2901 // convert to signed 16 bit before volume calculation
2902 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
2903 size_t count = mFrameCount * mChannelCount;
2904 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2905 int16_t *dst = mMixBuffer + count-1;
2906 while(count--) {
2907 *dst-- = (int16_t)(*src--^0x80) << 8;
2908 }
2909 }
2910
2911 frameCount = mFrameCount;
2912 int16_t *out = mMixBuffer;
2913 if (rampVolume) {
2914 if (mChannelCount == 1) {
2915 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2916 int32_t vlInc = d / (int32_t)frameCount;
2917 int32_t vl = ((int32_t)mLeftVolShort << 16);
2918 do {
2919 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2920 out++;
2921 vl += vlInc;
2922 } while (--frameCount);
2923
2924 } else {
2925 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2926 int32_t vlInc = d / (int32_t)frameCount;
2927 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2928 int32_t vrInc = d / (int32_t)frameCount;
2929 int32_t vl = ((int32_t)mLeftVolShort << 16);
2930 int32_t vr = ((int32_t)mRightVolShort << 16);
2931 do {
2932 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2933 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2934 out += 2;
2935 vl += vlInc;
2936 vr += vrInc;
2937 } while (--frameCount);
2938 }
2939 } else {
2940 if (mChannelCount == 1) {
2941 do {
2942 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2943 out++;
2944 } while (--frameCount);
2945 } else {
2946 do {
2947 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2948 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2949 out += 2;
2950 } while (--frameCount);
2951 }
2952 }
2953
2954 // convert back to unsigned 8 bit after volume calculation
2955 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
2956 size_t count = mFrameCount * mChannelCount;
2957 int16_t *src = mMixBuffer;
2958 uint8_t *dst = (uint8_t *)mMixBuffer;
2959 while(count--) {
2960 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2961 }
2962 }
2963
2964 mLeftVolShort = leftVol;
2965 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002966}
2967
2968void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
2969{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002970 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002971 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002972 sleepTime = activeSleepTime;
2973 } else {
2974 sleepTime = idleSleepTime;
2975 }
2976 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
2977 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2978 sleepTime = 0;
2979 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002980}
2981
2982// getTrackName_l() must be called with ThreadBase::mLock held
2983int AudioFlinger::DirectOutputThread::getTrackName_l()
2984{
2985 return 0;
2986}
2987
2988// deleteTrackName_l() must be called with ThreadBase::mLock held
2989void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2990{
2991}
2992
2993// checkForNewParameters_l() must be called with ThreadBase::mLock held
2994bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2995{
2996 bool reconfig = false;
2997
2998 while (!mNewParameters.isEmpty()) {
2999 status_t status = NO_ERROR;
3000 String8 keyValuePair = mNewParameters[0];
3001 AudioParameter param = AudioParameter(keyValuePair);
3002 int value;
3003
3004 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3005 // do not accept frame count changes if tracks are open as the track buffer
3006 // size depends on frame count and correct behavior would not be garantied
3007 // if frame count is changed after track creation
3008 if (!mTracks.isEmpty()) {
3009 status = INVALID_OPERATION;
3010 } else {
3011 reconfig = true;
3012 }
3013 }
3014 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003015 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003016 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003017 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003018 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003019 mStandby = true;
3020 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07003021 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003022 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003023 }
3024 if (status == NO_ERROR && reconfig) {
3025 readOutputParameters();
3026 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3027 }
3028 }
3029
3030 mNewParameters.removeAt(0);
3031
3032 mParamStatus = status;
3033 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003034 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3035 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003036 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003037 }
3038 return reconfig;
3039}
3040
3041uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
3042{
3043 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003044 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003045 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003046 } else {
3047 time = 10000;
3048 }
3049 return time;
3050}
3051
3052uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
3053{
3054 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003055 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003056 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003057 } else {
3058 time = 10000;
3059 }
3060 return time;
3061}
3062
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003063uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
3064{
3065 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003066 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003067 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3068 } else {
3069 time = 10000;
3070 }
3071 return time;
3072}
3073
Glenn Kasten66fcab92012-02-24 14:59:21 -08003074void AudioFlinger::DirectOutputThread::cacheParameters_l()
3075{
3076 PlaybackThread::cacheParameters_l();
3077
3078 // use shorter standby delay as on normal output to release
3079 // hardware resources as soon as possible
3080 standbyDelay = microseconds(activeSleepTime*2);
3081}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003082
Mathias Agopian65ab4712010-07-14 17:59:35 -07003083// ----------------------------------------------------------------------------
3084
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003085AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003086 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003087 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3088 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003089{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003090 addOutputTrack(mainThread);
3091}
3092
3093AudioFlinger::DuplicatingThread::~DuplicatingThread()
3094{
3095 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3096 mOutputTracks[i]->destroy();
3097 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003098}
3099
Glenn Kasten000f0e32012-03-01 17:10:56 -08003100void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003101{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003102 // mix buffers...
3103 if (outputsReady(outputTracks)) {
3104 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3105 } else {
3106 memset(mMixBuffer, 0, mixBufferSize);
3107 }
3108 sleepTime = 0;
3109 writeFrames = mFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003110}
3111
3112void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3113{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003114 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003115 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003116 sleepTime = activeSleepTime;
3117 } else {
3118 sleepTime = idleSleepTime;
3119 }
3120 } else if (mBytesWritten != 0) {
3121 // flush remaining overflow buffers in output tracks
3122 for (size_t i = 0; i < outputTracks.size(); i++) {
3123 if (outputTracks[i]->isActive()) {
3124 sleepTime = 0;
3125 writeFrames = 0;
3126 memset(mMixBuffer, 0, mixBufferSize);
3127 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003128 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003129 }
3130 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003131}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003132
Glenn Kasten000f0e32012-03-01 17:10:56 -08003133void AudioFlinger::DuplicatingThread::threadLoop_write()
3134{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003135 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003136 for (size_t i = 0; i < outputTracks.size(); i++) {
3137 outputTracks[i]->write(mMixBuffer, writeFrames);
3138 }
3139 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003140}
Glenn Kasten688a6402012-02-29 07:57:06 -08003141
Glenn Kasten000f0e32012-03-01 17:10:56 -08003142void AudioFlinger::DuplicatingThread::threadLoop_standby()
3143{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003144 // DuplicatingThread implements standby by stopping all tracks
3145 for (size_t i = 0; i < outputTracks.size(); i++) {
3146 outputTracks[i]->stop();
3147 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003148}
3149
Glenn Kastenfa26a852012-03-06 11:28:04 -08003150void AudioFlinger::DuplicatingThread::saveOutputTracks()
3151{
3152 outputTracks = mOutputTracks;
3153}
3154
3155void AudioFlinger::DuplicatingThread::clearOutputTracks()
3156{
3157 outputTracks.clear();
3158}
3159
Mathias Agopian65ab4712010-07-14 17:59:35 -07003160void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3161{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003162 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003163 // FIXME explain this formula
Mathias Agopian65ab4712010-07-14 17:59:35 -07003164 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003165 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003166 this,
3167 mSampleRate,
3168 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003169 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003170 frameCount);
3171 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003172 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003173 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003174 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003175 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003176 }
3177}
3178
3179void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3180{
3181 Mutex::Autolock _l(mLock);
3182 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003183 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184 mOutputTracks[i]->destroy();
3185 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003186 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003187 return;
3188 }
3189 }
Steve Block3856b092011-10-20 11:56:00 +01003190 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003191}
3192
Glenn Kasten438b0362012-03-06 11:24:48 -08003193// caller must hold mLock
3194void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003195{
3196 mWaitTimeMs = UINT_MAX;
3197 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3198 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003199 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003200 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3201 if (waitTimeMs < mWaitTimeMs) {
3202 mWaitTimeMs = waitTimeMs;
3203 }
3204 }
3205 }
3206}
3207
3208
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003209bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003210{
3211 for (size_t i = 0; i < outputTracks.size(); i++) {
3212 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3213 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003214 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003215 return false;
3216 }
3217 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3218 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003219 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220 return false;
3221 }
3222 }
3223 return true;
3224}
3225
3226uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3227{
3228 return (mWaitTimeMs * 1000) / 2;
3229}
3230
Glenn Kasten66fcab92012-02-24 14:59:21 -08003231void AudioFlinger::DuplicatingThread::cacheParameters_l()
3232{
3233 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3234 updateWaitTime_l();
3235
3236 MixerThread::cacheParameters_l();
3237}
3238
Mathias Agopian65ab4712010-07-14 17:59:35 -07003239// ----------------------------------------------------------------------------
3240
3241// TrackBase constructor must be called with AudioFlinger::mLock held
3242AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003243 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003244 const sp<Client>& client,
3245 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003246 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003247 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003248 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003249 const sp<IMemory>& sharedBuffer,
3250 int sessionId)
3251 : RefBase(),
3252 mThread(thread),
3253 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003254 mCblk(NULL),
3255 // mBuffer
3256 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003257 mFrameCount(0),
3258 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003259 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003260 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003261 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003262 // mChannelCount
3263 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003264{
Steve Block3856b092011-10-20 11:56:00 +01003265 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003266
Steve Blockb8a80522011-12-20 16:23:08 +00003267 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003268 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003269 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003270 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3271 if (sharedBuffer == 0) {
3272 size += bufferSize;
3273 }
3274
3275 if (client != NULL) {
3276 mCblkMemory = client->heap()->allocate(size);
3277 if (mCblkMemory != 0) {
3278 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003279 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003280 new(mCblk) audio_track_cblk_t();
3281 // clear all buffers
3282 mCblk->frameCount = frameCount;
3283 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003284 mChannelCount = channelCount;
3285 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003286 if (sharedBuffer == 0) {
3287 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3288 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3289 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003290 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003291 mCblk->flags = CBLK_UNDERRUN_ON;
3292 } else {
3293 mBuffer = sharedBuffer->pointer();
3294 }
3295 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3296 }
3297 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003298 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003299 client->heap()->dump("AudioTrack");
3300 return;
3301 }
3302 } else {
3303 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003304 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003305 new(mCblk) audio_track_cblk_t();
3306 // clear all buffers
3307 mCblk->frameCount = frameCount;
3308 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003309 mChannelCount = channelCount;
3310 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003311 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3312 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3313 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003314 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003315 mCblk->flags = CBLK_UNDERRUN_ON;
3316 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003317 }
3318}
3319
3320AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3321{
Glenn Kastena0d68332012-01-27 16:47:15 -08003322 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003323 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003324 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003325 } else {
3326 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003327 }
3328 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003329 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003330 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003331 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003332 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003333 // If the client's reference count drops to zero, the associated destructor
3334 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3335 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003336 mClient.clear();
3337 }
3338}
3339
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003340// AudioBufferProvider interface
3341// getNextBuffer() = 0;
3342// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07003343void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3344{
Glenn Kastene0feee32011-12-13 11:53:26 -08003345 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003346 mFrameCount = buffer->frameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003347 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003348 buffer->frameCount = 0;
3349}
3350
3351bool AudioFlinger::ThreadBase::TrackBase::step() {
3352 bool result;
3353 audio_track_cblk_t* cblk = this->cblk();
3354
3355 result = cblk->stepServer(mFrameCount);
3356 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003357 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003358 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003359 }
3360 return result;
3361}
3362
3363void AudioFlinger::ThreadBase::TrackBase::reset() {
3364 audio_track_cblk_t* cblk = this->cblk();
3365
3366 cblk->user = 0;
3367 cblk->server = 0;
3368 cblk->userBase = 0;
3369 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003370 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01003371 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003372}
3373
Mathias Agopian65ab4712010-07-14 17:59:35 -07003374int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3375 return (int)mCblk->sampleRate;
3376}
3377
Mathias Agopian65ab4712010-07-14 17:59:35 -07003378void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3379 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003380 size_t frameSize = cblk->frameSize;
3381 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3382 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003383
3384 // Check validity of returned pointer in case the track control block would have been corrupted.
3385 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003386 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003387 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 -07003388 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003389 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003390 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003391 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003392 }
3393
3394 return bufferStart;
3395}
3396
3397// ----------------------------------------------------------------------------
3398
3399// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3400AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003401 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003402 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003403 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003404 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003405 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003406 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003407 int frameCount,
3408 const sp<IMemory>& sharedBuffer,
3409 int sessionId)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003410 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003411 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3412 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003413{
3414 if (mCblk != NULL) {
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003415 if (thread != NULL) {
3416 mName = thread->getTrackName_l();
3417 mMainBuffer = thread->mixBuffer();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003418 }
Glenn Kasten23d82a92012-02-03 11:10:00 -08003419 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003420 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003421 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003422 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003423 mStreamType = streamType;
3424 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3425 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003426 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003427 }
3428}
3429
3430AudioFlinger::PlaybackThread::Track::~Track()
3431{
Steve Block3856b092011-10-20 11:56:00 +01003432 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003433 sp<ThreadBase> thread = mThread.promote();
3434 if (thread != 0) {
3435 Mutex::Autolock _l(thread->mLock);
3436 mState = TERMINATED;
3437 }
3438}
3439
3440void AudioFlinger::PlaybackThread::Track::destroy()
3441{
3442 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3443 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08003444 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003445 // we must acquire a strong reference on this Track before locking mLock
3446 // here so that the destructor is called only when exiting this function.
3447 // On the other hand, as long as Track::destroy() is only called by
3448 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3449 // this Track with its member mTrack.
3450 sp<Track> keep(this);
3451 { // scope for mLock
3452 sp<ThreadBase> thread = mThread.promote();
3453 if (thread != 0) {
3454 if (!isOutputTrack()) {
3455 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08003456 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003457
3458 // to track the speaker usage
3459 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003460 }
3461 AudioSystem::releaseOutput(thread->id());
3462 }
3463 Mutex::Autolock _l(thread->mLock);
3464 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3465 playbackThread->destroyTrack_l(this);
3466 }
3467 }
3468}
3469
3470void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3471{
Glenn Kasten83d86532012-01-17 14:39:34 -08003472 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003473 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 -07003474 mName - AudioMixer::TRACK0,
Glenn Kasten44deb052012-02-05 18:09:08 -08003475 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003476 mStreamType,
3477 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003478 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003479 mSessionId,
3480 mFrameCount,
3481 mState,
3482 mMute,
3483 mFillingUpStatus,
3484 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003485 vlr & 0xFFFF,
3486 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003487 mCblk->server,
3488 mCblk->user,
3489 (int)mMainBuffer,
3490 (int)mAuxBuffer);
3491}
3492
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003493// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08003494status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
3495 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003496{
3497 audio_track_cblk_t* cblk = this->cblk();
3498 uint32_t framesReady;
3499 uint32_t framesReq = buffer->frameCount;
3500
3501 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003502 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003503 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003504 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003505 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003506 }
3507
3508 framesReady = cblk->framesReady();
3509
Glenn Kastenf6b16782011-12-15 09:51:17 -08003510 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003511 uint32_t s = cblk->server;
3512 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3513
3514 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3515 if (framesReq > framesReady) {
3516 framesReq = framesReady;
3517 }
3518 if (s + framesReq > bufferEnd) {
3519 framesReq = bufferEnd - s;
3520 }
3521
3522 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003523 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003524
3525 buffer->frameCount = framesReq;
3526 return NO_ERROR;
3527 }
3528
3529getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003530 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003531 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003532 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003533 return NOT_ENOUGH_DATA;
3534}
3535
John Grossman4ff14ba2012-02-08 16:37:41 -08003536uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const{
3537 return mCblk->framesReady();
3538}
3539
Mathias Agopian65ab4712010-07-14 17:59:35 -07003540bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003541 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003542
John Grossman4ff14ba2012-02-08 16:37:41 -08003543 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003544 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3545 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003546 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003547 return true;
3548 }
3549 return false;
3550}
3551
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003552status_t AudioFlinger::PlaybackThread::Track::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003553{
3554 status_t status = NO_ERROR;
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003555 ALOGV("start(%d), calling pid %d session %d tid %d",
3556 mName, IPCThreadState::self()->getCallingPid(), mSessionId, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003557 sp<ThreadBase> thread = mThread.promote();
3558 if (thread != 0) {
3559 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003560 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003561 // here the track could be either new, or restarted
3562 // in both cases "unstop" the track
3563 if (mState == PAUSED) {
3564 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003565 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003566 } else {
3567 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003568 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003569 }
3570
3571 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3572 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003573 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003574 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003575
3576 // to track the speaker usage
3577 if (status == NO_ERROR) {
3578 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3579 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003580 }
3581 if (status == NO_ERROR) {
3582 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3583 playbackThread->addTrack_l(this);
3584 } else {
3585 mState = state;
3586 }
3587 } else {
3588 status = BAD_VALUE;
3589 }
3590 return status;
3591}
3592
3593void AudioFlinger::PlaybackThread::Track::stop()
3594{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003595 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003596 sp<ThreadBase> thread = mThread.promote();
3597 if (thread != 0) {
3598 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003599 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003600 if (mState > STOPPED) {
3601 mState = STOPPED;
3602 // If the track is not active (PAUSED and buffers full), flush buffers
3603 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3604 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3605 reset();
3606 }
Steve Block3856b092011-10-20 11:56:00 +01003607 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003608 }
3609 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3610 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003611 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003612 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003613
3614 // to track the speaker usage
3615 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003616 }
3617 }
3618}
3619
3620void AudioFlinger::PlaybackThread::Track::pause()
3621{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003622 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003623 sp<ThreadBase> thread = mThread.promote();
3624 if (thread != 0) {
3625 Mutex::Autolock _l(thread->mLock);
3626 if (mState == ACTIVE || mState == RESUMING) {
3627 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003628 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003629 if (!isOutputTrack()) {
3630 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003631 AudioSystem::stopOutput(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 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003636 }
3637 }
3638 }
3639}
3640
3641void AudioFlinger::PlaybackThread::Track::flush()
3642{
Steve Block3856b092011-10-20 11:56:00 +01003643 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003644 sp<ThreadBase> thread = mThread.promote();
3645 if (thread != 0) {
3646 Mutex::Autolock _l(thread->mLock);
3647 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3648 return;
3649 }
3650 // No point remaining in PAUSED state after a flush => go to
3651 // STOPPED state
3652 mState = STOPPED;
3653
Eric Laurent38ccae22011-03-28 18:37:07 -07003654 // do not reset the track if it is still in the process of being stopped or paused.
3655 // this will be done by prepareTracks_l() when the track is stopped.
3656 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3657 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3658 reset();
3659 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003660 }
3661}
3662
3663void AudioFlinger::PlaybackThread::Track::reset()
3664{
3665 // Do not reset twice to avoid discarding data written just after a flush and before
3666 // the audioflinger thread detects the track is stopped.
3667 if (!mResetDone) {
3668 TrackBase::reset();
3669 // Force underrun condition to avoid false underrun callback until first data is
3670 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003671 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3672 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003673 mFillingUpStatus = FS_FILLING;
3674 mResetDone = true;
3675 }
3676}
3677
3678void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3679{
3680 mMute = muted;
3681}
3682
Mathias Agopian65ab4712010-07-14 17:59:35 -07003683status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3684{
3685 status_t status = DEAD_OBJECT;
3686 sp<ThreadBase> thread = mThread.promote();
3687 if (thread != 0) {
3688 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3689 status = playbackThread->attachAuxEffect(this, EffectId);
3690 }
3691 return status;
3692}
3693
3694void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3695{
3696 mAuxEffectId = EffectId;
3697 mAuxBuffer = buffer;
3698}
3699
John Grossman4ff14ba2012-02-08 16:37:41 -08003700// timed audio tracks
3701
3702sp<AudioFlinger::PlaybackThread::TimedTrack>
3703AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003704 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003705 const sp<Client>& client,
3706 audio_stream_type_t streamType,
3707 uint32_t sampleRate,
3708 audio_format_t format,
3709 uint32_t channelMask,
3710 int frameCount,
3711 const sp<IMemory>& sharedBuffer,
3712 int sessionId) {
3713 if (!client->reserveTimedTrack())
3714 return NULL;
3715
3716 sp<TimedTrack> track = new TimedTrack(
3717 thread, client, streamType, sampleRate, format, channelMask, frameCount,
3718 sharedBuffer, sessionId);
3719
3720 if (track == NULL) {
3721 client->releaseTimedTrack();
3722 return NULL;
3723 }
3724
3725 return track;
3726}
3727
3728AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003729 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003730 const sp<Client>& client,
3731 audio_stream_type_t streamType,
3732 uint32_t sampleRate,
3733 audio_format_t format,
3734 uint32_t channelMask,
3735 int frameCount,
3736 const sp<IMemory>& sharedBuffer,
3737 int sessionId)
3738 : Track(thread, client, streamType, sampleRate, format, channelMask,
3739 frameCount, sharedBuffer, sessionId),
3740 mTimedSilenceBuffer(NULL),
3741 mTimedSilenceBufferSize(0),
3742 mTimedAudioOutputOnTime(false),
3743 mMediaTimeTransformValid(false)
3744{
3745 LocalClock lc;
3746 mLocalTimeFreq = lc.getLocalFreq();
3747
3748 mLocalTimeToSampleTransform.a_zero = 0;
3749 mLocalTimeToSampleTransform.b_zero = 0;
3750 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3751 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3752 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3753 &mLocalTimeToSampleTransform.a_to_b_denom);
3754}
3755
3756AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3757 mClient->releaseTimedTrack();
3758 delete [] mTimedSilenceBuffer;
3759}
3760
3761status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3762 size_t size, sp<IMemory>* buffer) {
3763
3764 Mutex::Autolock _l(mTimedBufferQueueLock);
3765
3766 trimTimedBufferQueue_l();
3767
3768 // lazily initialize the shared memory heap for timed buffers
3769 if (mTimedMemoryDealer == NULL) {
3770 const int kTimedBufferHeapSize = 512 << 10;
3771
3772 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3773 "AudioFlingerTimed");
3774 if (mTimedMemoryDealer == NULL)
3775 return NO_MEMORY;
3776 }
3777
3778 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3779 if (newBuffer == NULL) {
3780 newBuffer = mTimedMemoryDealer->allocate(size);
3781 if (newBuffer == NULL)
3782 return NO_MEMORY;
3783 }
3784
3785 *buffer = newBuffer;
3786 return NO_ERROR;
3787}
3788
3789// caller must hold mTimedBufferQueueLock
3790void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
3791 int64_t mediaTimeNow;
3792 {
3793 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3794 if (!mMediaTimeTransformValid)
3795 return;
3796
3797 int64_t targetTimeNow;
3798 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
3799 ? mCCHelper.getCommonTime(&targetTimeNow)
3800 : mCCHelper.getLocalTime(&targetTimeNow);
3801
3802 if (OK != res)
3803 return;
3804
3805 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
3806 &mediaTimeNow)) {
3807 return;
3808 }
3809 }
3810
3811 size_t trimIndex;
3812 for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
3813 if (mTimedBufferQueue[trimIndex].pts() > mediaTimeNow)
3814 break;
3815 }
3816
3817 if (trimIndex) {
3818 mTimedBufferQueue.removeItemsAt(0, trimIndex);
3819 }
3820}
3821
3822status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
3823 const sp<IMemory>& buffer, int64_t pts) {
3824
3825 {
3826 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3827 if (!mMediaTimeTransformValid)
3828 return INVALID_OPERATION;
3829 }
3830
3831 Mutex::Autolock _l(mTimedBufferQueueLock);
3832
3833 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
3834
3835 return NO_ERROR;
3836}
3837
3838status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
3839 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
3840
3841 ALOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
3842 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
3843 target);
3844
3845 if (!(target == TimedAudioTrack::LOCAL_TIME ||
3846 target == TimedAudioTrack::COMMON_TIME)) {
3847 return BAD_VALUE;
3848 }
3849
3850 Mutex::Autolock lock(mMediaTimeTransformLock);
3851 mMediaTimeTransform = xform;
3852 mMediaTimeTransformTarget = target;
3853 mMediaTimeTransformValid = true;
3854
3855 return NO_ERROR;
3856}
3857
3858#define min(a, b) ((a) < (b) ? (a) : (b))
3859
3860// implementation of getNextBuffer for tracks whose buffers have timestamps
3861status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
3862 AudioBufferProvider::Buffer* buffer, int64_t pts)
3863{
3864 if (pts == AudioBufferProvider::kInvalidPTS) {
3865 buffer->raw = 0;
3866 buffer->frameCount = 0;
3867 return INVALID_OPERATION;
3868 }
3869
John Grossman4ff14ba2012-02-08 16:37:41 -08003870 Mutex::Autolock _l(mTimedBufferQueueLock);
3871
3872 while (true) {
3873
3874 // if we have no timed buffers, then fail
3875 if (mTimedBufferQueue.isEmpty()) {
3876 buffer->raw = 0;
3877 buffer->frameCount = 0;
3878 return NOT_ENOUGH_DATA;
3879 }
3880
3881 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
3882
3883 // calculate the PTS of the head of the timed buffer queue expressed in
3884 // local time
3885 int64_t headLocalPTS;
3886 {
3887 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3888
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003889 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08003890
3891 if (mMediaTimeTransform.a_to_b_denom == 0) {
3892 // the transform represents a pause, so yield silence
3893 timedYieldSilence(buffer->frameCount, buffer);
3894 return NO_ERROR;
3895 }
3896
3897 int64_t transformedPTS;
3898 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
3899 &transformedPTS)) {
3900 // the transform failed. this shouldn't happen, but if it does
3901 // then just drop this buffer
3902 ALOGW("timedGetNextBuffer transform failed");
3903 buffer->raw = 0;
3904 buffer->frameCount = 0;
3905 mTimedBufferQueue.removeAt(0);
3906 return NO_ERROR;
3907 }
3908
3909 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
3910 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
3911 &headLocalPTS)) {
3912 buffer->raw = 0;
3913 buffer->frameCount = 0;
3914 return INVALID_OPERATION;
3915 }
3916 } else {
3917 headLocalPTS = transformedPTS;
3918 }
3919 }
3920
3921 // adjust the head buffer's PTS to reflect the portion of the head buffer
3922 // that has already been consumed
3923 int64_t effectivePTS = headLocalPTS +
3924 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
3925
3926 // Calculate the delta in samples between the head of the input buffer
3927 // queue and the start of the next output buffer that will be written.
3928 // If the transformation fails because of over or underflow, it means
3929 // that the sample's position in the output stream is so far out of
3930 // whack that it should just be dropped.
3931 int64_t sampleDelta;
3932 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
3933 ALOGV("*** head buffer is too far from PTS: dropped buffer");
3934 mTimedBufferQueue.removeAt(0);
3935 continue;
3936 }
3937 if (!mLocalTimeToSampleTransform.doForwardTransform(
3938 (effectivePTS - pts) << 32, &sampleDelta)) {
3939 ALOGV("*** too late during sample rate transform: dropped buffer");
3940 mTimedBufferQueue.removeAt(0);
3941 continue;
3942 }
3943
3944 ALOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
3945 __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
3946 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
3947 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
3948
3949 // if the delta between the ideal placement for the next input sample and
3950 // the current output position is within this threshold, then we will
3951 // concatenate the next input samples to the previous output
3952 const int64_t kSampleContinuityThreshold =
3953 (static_cast<int64_t>(sampleRate()) << 32) / 10;
3954
3955 // if this is the first buffer of audio that we're emitting from this track
3956 // then it should be almost exactly on time.
3957 const int64_t kSampleStartupThreshold = 1LL << 32;
3958
3959 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
3960 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
3961 // the next input is close enough to being on time, so concatenate it
3962 // with the last output
3963 timedYieldSamples(buffer);
3964
3965 ALOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
3966 return NO_ERROR;
3967 } else if (sampleDelta > 0) {
3968 // the gap between the current output position and the proper start of
3969 // the next input sample is too big, so fill it with silence
3970 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
3971
3972 timedYieldSilence(framesUntilNextInput, buffer);
3973 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
3974 return NO_ERROR;
3975 } else {
3976 // the next input sample is late
3977 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
3978 size_t onTimeSamplePosition =
3979 head.position() + lateFrames * mCblk->frameSize;
3980
3981 if (onTimeSamplePosition > head.buffer()->size()) {
3982 // all the remaining samples in the head are too late, so
3983 // drop it and move on
3984 ALOGV("*** too late: dropped buffer");
3985 mTimedBufferQueue.removeAt(0);
3986 continue;
3987 } else {
3988 // skip over the late samples
3989 head.setPosition(onTimeSamplePosition);
3990
3991 // yield the available samples
3992 timedYieldSamples(buffer);
3993
3994 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
3995 return NO_ERROR;
3996 }
3997 }
3998 }
3999}
4000
4001// Yield samples from the timed buffer queue head up to the given output
4002// buffer's capacity.
4003//
4004// Caller must hold mTimedBufferQueueLock
4005void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples(
4006 AudioBufferProvider::Buffer* buffer) {
4007
4008 const TimedBuffer& head = mTimedBufferQueue[0];
4009
4010 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4011 head.position());
4012
4013 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4014 mCblk->frameSize);
4015 size_t framesRequested = buffer->frameCount;
4016 buffer->frameCount = min(framesLeftInHead, framesRequested);
4017
4018 mTimedAudioOutputOnTime = true;
4019}
4020
4021// Yield samples of silence up to the given output buffer's capacity
4022//
4023// Caller must hold mTimedBufferQueueLock
4024void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence(
4025 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4026
4027 // lazily allocate a buffer filled with silence
4028 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4029 delete [] mTimedSilenceBuffer;
4030 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4031 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4032 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4033 }
4034
4035 buffer->raw = mTimedSilenceBuffer;
4036 size_t framesRequested = buffer->frameCount;
4037 buffer->frameCount = min(numFrames, framesRequested);
4038
4039 mTimedAudioOutputOnTime = false;
4040}
4041
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004042// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004043void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4044 AudioBufferProvider::Buffer* buffer) {
4045
4046 Mutex::Autolock _l(mTimedBufferQueueLock);
4047
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004048 // If the buffer which was just released is part of the buffer at the head
4049 // of the queue, be sure to update the amt of the buffer which has been
4050 // consumed. If the buffer being returned is not part of the head of the
4051 // queue, its either because the buffer is part of the silence buffer, or
4052 // because the head of the timed queue was trimmed after the mixer called
4053 // getNextBuffer but before the mixer called releaseBuffer.
4054 if ((buffer->raw != mTimedSilenceBuffer) && mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004055 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004056
4057 void* start = head.buffer()->pointer();
Glenn Kastenf063b492012-02-17 16:24:10 -08004058 void* end = (char *) head.buffer()->pointer() + head.buffer()->size();
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004059
4060 if ((buffer->raw >= start) && (buffer->raw <= end)) {
4061 head.setPosition(head.position() +
4062 (buffer->frameCount * mCblk->frameSize));
4063 if (static_cast<size_t>(head.position()) >= head.buffer()->size()) {
4064 mTimedBufferQueue.removeAt(0);
4065 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004066 }
4067 }
4068
4069 buffer->raw = 0;
4070 buffer->frameCount = 0;
4071}
4072
4073uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4074 Mutex::Autolock _l(mTimedBufferQueueLock);
4075
4076 uint32_t frames = 0;
4077 for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4078 const TimedBuffer& tb = mTimedBufferQueue[i];
4079 frames += (tb.buffer()->size() - tb.position()) / mCblk->frameSize;
4080 }
4081
4082 return frames;
4083}
4084
4085AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4086 : mPTS(0), mPosition(0) {}
4087
4088AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4089 const sp<IMemory>& buffer, int64_t pts)
4090 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4091
Mathias Agopian65ab4712010-07-14 17:59:35 -07004092// ----------------------------------------------------------------------------
4093
4094// RecordTrack constructor must be called with AudioFlinger::mLock held
4095AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004096 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004097 const sp<Client>& client,
4098 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004099 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004100 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004101 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004102 int sessionId)
4103 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004104 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004105 mOverflow(false)
4106{
4107 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01004108 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07004109 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004110 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07004111 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004112 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004113 } else {
4114 mCblk->frameSize = sizeof(int8_t);
4115 }
4116 }
4117}
4118
4119AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4120{
4121 sp<ThreadBase> thread = mThread.promote();
4122 if (thread != 0) {
4123 AudioSystem::releaseInput(thread->id());
4124 }
4125}
4126
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004127// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004128status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004129{
4130 audio_track_cblk_t* cblk = this->cblk();
4131 uint32_t framesAvail;
4132 uint32_t framesReq = buffer->frameCount;
4133
4134 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004135 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004136 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004137 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004138 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004139 }
4140
4141 framesAvail = cblk->framesAvailable_l();
4142
Glenn Kastenf6b16782011-12-15 09:51:17 -08004143 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004144 uint32_t s = cblk->server;
4145 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4146
4147 if (framesReq > framesAvail) {
4148 framesReq = framesAvail;
4149 }
4150 if (s + framesReq > bufferEnd) {
4151 framesReq = bufferEnd - s;
4152 }
4153
4154 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004155 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004156
4157 buffer->frameCount = framesReq;
4158 return NO_ERROR;
4159 }
4160
4161getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004162 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004163 buffer->frameCount = 0;
4164 return NOT_ENOUGH_DATA;
4165}
4166
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004167status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004168{
4169 sp<ThreadBase> thread = mThread.promote();
4170 if (thread != 0) {
4171 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004172 return recordThread->start(this, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004173 } else {
4174 return BAD_VALUE;
4175 }
4176}
4177
4178void AudioFlinger::RecordThread::RecordTrack::stop()
4179{
4180 sp<ThreadBase> thread = mThread.promote();
4181 if (thread != 0) {
4182 RecordThread *recordThread = (RecordThread *)thread.get();
4183 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004184 TrackBase::reset();
4185 // Force overerrun condition to avoid false overrun callback until first data is
4186 // read from buffer
4187 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004188 }
4189}
4190
4191void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4192{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004193 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004194 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004195 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004196 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004197 mSessionId,
4198 mFrameCount,
4199 mState,
4200 mCblk->sampleRate,
4201 mCblk->server,
4202 mCblk->user);
4203}
4204
4205
4206// ----------------------------------------------------------------------------
4207
4208AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004209 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004210 DuplicatingThread *sourceThread,
4211 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004212 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004213 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004214 int frameCount)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004215 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004216 mActive(false), mSourceThread(sourceThread)
4217{
4218
Mathias Agopian65ab4712010-07-14 17:59:35 -07004219 if (mCblk != NULL) {
4220 mCblk->flags |= CBLK_DIRECTION_OUT;
4221 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004222 mOutBuffer.frameCount = 0;
4223 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01004224 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004225 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4226 mCblk, mBuffer, mCblk->buffers,
4227 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004228 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004229 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004230 }
4231}
4232
4233AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4234{
4235 clearBufferQueue();
4236}
4237
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004238status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004239{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004240 status_t status = Track::start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004241 if (status != NO_ERROR) {
4242 return status;
4243 }
4244
4245 mActive = true;
4246 mRetryCount = 127;
4247 return status;
4248}
4249
4250void AudioFlinger::PlaybackThread::OutputTrack::stop()
4251{
4252 Track::stop();
4253 clearBufferQueue();
4254 mOutBuffer.frameCount = 0;
4255 mActive = false;
4256}
4257
4258bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4259{
4260 Buffer *pInBuffer;
4261 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004262 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004263 bool outputBufferFull = false;
4264 inBuffer.frameCount = frames;
4265 inBuffer.i16 = data;
4266
4267 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4268
4269 if (!mActive && frames != 0) {
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004270 start(0);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004271 sp<ThreadBase> thread = mThread.promote();
4272 if (thread != 0) {
4273 MixerThread *mixerThread = (MixerThread *)thread.get();
4274 if (mCblk->frameCount > frames){
4275 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4276 uint32_t startFrames = (mCblk->frameCount - frames);
4277 pInBuffer = new Buffer;
4278 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4279 pInBuffer->frameCount = startFrames;
4280 pInBuffer->i16 = pInBuffer->mBuffer;
4281 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4282 mBufferQueue.add(pInBuffer);
4283 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004284 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004285 }
4286 }
4287 }
4288 }
4289
4290 while (waitTimeLeftMs) {
4291 // First write pending buffers, then new data
4292 if (mBufferQueue.size()) {
4293 pInBuffer = mBufferQueue.itemAt(0);
4294 } else {
4295 pInBuffer = &inBuffer;
4296 }
4297
4298 if (pInBuffer->frameCount == 0) {
4299 break;
4300 }
4301
4302 if (mOutBuffer.frameCount == 0) {
4303 mOutBuffer.frameCount = pInBuffer->frameCount;
4304 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08004305 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01004306 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004307 outputBufferFull = true;
4308 break;
4309 }
4310 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4311 if (waitTimeLeftMs >= waitTimeMs) {
4312 waitTimeLeftMs -= waitTimeMs;
4313 } else {
4314 waitTimeLeftMs = 0;
4315 }
4316 }
4317
4318 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4319 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4320 mCblk->stepUser(outFrames);
4321 pInBuffer->frameCount -= outFrames;
4322 pInBuffer->i16 += outFrames * channelCount;
4323 mOutBuffer.frameCount -= outFrames;
4324 mOutBuffer.i16 += outFrames * channelCount;
4325
4326 if (pInBuffer->frameCount == 0) {
4327 if (mBufferQueue.size()) {
4328 mBufferQueue.removeAt(0);
4329 delete [] pInBuffer->mBuffer;
4330 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01004331 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004332 } else {
4333 break;
4334 }
4335 }
4336 }
4337
4338 // If we could not write all frames, allocate a buffer and queue it for next time.
4339 if (inBuffer.frameCount) {
4340 sp<ThreadBase> thread = mThread.promote();
4341 if (thread != 0 && !thread->standby()) {
4342 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4343 pInBuffer = new Buffer;
4344 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4345 pInBuffer->frameCount = inBuffer.frameCount;
4346 pInBuffer->i16 = pInBuffer->mBuffer;
4347 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4348 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01004349 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004350 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004351 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004352 }
4353 }
4354 }
4355
4356 // Calling write() with a 0 length buffer, means that no more data will be written:
4357 // If no more buffers are pending, fill output track buffer to make sure it is started
4358 // by output mixer.
4359 if (frames == 0 && mBufferQueue.size() == 0) {
4360 if (mCblk->user < mCblk->frameCount) {
4361 frames = mCblk->frameCount - mCblk->user;
4362 pInBuffer = new Buffer;
4363 pInBuffer->mBuffer = new int16_t[frames * channelCount];
4364 pInBuffer->frameCount = frames;
4365 pInBuffer->i16 = pInBuffer->mBuffer;
4366 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4367 mBufferQueue.add(pInBuffer);
4368 } else if (mActive) {
4369 stop();
4370 }
4371 }
4372
4373 return outputBufferFull;
4374}
4375
4376status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4377{
4378 int active;
4379 status_t result;
4380 audio_track_cblk_t* cblk = mCblk;
4381 uint32_t framesReq = buffer->frameCount;
4382
Steve Block3856b092011-10-20 11:56:00 +01004383// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004384 buffer->frameCount = 0;
4385
4386 uint32_t framesAvail = cblk->framesAvailable();
4387
4388
4389 if (framesAvail == 0) {
4390 Mutex::Autolock _l(cblk->lock);
4391 goto start_loop_here;
4392 while (framesAvail == 0) {
4393 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004394 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004395 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004396 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004397 }
4398 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4399 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004400 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004401 }
4402 // read the server count again
4403 start_loop_here:
4404 framesAvail = cblk->framesAvailable_l();
4405 }
4406 }
4407
4408// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004409// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004410// }
4411
4412 if (framesReq > framesAvail) {
4413 framesReq = framesAvail;
4414 }
4415
4416 uint32_t u = cblk->user;
4417 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4418
4419 if (u + framesReq > bufferEnd) {
4420 framesReq = bufferEnd - u;
4421 }
4422
4423 buffer->frameCount = framesReq;
4424 buffer->raw = (void *)cblk->buffer(u);
4425 return NO_ERROR;
4426}
4427
4428
4429void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4430{
4431 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004432
4433 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004434 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004435 delete [] pBuffer->mBuffer;
4436 delete pBuffer;
4437 }
4438 mBufferQueue.clear();
4439}
4440
4441// ----------------------------------------------------------------------------
4442
4443AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4444 : RefBase(),
4445 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08004446 // 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 -07004447 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08004448 mPid(pid),
4449 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004450{
4451 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4452}
4453
4454// Client destructor must be called with AudioFlinger::mLock held
4455AudioFlinger::Client::~Client()
4456{
4457 mAudioFlinger->removeClient_l(mPid);
4458}
4459
Glenn Kasten435dbe62012-01-30 10:15:48 -08004460sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004461{
4462 return mMemoryDealer;
4463}
4464
John Grossman4ff14ba2012-02-08 16:37:41 -08004465// Reserve one of the limited slots for a timed audio track associated
4466// with this client
4467bool AudioFlinger::Client::reserveTimedTrack()
4468{
4469 const int kMaxTimedTracksPerClient = 4;
4470
4471 Mutex::Autolock _l(mTimedTrackLock);
4472
4473 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4474 ALOGW("can not create timed track - pid %d has exceeded the limit",
4475 mPid);
4476 return false;
4477 }
4478
4479 mTimedTrackCount++;
4480 return true;
4481}
4482
4483// Release a slot for a timed audio track
4484void AudioFlinger::Client::releaseTimedTrack()
4485{
4486 Mutex::Autolock _l(mTimedTrackLock);
4487 mTimedTrackCount--;
4488}
4489
Mathias Agopian65ab4712010-07-14 17:59:35 -07004490// ----------------------------------------------------------------------------
4491
4492AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4493 const sp<IAudioFlingerClient>& client,
4494 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004495 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004496{
4497}
4498
4499AudioFlinger::NotificationClient::~NotificationClient()
4500{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004501}
4502
4503void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4504{
4505 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08004506 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004507}
4508
4509// ----------------------------------------------------------------------------
4510
4511AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4512 : BnAudioTrack(),
4513 mTrack(track)
4514{
4515}
4516
4517AudioFlinger::TrackHandle::~TrackHandle() {
4518 // just stop the track on deletion, associated resources
4519 // will be freed from the main thread once all pending buffers have
4520 // been played. Unless it's not in the active track list, in which
4521 // case we free everything now...
4522 mTrack->destroy();
4523}
4524
Glenn Kasten90716c52012-01-26 13:40:12 -08004525sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4526 return mTrack->getCblk();
4527}
4528
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004529status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4530 return mTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004531}
4532
4533void AudioFlinger::TrackHandle::stop() {
4534 mTrack->stop();
4535}
4536
4537void AudioFlinger::TrackHandle::flush() {
4538 mTrack->flush();
4539}
4540
4541void AudioFlinger::TrackHandle::mute(bool e) {
4542 mTrack->mute(e);
4543}
4544
4545void AudioFlinger::TrackHandle::pause() {
4546 mTrack->pause();
4547}
4548
Mathias Agopian65ab4712010-07-14 17:59:35 -07004549status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4550{
4551 return mTrack->attachAuxEffect(EffectId);
4552}
4553
John Grossman4ff14ba2012-02-08 16:37:41 -08004554status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4555 sp<IMemory>* buffer) {
4556 if (!mTrack->isTimedTrack())
4557 return INVALID_OPERATION;
4558
4559 PlaybackThread::TimedTrack* tt =
4560 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4561 return tt->allocateTimedBuffer(size, buffer);
4562}
4563
4564status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4565 int64_t pts) {
4566 if (!mTrack->isTimedTrack())
4567 return INVALID_OPERATION;
4568
4569 PlaybackThread::TimedTrack* tt =
4570 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4571 return tt->queueTimedBuffer(buffer, pts);
4572}
4573
4574status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4575 const LinearTransform& xform, int target) {
4576
4577 if (!mTrack->isTimedTrack())
4578 return INVALID_OPERATION;
4579
4580 PlaybackThread::TimedTrack* tt =
4581 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4582 return tt->setMediaTimeTransform(
4583 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4584}
4585
Mathias Agopian65ab4712010-07-14 17:59:35 -07004586status_t AudioFlinger::TrackHandle::onTransact(
4587 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4588{
4589 return BnAudioTrack::onTransact(code, data, reply, flags);
4590}
4591
4592// ----------------------------------------------------------------------------
4593
4594sp<IAudioRecord> AudioFlinger::openRecord(
4595 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004596 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004597 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004598 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004599 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004600 int frameCount,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004601 // FIXME dead, remove from IAudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -07004602 uint32_t flags,
4603 int *sessionId,
4604 status_t *status)
4605{
4606 sp<RecordThread::RecordTrack> recordTrack;
4607 sp<RecordHandle> recordHandle;
4608 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004609 status_t lStatus;
4610 RecordThread *thread;
4611 size_t inFrameCount;
4612 int lSessionId;
4613
4614 // check calling permissions
4615 if (!recordingAllowed()) {
4616 lStatus = PERMISSION_DENIED;
4617 goto Exit;
4618 }
4619
4620 // add client to list
4621 { // scope for mLock
4622 Mutex::Autolock _l(mLock);
4623 thread = checkRecordThread_l(input);
4624 if (thread == NULL) {
4625 lStatus = BAD_VALUE;
4626 goto Exit;
4627 }
4628
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004629 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004630
4631 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004632 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004633 lSessionId = *sessionId;
4634 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004635 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004636 if (sessionId != NULL) {
4637 *sessionId = lSessionId;
4638 }
4639 }
4640 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004641 recordTrack = thread->createRecordTrack_l(client,
4642 sampleRate,
4643 format,
4644 channelMask,
4645 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004646 lSessionId,
4647 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004648 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004649 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004650 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4651 // destructor is called by the TrackBase destructor with mLock held
4652 client.clear();
4653 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004654 goto Exit;
4655 }
4656
4657 // return to handle to client
4658 recordHandle = new RecordHandle(recordTrack);
4659 lStatus = NO_ERROR;
4660
4661Exit:
4662 if (status) {
4663 *status = lStatus;
4664 }
4665 return recordHandle;
4666}
4667
4668// ----------------------------------------------------------------------------
4669
4670AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4671 : BnAudioRecord(),
4672 mRecordTrack(recordTrack)
4673{
4674}
4675
4676AudioFlinger::RecordHandle::~RecordHandle() {
4677 stop();
4678}
4679
Glenn Kasten90716c52012-01-26 13:40:12 -08004680sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4681 return mRecordTrack->getCblk();
4682}
4683
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004684status_t AudioFlinger::RecordHandle::start(pid_t tid) {
Steve Block3856b092011-10-20 11:56:00 +01004685 ALOGV("RecordHandle::start()");
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004686 return mRecordTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004687}
4688
4689void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004690 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004691 mRecordTrack->stop();
4692}
4693
Mathias Agopian65ab4712010-07-14 17:59:35 -07004694status_t AudioFlinger::RecordHandle::onTransact(
4695 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4696{
4697 return BnAudioRecord::onTransact(code, data, reply, flags);
4698}
4699
4700// ----------------------------------------------------------------------------
4701
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004702AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4703 AudioStreamIn *input,
4704 uint32_t sampleRate,
4705 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004706 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004707 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004708 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004709 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4710 // mRsmpInIndex and mInputBytes set by readInputParameters()
4711 mReqChannelCount(popcount(channels)),
4712 mReqSampleRate(sampleRate)
4713 // mBytesRead is only meaningful while active, and so is cleared in start()
4714 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004715{
Glenn Kasten480b4682012-02-28 12:30:08 -08004716 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07004717
Mathias Agopian65ab4712010-07-14 17:59:35 -07004718 readInputParameters();
4719}
4720
4721
4722AudioFlinger::RecordThread::~RecordThread()
4723{
4724 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004725 delete mResampler;
4726 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004727}
4728
4729void AudioFlinger::RecordThread::onFirstRef()
4730{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004731 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004732}
4733
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004734status_t AudioFlinger::RecordThread::readyToRun()
4735{
4736 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004737 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004738 return status;
4739}
4740
Mathias Agopian65ab4712010-07-14 17:59:35 -07004741bool AudioFlinger::RecordThread::threadLoop()
4742{
4743 AudioBufferProvider::Buffer buffer;
4744 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004745 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004746
Eric Laurent44d98482010-09-30 16:12:31 -07004747 nsecs_t lastWarning = 0;
4748
Eric Laurentfeb0db62011-07-22 09:04:31 -07004749 acquireWakeLock();
4750
Mathias Agopian65ab4712010-07-14 17:59:35 -07004751 // start recording
4752 while (!exitPending()) {
4753
4754 processConfigEvents();
4755
4756 { // scope for mLock
4757 Mutex::Autolock _l(mLock);
4758 checkForNewParameters_l();
4759 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4760 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004761 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004762 mStandby = true;
4763 }
4764
4765 if (exitPending()) break;
4766
Eric Laurentfeb0db62011-07-22 09:04:31 -07004767 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004768 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004769 // go to sleep
4770 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004771 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004772 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004773 continue;
4774 }
4775 if (mActiveTrack != 0) {
4776 if (mActiveTrack->mState == TrackBase::PAUSING) {
4777 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004778 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004779 mStandby = true;
4780 }
4781 mActiveTrack.clear();
4782 mStartStopCond.broadcast();
4783 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4784 if (mReqChannelCount != mActiveTrack->channelCount()) {
4785 mActiveTrack.clear();
4786 mStartStopCond.broadcast();
4787 } else if (mBytesRead != 0) {
4788 // record start succeeds only if first read from audio input
4789 // succeeds
4790 if (mBytesRead > 0) {
4791 mActiveTrack->mState = TrackBase::ACTIVE;
4792 } else {
4793 mActiveTrack.clear();
4794 }
4795 mStartStopCond.broadcast();
4796 }
4797 mStandby = false;
4798 }
4799 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004800 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004801 }
4802
4803 if (mActiveTrack != 0) {
4804 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4805 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004806 unlockEffectChains(effectChains);
4807 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004808 continue;
4809 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004810 for (size_t i = 0; i < effectChains.size(); i ++) {
4811 effectChains[i]->process_l();
4812 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004813
Mathias Agopian65ab4712010-07-14 17:59:35 -07004814 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004815 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004816 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004817 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004818 // no resampling
4819 while (framesOut) {
4820 size_t framesIn = mFrameCount - mRsmpInIndex;
4821 if (framesIn) {
4822 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4823 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4824 if (framesIn > framesOut)
4825 framesIn = framesOut;
4826 mRsmpInIndex += framesIn;
4827 framesOut -= framesIn;
4828 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004829 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004830 memcpy(dst, src, framesIn * mFrameSize);
4831 } else {
4832 int16_t *src16 = (int16_t *)src;
4833 int16_t *dst16 = (int16_t *)dst;
4834 if (mChannelCount == 1) {
4835 while (framesIn--) {
4836 *dst16++ = *src16;
4837 *dst16++ = *src16++;
4838 }
4839 } else {
4840 while (framesIn--) {
4841 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4842 src16 += 2;
4843 }
4844 }
4845 }
4846 }
4847 if (framesOut && mFrameCount == mRsmpInIndex) {
4848 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004849 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004850 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004851 framesOut = 0;
4852 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004853 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004854 mRsmpInIndex = 0;
4855 }
4856 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004857 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004858 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4859 // Force input into standby so that it tries to
4860 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004861 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004862 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004863 }
4864 mRsmpInIndex = mFrameCount;
4865 framesOut = 0;
4866 buffer.frameCount = 0;
4867 }
4868 }
4869 }
4870 } else {
4871 // resampling
4872
4873 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4874 // alter output frame count as if we were expecting stereo samples
4875 if (mChannelCount == 1 && mReqChannelCount == 1) {
4876 framesOut >>= 1;
4877 }
4878 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4879 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4880 // are 32 bit aligned which should be always true.
4881 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004882 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004883 // the resampler always outputs stereo samples: do post stereo to mono conversion
4884 int16_t *src = (int16_t *)mRsmpOutBuffer;
4885 int16_t *dst = buffer.i16;
4886 while (framesOut--) {
4887 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4888 src += 2;
4889 }
4890 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004891 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004892 }
4893
4894 }
4895 mActiveTrack->releaseBuffer(&buffer);
4896 mActiveTrack->overflow();
4897 }
4898 // client isn't retrieving buffers fast enough
4899 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004900 if (!mActiveTrack->setOverflow()) {
4901 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004902 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004903 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004904 lastWarning = now;
4905 }
4906 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004907 // Release the processor for a while before asking for a new buffer.
4908 // This will give the application more chance to read from the buffer and
4909 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004910 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004911 }
4912 }
Eric Laurentec437d82011-07-26 20:54:46 -07004913 // enable changes in effect chain
4914 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004915 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004916 }
4917
4918 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004919 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004920 }
4921 mActiveTrack.clear();
4922
4923 mStartStopCond.broadcast();
4924
Eric Laurentfeb0db62011-07-22 09:04:31 -07004925 releaseWakeLock();
4926
Steve Block3856b092011-10-20 11:56:00 +01004927 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004928 return false;
4929}
4930
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004931
4932sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4933 const sp<AudioFlinger::Client>& client,
4934 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004935 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004936 int channelMask,
4937 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004938 int sessionId,
4939 status_t *status)
4940{
4941 sp<RecordTrack> track;
4942 status_t lStatus;
4943
4944 lStatus = initCheck();
4945 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004946 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004947 goto Exit;
4948 }
4949
4950 { // scope for mLock
4951 Mutex::Autolock _l(mLock);
4952
4953 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004954 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004955
Glenn Kasten7378ca52012-01-20 13:44:40 -08004956 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004957 lStatus = NO_MEMORY;
4958 goto Exit;
4959 }
4960
4961 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004962 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4963 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004964 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004965 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4966 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004967 }
4968 lStatus = NO_ERROR;
4969
4970Exit:
4971 if (status) {
4972 *status = lStatus;
4973 }
4974 return track;
4975}
4976
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004977status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004978{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004979 ALOGV("RecordThread::start tid=%d", tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004980 sp <ThreadBase> strongMe = this;
4981 status_t status = NO_ERROR;
4982 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004983 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004984 if (mActiveTrack != 0) {
4985 if (recordTrack != mActiveTrack.get()) {
4986 status = -EBUSY;
4987 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4988 mActiveTrack->mState = TrackBase::ACTIVE;
4989 }
4990 return status;
4991 }
4992
4993 recordTrack->mState = TrackBase::IDLE;
4994 mActiveTrack = recordTrack;
4995 mLock.unlock();
4996 status_t status = AudioSystem::startInput(mId);
4997 mLock.lock();
4998 if (status != NO_ERROR) {
4999 mActiveTrack.clear();
5000 return status;
5001 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005002 mRsmpInIndex = mFrameCount;
5003 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005004 if (mResampler != NULL) {
5005 mResampler->reset();
5006 }
5007 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005008 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005009 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005010 mWaitWorkCV.signal();
5011 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005012 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005013 mActiveTrack.clear();
5014 status = INVALID_OPERATION;
5015 goto startError;
5016 }
5017 mStartStopCond.wait(mLock);
5018 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005019 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005020 status = BAD_VALUE;
5021 goto startError;
5022 }
Steve Block3856b092011-10-20 11:56:00 +01005023 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005024 return status;
5025 }
5026startError:
5027 AudioSystem::stopInput(mId);
5028 return status;
5029}
5030
5031void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005032 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005033 sp <ThreadBase> strongMe = this;
5034 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005035 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005036 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5037 mActiveTrack->mState = TrackBase::PAUSING;
5038 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005039 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005040 return;
5041 }
5042 mStartStopCond.wait(mLock);
5043 // if we have been restarted, recordTrack == mActiveTrack.get() here
5044 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5045 mLock.unlock();
5046 AudioSystem::stopInput(mId);
5047 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005048 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005049 }
5050 }
5051 }
5052}
5053
5054status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5055{
5056 const size_t SIZE = 256;
5057 char buffer[SIZE];
5058 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005059
5060 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5061 result.append(buffer);
5062
5063 if (mActiveTrack != 0) {
5064 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005065 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005066 mActiveTrack->dump(buffer, SIZE);
5067 result.append(buffer);
5068
5069 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5070 result.append(buffer);
5071 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5072 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005073 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005074 result.append(buffer);
5075 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5076 result.append(buffer);
5077 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5078 result.append(buffer);
5079
5080
5081 } else {
5082 result.append("No record client\n");
5083 }
5084 write(fd, result.string(), result.size());
5085
5086 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005087 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005088
5089 return NO_ERROR;
5090}
5091
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005092// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005093status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005094{
5095 size_t framesReq = buffer->frameCount;
5096 size_t framesReady = mFrameCount - mRsmpInIndex;
5097 int channelCount;
5098
5099 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005100 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005101 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005102 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005103 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5104 // Force input into standby so that it tries to
5105 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005106 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005107 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005108 }
Glenn Kastene0feee32011-12-13 11:53:26 -08005109 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005110 buffer->frameCount = 0;
5111 return NOT_ENOUGH_DATA;
5112 }
5113 mRsmpInIndex = 0;
5114 framesReady = mFrameCount;
5115 }
5116
5117 if (framesReq > framesReady) {
5118 framesReq = framesReady;
5119 }
5120
5121 if (mChannelCount == 1 && mReqChannelCount == 2) {
5122 channelCount = 1;
5123 } else {
5124 channelCount = 2;
5125 }
5126 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5127 buffer->frameCount = framesReq;
5128 return NO_ERROR;
5129}
5130
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005131// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07005132void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5133{
5134 mRsmpInIndex += buffer->frameCount;
5135 buffer->frameCount = 0;
5136}
5137
5138bool AudioFlinger::RecordThread::checkForNewParameters_l()
5139{
5140 bool reconfig = false;
5141
5142 while (!mNewParameters.isEmpty()) {
5143 status_t status = NO_ERROR;
5144 String8 keyValuePair = mNewParameters[0];
5145 AudioParameter param = AudioParameter(keyValuePair);
5146 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08005147 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005148 int reqSamplingRate = mReqSampleRate;
5149 int reqChannelCount = mReqChannelCount;
5150
5151 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5152 reqSamplingRate = value;
5153 reconfig = true;
5154 }
5155 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08005156 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005157 reconfig = true;
5158 }
5159 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005160 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005161 reconfig = true;
5162 }
5163 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5164 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08005165 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005166 // if frame count is changed after track creation
5167 if (mActiveTrack != 0) {
5168 status = INVALID_OPERATION;
5169 } else {
5170 reconfig = true;
5171 }
5172 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005173 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5174 // forward device change to effects that have requested to be
5175 // aware of attached audio device.
5176 for (size_t i = 0; i < mEffectChains.size(); i++) {
5177 mEffectChains[i]->setDevice_l(value);
5178 }
5179 // store input device and output device but do not forward output device to audio HAL.
5180 // Note that status is ignored by the caller for output device
5181 // (see AudioFlinger::setParameters()
5182 if (value & AUDIO_DEVICE_OUT_ALL) {
5183 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5184 status = BAD_VALUE;
5185 } else {
5186 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07005187 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5188 if (mTrack != NULL) {
5189 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005190 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005191 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5192 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5193 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005194 }
5195 mDevice |= (uint32_t)value;
5196 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005197 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005198 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005199 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005200 mInput->stream->common.standby(&mInput->stream->common);
5201 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005202 }
5203 if (reconfig) {
5204 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005205 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005206 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005207 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08005208 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
5209 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005210 status = NO_ERROR;
5211 }
5212 if (status == NO_ERROR) {
5213 readInputParameters();
5214 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5215 }
5216 }
5217 }
5218
5219 mNewParameters.removeAt(0);
5220
5221 mParamStatus = status;
5222 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07005223 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5224 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08005225 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005226 }
5227 return reconfig;
5228}
5229
5230String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5231{
Dima Zavinfce7a472011-04-19 22:30:36 -07005232 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005233 String8 out_s8 = String8();
5234
5235 Mutex::Autolock _l(mLock);
5236 if (initCheck() != NO_ERROR) {
5237 return out_s8;
5238 }
Dima Zavinfce7a472011-04-19 22:30:36 -07005239
Dima Zavin799a70e2011-04-18 16:57:27 -07005240 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07005241 out_s8 = String8(s);
5242 free(s);
5243 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005244}
5245
5246void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5247 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08005248 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005249
5250 switch (event) {
5251 case AudioSystem::INPUT_OPENED:
5252 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005253 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005254 desc.samplingRate = mSampleRate;
5255 desc.format = mFormat;
5256 desc.frameCount = mFrameCount;
5257 desc.latency = 0;
5258 param2 = &desc;
5259 break;
5260
5261 case AudioSystem::INPUT_CLOSED:
5262 default:
5263 break;
5264 }
5265 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5266}
5267
5268void AudioFlinger::RecordThread::readInputParameters()
5269{
Glenn Kastene9dd0172012-01-27 18:08:45 -08005270 delete mRsmpInBuffer;
5271 // mRsmpInBuffer is always assigned a new[] below
5272 delete mRsmpOutBuffer;
5273 mRsmpOutBuffer = NULL;
5274 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08005275 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005276
Dima Zavin799a70e2011-04-18 16:57:27 -07005277 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005278 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5279 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07005280 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08005281 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07005282 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005283 mFrameCount = mInputBytes / mFrameSize;
5284 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5285
Glenn Kasten53d76db2012-03-08 12:32:47 -08005286 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005287 {
5288 int channelCount;
5289 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5290 // stereo to mono post process as the resampler always outputs stereo.
5291 if (mChannelCount == 1 && mReqChannelCount == 2) {
5292 channelCount = 1;
5293 } else {
5294 channelCount = 2;
5295 }
5296 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5297 mResampler->setSampleRate(mSampleRate);
5298 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5299 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5300
5301 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5302 if (mChannelCount == 1 && mReqChannelCount == 1) {
5303 mFrameCount >>= 1;
5304 }
5305
5306 }
5307 mRsmpInIndex = mFrameCount;
5308}
5309
5310unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5311{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005312 Mutex::Autolock _l(mLock);
5313 if (initCheck() != NO_ERROR) {
5314 return 0;
5315 }
5316
Dima Zavin799a70e2011-04-18 16:57:27 -07005317 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005318}
5319
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005320uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5321{
5322 Mutex::Autolock _l(mLock);
5323 uint32_t result = 0;
5324 if (getEffectChain_l(sessionId) != 0) {
5325 result = EFFECT_SESSION;
5326 }
5327
5328 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5329 result |= TRACK_SESSION;
5330 }
5331
5332 return result;
5333}
5334
Eric Laurent59bd0da2011-08-01 09:52:20 -07005335AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5336{
5337 Mutex::Autolock _l(mLock);
5338 return mTrack;
5339}
5340
Glenn Kastenaed850d2012-01-26 09:46:34 -08005341AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005342{
5343 Mutex::Autolock _l(mLock);
5344 return mInput;
5345}
5346
5347AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5348{
5349 Mutex::Autolock _l(mLock);
5350 AudioStreamIn *input = mInput;
5351 mInput = NULL;
5352 return input;
5353}
5354
5355// this method must always be called either with ThreadBase mLock held or inside the thread loop
5356audio_stream_t* AudioFlinger::RecordThread::stream()
5357{
5358 if (mInput == NULL) {
5359 return NULL;
5360 }
5361 return &mInput->stream->common;
5362}
5363
5364
Mathias Agopian65ab4712010-07-14 17:59:35 -07005365// ----------------------------------------------------------------------------
5366
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005367audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005368 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005369 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005370 uint32_t *pChannels,
5371 uint32_t *pLatencyMs,
Glenn Kasten18868c52012-03-07 09:15:37 -08005372 audio_policy_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005373{
5374 status_t status;
5375 PlaybackThread *thread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005376 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005377 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005378 uint32_t channels = pChannels ? *pChannels : 0;
5379 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07005380 audio_stream_out_t *outStream;
5381 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005382
Steve Block3856b092011-10-20 11:56:00 +01005383 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07005384 pDevices ? *pDevices : 0,
5385 samplingRate,
5386 format,
5387 channels,
5388 flags);
5389
5390 if (pDevices == NULL || *pDevices == 0) {
5391 return 0;
5392 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005393
Mathias Agopian65ab4712010-07-14 17:59:35 -07005394 Mutex::Autolock _l(mLock);
5395
Dima Zavin799a70e2011-04-18 16:57:27 -07005396 outHwDev = findSuitableHwDev_l(*pDevices);
5397 if (outHwDev == NULL)
5398 return 0;
5399
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005400 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Glenn Kasten58f30212012-01-12 12:27:51 -08005401 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005402 &channels, &samplingRate, &outStream);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005403 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01005404 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005405 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005406 samplingRate,
5407 format,
5408 channels,
5409 status);
5410
Dima Zavin799a70e2011-04-18 16:57:27 -07005411 if (outStream != NULL) {
5412 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005413 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07005414
Dima Zavinfce7a472011-04-19 22:30:36 -07005415 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5416 (format != AUDIO_FORMAT_PCM_16_BIT) ||
5417 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005418 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005419 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005420 } else {
5421 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005422 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005423 }
5424 mPlaybackThreads.add(id, thread);
5425
Glenn Kastena0d68332012-01-27 16:47:15 -08005426 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5427 if (pFormat != NULL) *pFormat = format;
5428 if (pChannels != NULL) *pChannels = channels;
5429 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005430
5431 // notify client processes of the new output creation
5432 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5433 return id;
5434 }
5435
5436 return 0;
5437}
5438
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005439audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
5440 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005441{
5442 Mutex::Autolock _l(mLock);
5443 MixerThread *thread1 = checkMixerThread_l(output1);
5444 MixerThread *thread2 = checkMixerThread_l(output2);
5445
5446 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005447 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005448 return 0;
5449 }
5450
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005451 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005452 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5453 thread->addOutputTrack(thread2);
5454 mPlaybackThreads.add(id, thread);
5455 // notify client processes of the new output creation
5456 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5457 return id;
5458}
5459
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005460status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005461{
5462 // keep strong reference on the playback thread so that
5463 // it is not destroyed while exit() is executed
5464 sp <PlaybackThread> thread;
5465 {
5466 Mutex::Autolock _l(mLock);
5467 thread = checkPlaybackThread_l(output);
5468 if (thread == NULL) {
5469 return BAD_VALUE;
5470 }
5471
Steve Block3856b092011-10-20 11:56:00 +01005472 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005473
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005474 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005475 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005476 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005477 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5478 dupThread->removeOutputTrack((MixerThread *)thread.get());
5479 }
5480 }
5481 }
Glenn Kastena1117922012-01-26 10:53:32 -08005482 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005483 mPlaybackThreads.removeItem(output);
5484 }
5485 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005486 // The thread entity (active unit of execution) is no longer running here,
5487 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005488
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005489 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005490 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005491 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005492 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005493 out->hwDev->close_output_stream(out->hwDev, out->stream);
5494 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005495 }
5496 return NO_ERROR;
5497}
5498
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005499status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005500{
5501 Mutex::Autolock _l(mLock);
5502 PlaybackThread *thread = checkPlaybackThread_l(output);
5503
5504 if (thread == NULL) {
5505 return BAD_VALUE;
5506 }
5507
Steve Block3856b092011-10-20 11:56:00 +01005508 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005509 thread->suspend();
5510
5511 return NO_ERROR;
5512}
5513
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005514status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005515{
5516 Mutex::Autolock _l(mLock);
5517 PlaybackThread *thread = checkPlaybackThread_l(output);
5518
5519 if (thread == NULL) {
5520 return BAD_VALUE;
5521 }
5522
Steve Block3856b092011-10-20 11:56:00 +01005523 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005524
5525 thread->restore();
5526
5527 return NO_ERROR;
5528}
5529
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005530audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005531 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005532 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005533 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005534 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005535{
5536 status_t status;
5537 RecordThread *thread = NULL;
5538 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005539 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005540 uint32_t channels = pChannels ? *pChannels : 0;
5541 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005542 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005543 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005544 audio_stream_in_t *inStream;
5545 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005546
5547 if (pDevices == NULL || *pDevices == 0) {
5548 return 0;
5549 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005550
Mathias Agopian65ab4712010-07-14 17:59:35 -07005551 Mutex::Autolock _l(mLock);
5552
Dima Zavin799a70e2011-04-18 16:57:27 -07005553 inHwDev = findSuitableHwDev_l(*pDevices);
5554 if (inHwDev == NULL)
5555 return 0;
5556
Glenn Kasten58f30212012-01-12 12:27:51 -08005557 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005558 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005559 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005560 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005561 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005562 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005563 samplingRate,
5564 format,
5565 channels,
5566 acoustics,
5567 status);
5568
5569 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5570 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5571 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005572 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005573 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005574 (samplingRate <= 2 * reqSamplingRate) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08005575 (popcount(channels) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01005576 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005577 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005578 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005579 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005580 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005581 }
5582
Dima Zavin799a70e2011-04-18 16:57:27 -07005583 if (inStream != NULL) {
5584 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5585
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005586 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005587 // Start record thread
5588 // RecorThread require both input and output device indication to forward to audio
5589 // pre processing modules
5590 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5591 thread = new RecordThread(this,
5592 input,
5593 reqSamplingRate,
5594 reqChannels,
5595 id,
5596 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005597 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005598 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005599 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5600 if (pFormat != NULL) *pFormat = format;
5601 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005602
Dima Zavin799a70e2011-04-18 16:57:27 -07005603 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005604
5605 // notify client processes of the new input creation
5606 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5607 return id;
5608 }
5609
5610 return 0;
5611}
5612
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005613status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005614{
5615 // keep strong reference on the record thread so that
5616 // it is not destroyed while exit() is executed
5617 sp <RecordThread> thread;
5618 {
5619 Mutex::Autolock _l(mLock);
5620 thread = checkRecordThread_l(input);
5621 if (thread == NULL) {
5622 return BAD_VALUE;
5623 }
5624
Steve Block3856b092011-10-20 11:56:00 +01005625 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08005626 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005627 mRecordThreads.removeItem(input);
5628 }
5629 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005630 // The thread entity (active unit of execution) is no longer running here,
5631 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005632
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005633 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005634 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005635 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005636 in->hwDev->close_input_stream(in->hwDev, in->stream);
5637 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005638
5639 return NO_ERROR;
5640}
5641
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005642status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005643{
5644 Mutex::Autolock _l(mLock);
5645 MixerThread *dstThread = checkMixerThread_l(output);
5646 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005647 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005648 return BAD_VALUE;
5649 }
5650
Steve Block3856b092011-10-20 11:56:00 +01005651 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005652 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5653
Eric Laurent9f6530f2011-08-30 10:18:54 -07005654 dstThread->setStreamValid(stream, true);
5655
Mathias Agopian65ab4712010-07-14 17:59:35 -07005656 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5657 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08005658 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005659 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005660 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005661 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005662 }
Eric Laurentde070132010-07-13 04:45:46 -07005663 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005664
5665 return NO_ERROR;
5666}
5667
5668
5669int AudioFlinger::newAudioSessionId()
5670{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005671 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005672}
5673
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005674void AudioFlinger::acquireAudioSessionId(int audioSession)
5675{
5676 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005677 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005678 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005679 size_t num = mAudioSessionRefs.size();
5680 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005681 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005682 if (ref->mSessionid == audioSession && ref->mPid == caller) {
5683 ref->mCnt++;
5684 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005685 return;
5686 }
5687 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005688 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5689 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005690}
5691
5692void AudioFlinger::releaseAudioSessionId(int audioSession)
5693{
5694 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005695 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005696 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005697 size_t num = mAudioSessionRefs.size();
5698 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005699 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005700 if (ref->mSessionid == audioSession && ref->mPid == caller) {
5701 ref->mCnt--;
5702 ALOGV(" decremented refcount to %d", ref->mCnt);
5703 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005704 mAudioSessionRefs.removeAt(i);
5705 delete ref;
5706 purgeStaleEffects_l();
5707 }
5708 return;
5709 }
5710 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005711 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005712}
5713
5714void AudioFlinger::purgeStaleEffects_l() {
5715
Steve Block3856b092011-10-20 11:56:00 +01005716 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005717
5718 Vector< sp<EffectChain> > chains;
5719
5720 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5721 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5722 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5723 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005724 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5725 chains.push(ec);
5726 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005727 }
5728 }
5729 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5730 sp<RecordThread> t = mRecordThreads.valueAt(i);
5731 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5732 sp<EffectChain> ec = t->mEffectChains[j];
5733 chains.push(ec);
5734 }
5735 }
5736
5737 for (size_t i = 0; i < chains.size(); i++) {
5738 sp<EffectChain> ec = chains[i];
5739 int sessionid = ec->sessionId();
5740 sp<ThreadBase> t = ec->mThread.promote();
5741 if (t == 0) {
5742 continue;
5743 }
5744 size_t numsessionrefs = mAudioSessionRefs.size();
5745 bool found = false;
5746 for (size_t k = 0; k < numsessionrefs; k++) {
5747 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005748 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005749 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005750 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005751 found = true;
5752 break;
5753 }
5754 }
5755 if (!found) {
5756 // remove all effects from the chain
5757 while (ec->mEffects.size()) {
5758 sp<EffectModule> effect = ec->mEffects[0];
5759 effect->unPin();
5760 Mutex::Autolock _l (t->mLock);
5761 t->removeEffect_l(effect);
5762 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5763 sp<EffectHandle> handle = effect->mHandles[j].promote();
5764 if (handle != 0) {
5765 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005766 if (handle->mHasControl && handle->mEnabled) {
5767 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5768 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005769 }
5770 }
5771 AudioSystem::unregisterEffect(effect->id());
5772 }
5773 }
5774 }
5775 return;
5776}
5777
Mathias Agopian65ab4712010-07-14 17:59:35 -07005778// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005779AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005780{
Glenn Kastena1117922012-01-26 10:53:32 -08005781 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005782}
5783
5784// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005785AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005786{
5787 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08005788 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005789}
5790
5791// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005792AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005793{
Glenn Kastena1117922012-01-26 10:53:32 -08005794 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005795}
5796
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005797uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005798{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005799 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005800}
5801
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08005802AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005803{
5804 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5805 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005806 AudioStreamOut *output = thread->getOutput();
5807 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005808 return thread;
5809 }
5810 }
5811 return NULL;
5812}
5813
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08005814uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005815{
5816 PlaybackThread *thread = primaryPlaybackThread_l();
5817
5818 if (thread == NULL) {
5819 return 0;
5820 }
5821
5822 return thread->device();
5823}
5824
5825
Mathias Agopian65ab4712010-07-14 17:59:35 -07005826// ----------------------------------------------------------------------------
5827// Effect management
5828// ----------------------------------------------------------------------------
5829
5830
Glenn Kastenf587ba52012-01-26 16:25:10 -08005831status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005832{
5833 Mutex::Autolock _l(mLock);
5834 return EffectQueryNumberEffects(numEffects);
5835}
5836
Glenn Kastenf587ba52012-01-26 16:25:10 -08005837status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005838{
5839 Mutex::Autolock _l(mLock);
5840 return EffectQueryEffect(index, descriptor);
5841}
5842
Glenn Kasten5e92a782012-01-30 07:40:52 -08005843status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08005844 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005845{
5846 Mutex::Autolock _l(mLock);
5847 return EffectGetDescriptor(pUuid, descriptor);
5848}
5849
5850
Mathias Agopian65ab4712010-07-14 17:59:35 -07005851sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5852 effect_descriptor_t *pDesc,
5853 const sp<IEffectClient>& effectClient,
5854 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005855 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005856 int sessionId,
5857 status_t *status,
5858 int *id,
5859 int *enabled)
5860{
5861 status_t lStatus = NO_ERROR;
5862 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005863 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005864
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005865 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005866 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005867
5868 if (pDesc == NULL) {
5869 lStatus = BAD_VALUE;
5870 goto Exit;
5871 }
5872
Eric Laurent84e9a102010-09-23 16:10:16 -07005873 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005874 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005875 lStatus = PERMISSION_DENIED;
5876 goto Exit;
5877 }
5878
Dima Zavinfce7a472011-04-19 22:30:36 -07005879 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005880 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08005881 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005882 lStatus = PERMISSION_DENIED;
5883 goto Exit;
5884 }
5885
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005886 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005887 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005888 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005889 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005890 lStatus = BAD_VALUE;
5891 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005892 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005893 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005894 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005895 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005896 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005897 }
5898 }
5899
Mathias Agopian65ab4712010-07-14 17:59:35 -07005900 {
5901 Mutex::Autolock _l(mLock);
5902
Mathias Agopian65ab4712010-07-14 17:59:35 -07005903
5904 if (!EffectIsNullUuid(&pDesc->uuid)) {
5905 // if uuid is specified, request effect descriptor
5906 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5907 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005908 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005909 goto Exit;
5910 }
5911 } else {
5912 // if uuid is not specified, look for an available implementation
5913 // of the required type in effect factory
5914 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005915 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005916 lStatus = BAD_VALUE;
5917 goto Exit;
5918 }
5919 uint32_t numEffects = 0;
5920 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005921 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005922 bool found = false;
5923
5924 lStatus = EffectQueryNumberEffects(&numEffects);
5925 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005926 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005927 goto Exit;
5928 }
5929 for (uint32_t i = 0; i < numEffects; i++) {
5930 lStatus = EffectQueryEffect(i, &desc);
5931 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005932 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005933 continue;
5934 }
5935 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5936 // If matching type found save effect descriptor. If the session is
5937 // 0 and the effect is not auxiliary, continue enumeration in case
5938 // an auxiliary version of this effect type is available
5939 found = true;
5940 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005941 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005942 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5943 break;
5944 }
5945 }
5946 }
5947 if (!found) {
5948 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00005949 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005950 goto Exit;
5951 }
5952 // For same effect type, chose auxiliary version over insert version if
5953 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005954 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005955 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5956 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5957 }
5958 }
5959
5960 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005961 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005962 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5963 lStatus = INVALID_OPERATION;
5964 goto Exit;
5965 }
5966
Eric Laurent59255e42011-07-27 19:49:51 -07005967 // check recording permission for visualizer
5968 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5969 !recordingAllowed()) {
5970 lStatus = PERMISSION_DENIED;
5971 goto Exit;
5972 }
5973
Mathias Agopian65ab4712010-07-14 17:59:35 -07005974 // return effect descriptor
5975 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5976
5977 // If output is not specified try to find a matching audio session ID in one of the
5978 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005979 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5980 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005981 // Note: io is never 0 when creating an effect on an input
5982 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005983 // look for the thread where the specified audio session is present
5984 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5985 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005986 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005987 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005988 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005989 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005990 if (io == 0) {
5991 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5992 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5993 io = mRecordThreads.keyAt(i);
5994 break;
5995 }
5996 }
5997 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005998 // If no output thread contains the requested session ID, default to
5999 // first output. The effect chain will be moved to the correct output
6000 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006001 if (io == 0 && mPlaybackThreads.size()) {
6002 io = mPlaybackThreads.keyAt(0);
6003 }
Steve Block3856b092011-10-20 11:56:00 +01006004 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006005 }
6006 ThreadBase *thread = checkRecordThread_l(io);
6007 if (thread == NULL) {
6008 thread = checkPlaybackThread_l(io);
6009 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00006010 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006011 lStatus = BAD_VALUE;
6012 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07006013 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006014 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006015
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006016 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006017
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006018 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07006019 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6020 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006021 if (handle != 0 && id != NULL) {
6022 *id = handle->id();
6023 }
6024 }
6025
6026Exit:
6027 if(status) {
6028 *status = lStatus;
6029 }
6030 return handle;
6031}
6032
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006033status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
6034 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07006035{
Steve Block3856b092011-10-20 11:56:00 +01006036 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07006037 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006038 Mutex::Autolock _l(mLock);
6039 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006040 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006041 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006042 }
Eric Laurentde070132010-07-13 04:45:46 -07006043 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6044 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006045 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006046 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006047 }
Eric Laurentde070132010-07-13 04:45:46 -07006048 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6049 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006050 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006051 return BAD_VALUE;
6052 }
6053
6054 Mutex::Autolock _dl(dstThread->mLock);
6055 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07006056 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07006057
Mathias Agopian65ab4712010-07-14 17:59:35 -07006058 return NO_ERROR;
6059}
6060
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006061// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07006062status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07006063 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07006064 AudioFlinger::PlaybackThread *dstThread,
6065 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07006066{
Steve Block3856b092011-10-20 11:56:00 +01006067 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006068 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07006069
Eric Laurent59255e42011-07-27 19:49:51 -07006070 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006071 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006072 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006073 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07006074 return INVALID_OPERATION;
6075 }
6076
Eric Laurent39e94f82010-07-28 01:32:47 -07006077 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07006078 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07006079 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07006080 // removed.
6081 srcThread->removeEffectChain_l(chain);
6082
6083 // transfer all effects one by one so that new effect chain is created on new thread with
6084 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006085 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07006086 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006087 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07006088 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6089 while (effect != 0) {
6090 srcThread->removeEffect_l(effect);
6091 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07006092 // removeEffect_l() has stopped the effect if it was active so it must be restarted
6093 if (effect->state() == EffectModule::ACTIVE ||
6094 effect->state() == EffectModule::STOPPING) {
6095 effect->start();
6096 }
Eric Laurent39e94f82010-07-28 01:32:47 -07006097 // if the move request is not received from audio policy manager, the effect must be
6098 // re-registered with the new strategy and output
6099 if (dstChain == 0) {
6100 dstChain = effect->chain().promote();
6101 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006102 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07006103 srcThread->addEffect_l(effect);
6104 return NO_INIT;
6105 }
6106 strategy = dstChain->strategy();
6107 }
6108 if (reRegister) {
6109 AudioSystem::unregisterEffect(effect->id());
6110 AudioSystem::registerEffect(&effect->desc(),
6111 dstOutput,
6112 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07006113 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07006114 effect->id());
6115 }
Eric Laurentde070132010-07-13 04:45:46 -07006116 effect = chain->getEffectFromId_l(0);
6117 }
6118
6119 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006120}
6121
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006122
Mathias Agopian65ab4712010-07-14 17:59:35 -07006123// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006124sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07006125 const sp<AudioFlinger::Client>& client,
6126 const sp<IEffectClient>& effectClient,
6127 int32_t priority,
6128 int sessionId,
6129 effect_descriptor_t *desc,
6130 int *enabled,
6131 status_t *status
6132 )
6133{
6134 sp<EffectModule> effect;
6135 sp<EffectHandle> handle;
6136 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006137 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07006138 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006139 bool effectCreated = false;
6140 bool effectRegistered = false;
6141
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006142 lStatus = initCheck();
6143 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006144 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006145 goto Exit;
6146 }
6147
6148 // Do not allow effects with session ID 0 on direct output or duplicating threads
6149 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07006150 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006151 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07006152 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006153 lStatus = BAD_VALUE;
6154 goto Exit;
6155 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006156 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08006157 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006158 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006159 desc->name, desc->flags, mType);
6160 lStatus = BAD_VALUE;
6161 goto Exit;
6162 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006163
Steve Block3856b092011-10-20 11:56:00 +01006164 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006165
6166 { // scope for mLock
6167 Mutex::Autolock _l(mLock);
6168
6169 // check for existing effect chain with the requested audio session
6170 chain = getEffectChain_l(sessionId);
6171 if (chain == 0) {
6172 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006173 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006174 chain = new EffectChain(this, sessionId);
6175 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07006176 chain->setStrategy(getStrategyForSession_l(sessionId));
6177 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006178 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07006179 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006180 }
6181
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08006182 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006183
6184 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006185 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006186 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07006187 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006188 if (lStatus != NO_ERROR) {
6189 goto Exit;
6190 }
6191 effectRegistered = true;
6192 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07006193 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006194 lStatus = effect->status();
6195 if (lStatus != NO_ERROR) {
6196 goto Exit;
6197 }
Eric Laurentcab11242010-07-15 12:50:15 -07006198 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006199 if (lStatus != NO_ERROR) {
6200 goto Exit;
6201 }
6202 effectCreated = true;
6203
6204 effect->setDevice(mDevice);
6205 effect->setMode(mAudioFlinger->getMode());
6206 }
6207 // create effect handle and connect it to effect module
6208 handle = new EffectHandle(effect, client, effectClient, priority);
6209 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08006210 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006211 *enabled = (int)effect->isEnabled();
6212 }
6213 }
6214
6215Exit:
6216 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07006217 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006218 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07006219 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006220 }
6221 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07006222 AudioSystem::unregisterEffect(effect->id());
6223 }
6224 if (chainCreated) {
6225 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006226 }
6227 handle.clear();
6228 }
6229
6230 if(status) {
6231 *status = lStatus;
6232 }
6233 return handle;
6234}
6235
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006236sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6237{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006238 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08006239 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006240}
6241
Eric Laurentde070132010-07-13 04:45:46 -07006242// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6243// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006244status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07006245{
6246 // check for existing effect chain with the requested audio session
6247 int sessionId = effect->sessionId();
6248 sp<EffectChain> chain = getEffectChain_l(sessionId);
6249 bool chainCreated = false;
6250
6251 if (chain == 0) {
6252 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006253 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006254 chain = new EffectChain(this, sessionId);
6255 addEffectChain_l(chain);
6256 chain->setStrategy(getStrategyForSession_l(sessionId));
6257 chainCreated = true;
6258 }
Steve Block3856b092011-10-20 11:56:00 +01006259 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006260
6261 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006262 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07006263 this, effect->desc().name, chain.get());
6264 return BAD_VALUE;
6265 }
6266
6267 status_t status = chain->addEffect_l(effect);
6268 if (status != NO_ERROR) {
6269 if (chainCreated) {
6270 removeEffectChain_l(chain);
6271 }
6272 return status;
6273 }
6274
6275 effect->setDevice(mDevice);
6276 effect->setMode(mAudioFlinger->getMode());
6277 return NO_ERROR;
6278}
6279
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006280void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07006281
Steve Block3856b092011-10-20 11:56:00 +01006282 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006283 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07006284 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6285 detachAuxEffect_l(effect->id());
6286 }
6287
6288 sp<EffectChain> chain = effect->chain().promote();
6289 if (chain != 0) {
6290 // remove effect chain if removing last effect
6291 if (chain->removeEffect_l(effect) == 0) {
6292 removeEffectChain_l(chain);
6293 }
6294 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00006295 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006296 }
6297}
6298
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006299void AudioFlinger::ThreadBase::lockEffectChains_l(
6300 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
6301{
6302 effectChains = mEffectChains;
6303 for (size_t i = 0; i < mEffectChains.size(); i++) {
6304 mEffectChains[i]->lock();
6305 }
6306}
6307
6308void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006309 const Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006310{
6311 for (size_t i = 0; i < effectChains.size(); i++) {
6312 effectChains[i]->unlock();
6313 }
6314}
6315
6316sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6317{
6318 Mutex::Autolock _l(mLock);
6319 return getEffectChain_l(sessionId);
6320}
6321
6322sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6323{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006324 size_t size = mEffectChains.size();
6325 for (size_t i = 0; i < size; i++) {
6326 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08006327 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006328 }
6329 }
Glenn Kasten090f0192012-01-30 13:00:02 -08006330 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006331}
6332
Glenn Kastenf78aee72012-01-04 11:00:47 -08006333void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006334{
6335 Mutex::Autolock _l(mLock);
6336 size_t size = mEffectChains.size();
6337 for (size_t i = 0; i < size; i++) {
6338 mEffectChains[i]->setMode_l(mode);
6339 }
6340}
6341
6342void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006343 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08006344 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07006345
Mathias Agopian65ab4712010-07-14 17:59:35 -07006346 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006347 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006348 // delete the effect module if removing last handle on it
6349 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006350 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006351 removeEffect_l(effect);
6352 AudioSystem::unregisterEffect(effect->id());
6353 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006354 }
6355}
6356
6357status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6358{
6359 int session = chain->sessionId();
6360 int16_t *buffer = mMixBuffer;
6361 bool ownsBuffer = false;
6362
Steve Block3856b092011-10-20 11:56:00 +01006363 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006364 if (session > 0) {
6365 // Only one effect chain can be present in direct output thread and it uses
6366 // the mix buffer as input
6367 if (mType != DIRECT) {
6368 size_t numSamples = mFrameCount * mChannelCount;
6369 buffer = new int16_t[numSamples];
6370 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01006371 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006372 ownsBuffer = true;
6373 }
6374
6375 // Attach all tracks with same session ID to this chain.
6376 for (size_t i = 0; i < mTracks.size(); ++i) {
6377 sp<Track> track = mTracks[i];
6378 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006379 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006380 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006381 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006382 }
6383 }
6384
6385 // indicate all active tracks in the chain
6386 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6387 sp<Track> track = mActiveTracks[i].promote();
6388 if (track == 0) continue;
6389 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006390 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07006391 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006392 }
6393 }
6394 }
6395
6396 chain->setInBuffer(buffer, ownsBuffer);
6397 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006398 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006399 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006400 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6401 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006402 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006403 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6404 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006405 // Effect chain for other sessions are inserted at beginning of effect
6406 // chains list to be processed before output mix effects. Relative order between other
6407 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006408 size_t size = mEffectChains.size();
6409 size_t i = 0;
6410 for (i = 0; i < size; i++) {
6411 if (mEffectChains[i]->sessionId() < session) break;
6412 }
6413 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006414 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006415
6416 return NO_ERROR;
6417}
6418
6419size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6420{
6421 int session = chain->sessionId();
6422
Steve Block3856b092011-10-20 11:56:00 +01006423 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006424
6425 for (size_t i = 0; i < mEffectChains.size(); i++) {
6426 if (chain == mEffectChains[i]) {
6427 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006428 // detach all active tracks from the chain
6429 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6430 sp<Track> track = mActiveTracks[i].promote();
6431 if (track == 0) continue;
6432 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006433 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006434 chain.get(), session);
6435 chain->decActiveTrackCnt();
6436 }
6437 }
6438
Mathias Agopian65ab4712010-07-14 17:59:35 -07006439 // detach all tracks with same session ID from this chain
6440 for (size_t i = 0; i < mTracks.size(); ++i) {
6441 sp<Track> track = mTracks[i];
6442 if (session == track->sessionId()) {
6443 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006444 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006445 }
6446 }
Eric Laurentde070132010-07-13 04:45:46 -07006447 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006448 }
6449 }
6450 return mEffectChains.size();
6451}
6452
Eric Laurentde070132010-07-13 04:45:46 -07006453status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6454 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006455{
6456 Mutex::Autolock _l(mLock);
6457 return attachAuxEffect_l(track, EffectId);
6458}
6459
Eric Laurentde070132010-07-13 04:45:46 -07006460status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6461 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006462{
6463 status_t status = NO_ERROR;
6464
6465 if (EffectId == 0) {
6466 track->setAuxBuffer(0, NULL);
6467 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006468 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6469 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006470 if (effect != 0) {
6471 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6472 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6473 } else {
6474 status = INVALID_OPERATION;
6475 }
6476 } else {
6477 status = BAD_VALUE;
6478 }
6479 }
6480 return status;
6481}
6482
6483void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6484{
6485 for (size_t i = 0; i < mTracks.size(); ++i) {
6486 sp<Track> track = mTracks[i];
6487 if (track->auxEffectId() == effectId) {
6488 attachAuxEffect_l(track, 0);
6489 }
6490 }
6491}
6492
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006493status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6494{
6495 // only one chain per input thread
6496 if (mEffectChains.size() != 0) {
6497 return INVALID_OPERATION;
6498 }
Steve Block3856b092011-10-20 11:56:00 +01006499 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006500
6501 chain->setInBuffer(NULL);
6502 chain->setOutBuffer(NULL);
6503
Eric Laurent59255e42011-07-27 19:49:51 -07006504 checkSuspendOnAddEffectChain_l(chain);
6505
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006506 mEffectChains.add(chain);
6507
6508 return NO_ERROR;
6509}
6510
6511size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6512{
Steve Block3856b092011-10-20 11:56:00 +01006513 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006514 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006515 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6516 chain.get(), mEffectChains.size(), this);
6517 if (mEffectChains.size() == 1) {
6518 mEffectChains.removeAt(0);
6519 }
6520 return 0;
6521}
6522
Mathias Agopian65ab4712010-07-14 17:59:35 -07006523// ----------------------------------------------------------------------------
6524// EffectModule implementation
6525// ----------------------------------------------------------------------------
6526
6527#undef LOG_TAG
6528#define LOG_TAG "AudioFlinger::EffectModule"
6529
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006530AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006531 const wp<AudioFlinger::EffectChain>& chain,
6532 effect_descriptor_t *desc,
6533 int id,
6534 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006535 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006536 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006537{
Steve Block3856b092011-10-20 11:56:00 +01006538 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006539 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006540 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006541 return;
6542 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006543
6544 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6545
6546 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006547 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006548
6549 if (mStatus != NO_ERROR) {
6550 return;
6551 }
6552 lStatus = init();
6553 if (lStatus < 0) {
6554 mStatus = lStatus;
6555 goto Error;
6556 }
6557
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006558 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6559 mPinned = true;
6560 }
Steve Block3856b092011-10-20 11:56:00 +01006561 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006562 return;
6563Error:
6564 EffectRelease(mEffectInterface);
6565 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006566 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006567}
6568
6569AudioFlinger::EffectModule::~EffectModule()
6570{
Steve Block3856b092011-10-20 11:56:00 +01006571 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006572 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006573 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6574 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6575 sp<ThreadBase> thread = mThread.promote();
6576 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006577 audio_stream_t *stream = thread->stream();
6578 if (stream != NULL) {
6579 stream->remove_audio_effect(stream, mEffectInterface);
6580 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006581 }
6582 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006583 // release effect engine
6584 EffectRelease(mEffectInterface);
6585 }
6586}
6587
Glenn Kasten435dbe62012-01-30 10:15:48 -08006588status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006589{
6590 status_t status;
6591
6592 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006593 int priority = handle->priority();
6594 size_t size = mHandles.size();
6595 sp<EffectHandle> h;
6596 size_t i;
6597 for (i = 0; i < size; i++) {
6598 h = mHandles[i].promote();
6599 if (h == 0) continue;
6600 if (h->priority() <= priority) break;
6601 }
6602 // if inserted in first place, move effect control from previous owner to this handle
6603 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006604 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006605 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006606 enabled = h->enabled();
6607 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006608 }
Eric Laurent59255e42011-07-27 19:49:51 -07006609 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006610 status = NO_ERROR;
6611 } else {
6612 status = ALREADY_EXISTS;
6613 }
Steve Block3856b092011-10-20 11:56:00 +01006614 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006615 mHandles.insertAt(handle, i);
6616 return status;
6617}
6618
6619size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6620{
6621 Mutex::Autolock _l(mLock);
6622 size_t size = mHandles.size();
6623 size_t i;
6624 for (i = 0; i < size; i++) {
6625 if (mHandles[i] == handle) break;
6626 }
6627 if (i == size) {
6628 return size;
6629 }
Steve Block3856b092011-10-20 11:56:00 +01006630 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006631
6632 bool enabled = false;
6633 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006634 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006635 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006636 enabled = hdl->enabled();
6637 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006638 mHandles.removeAt(i);
6639 size = mHandles.size();
6640 // if removed from first place, move effect control from this handle to next in line
6641 if (i == 0 && size != 0) {
6642 sp<EffectHandle> h = mHandles[0].promote();
6643 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006644 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006645 }
6646 }
6647
Eric Laurentec437d82011-07-26 20:54:46 -07006648 // Prevent calls to process() and other functions on effect interface from now on.
6649 // The effect engine will be released by the destructor when the last strong reference on
6650 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006651 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006652 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006653 }
6654
Mathias Agopian65ab4712010-07-14 17:59:35 -07006655 return size;
6656}
6657
Eric Laurent59255e42011-07-27 19:49:51 -07006658sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6659{
6660 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08006661 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07006662}
6663
Glenn Kasten58123c32012-02-03 10:32:24 -08006664void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006665{
Glenn Kasten90bebef2012-01-27 15:24:38 -08006666 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006667 // keep a strong reference on this EffectModule to avoid calling the
6668 // destructor before we exit
6669 sp<EffectModule> keep(this);
6670 {
6671 sp<ThreadBase> thread = mThread.promote();
6672 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006673 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006674 }
6675 }
6676}
6677
6678void AudioFlinger::EffectModule::updateState() {
6679 Mutex::Autolock _l(mLock);
6680
6681 switch (mState) {
6682 case RESTART:
6683 reset_l();
6684 // FALL THROUGH
6685
6686 case STARTING:
6687 // clear auxiliary effect input buffer for next accumulation
6688 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6689 memset(mConfig.inputCfg.buffer.raw,
6690 0,
6691 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6692 }
6693 start_l();
6694 mState = ACTIVE;
6695 break;
6696 case STOPPING:
6697 stop_l();
6698 mDisableWaitCnt = mMaxDisableWaitCnt;
6699 mState = STOPPED;
6700 break;
6701 case STOPPED:
6702 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6703 // turn off sequence.
6704 if (--mDisableWaitCnt == 0) {
6705 reset_l();
6706 mState = IDLE;
6707 }
6708 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006709 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006710 break;
6711 }
6712}
6713
6714void AudioFlinger::EffectModule::process()
6715{
6716 Mutex::Autolock _l(mLock);
6717
Eric Laurentec437d82011-07-26 20:54:46 -07006718 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006719 mConfig.inputCfg.buffer.raw == NULL ||
6720 mConfig.outputCfg.buffer.raw == NULL) {
6721 return;
6722 }
6723
Eric Laurent8f45bd72010-08-31 13:50:07 -07006724 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006725 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6726 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006727 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006728 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006729 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006730 }
6731
6732 // do the actual processing in the effect engine
6733 int ret = (*mEffectInterface)->process(mEffectInterface,
6734 &mConfig.inputCfg.buffer,
6735 &mConfig.outputCfg.buffer);
6736
6737 // force transition to IDLE state when engine is ready
6738 if (mState == STOPPED && ret == -ENODATA) {
6739 mDisableWaitCnt = 1;
6740 }
6741
6742 // clear auxiliary effect input buffer for next accumulation
6743 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006744 memset(mConfig.inputCfg.buffer.raw, 0,
6745 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006746 }
6747 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006748 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6749 // If an insert effect is idle and input buffer is different from output buffer,
6750 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006751 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006752 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006753 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6754 int16_t *in = mConfig.inputCfg.buffer.s16;
6755 int16_t *out = mConfig.outputCfg.buffer.s16;
6756 for (size_t i = 0; i < frameCnt; i++) {
6757 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006758 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006759 }
6760 }
6761}
6762
6763void AudioFlinger::EffectModule::reset_l()
6764{
6765 if (mEffectInterface == NULL) {
6766 return;
6767 }
6768 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6769}
6770
6771status_t AudioFlinger::EffectModule::configure()
6772{
6773 uint32_t channels;
6774 if (mEffectInterface == NULL) {
6775 return NO_INIT;
6776 }
6777
6778 sp<ThreadBase> thread = mThread.promote();
6779 if (thread == 0) {
6780 return DEAD_OBJECT;
6781 }
6782
6783 // TODO: handle configuration of effects replacing track process
6784 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006785 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006786 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006787 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006788 }
6789
6790 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006791 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006792 } else {
6793 mConfig.inputCfg.channels = channels;
6794 }
6795 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006796 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6797 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006798 mConfig.inputCfg.samplingRate = thread->sampleRate();
6799 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6800 mConfig.inputCfg.bufferProvider.cookie = NULL;
6801 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6802 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6803 mConfig.outputCfg.bufferProvider.cookie = NULL;
6804 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6805 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6806 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6807 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006808 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006809 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006810 // - in other sessions:
6811 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6812 // other effect: overwrites output buffer: input buffer == output buffer
6813 // Auxiliary effect:
6814 // accumulates in output buffer: input buffer != output buffer
6815 // Therefore: accumulate <=> input buffer != output buffer
6816 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6817 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6818 } else {
6819 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6820 }
6821 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6822 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6823 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6824 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6825
Steve Block3856b092011-10-20 11:56:00 +01006826 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006827 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6828
Mathias Agopian65ab4712010-07-14 17:59:35 -07006829 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006830 uint32_t size = sizeof(int);
6831 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006832 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006833 sizeof(effect_config_t),
6834 &mConfig,
6835 &size,
6836 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006837 if (status == 0) {
6838 status = cmdStatus;
6839 }
6840
6841 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6842 (1000 * mConfig.outputCfg.buffer.frameCount);
6843
6844 return status;
6845}
6846
6847status_t AudioFlinger::EffectModule::init()
6848{
6849 Mutex::Autolock _l(mLock);
6850 if (mEffectInterface == NULL) {
6851 return NO_INIT;
6852 }
6853 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006854 uint32_t size = sizeof(status_t);
6855 status_t status = (*mEffectInterface)->command(mEffectInterface,
6856 EFFECT_CMD_INIT,
6857 0,
6858 NULL,
6859 &size,
6860 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006861 if (status == 0) {
6862 status = cmdStatus;
6863 }
6864 return status;
6865}
6866
Eric Laurentec35a142011-10-05 17:42:25 -07006867status_t AudioFlinger::EffectModule::start()
6868{
6869 Mutex::Autolock _l(mLock);
6870 return start_l();
6871}
6872
Mathias Agopian65ab4712010-07-14 17:59:35 -07006873status_t AudioFlinger::EffectModule::start_l()
6874{
6875 if (mEffectInterface == NULL) {
6876 return NO_INIT;
6877 }
6878 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006879 uint32_t size = sizeof(status_t);
6880 status_t status = (*mEffectInterface)->command(mEffectInterface,
6881 EFFECT_CMD_ENABLE,
6882 0,
6883 NULL,
6884 &size,
6885 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006886 if (status == 0) {
6887 status = cmdStatus;
6888 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006889 if (status == 0 &&
6890 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6891 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6892 sp<ThreadBase> thread = mThread.promote();
6893 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006894 audio_stream_t *stream = thread->stream();
6895 if (stream != NULL) {
6896 stream->add_audio_effect(stream, mEffectInterface);
6897 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006898 }
6899 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006900 return status;
6901}
6902
Eric Laurentec437d82011-07-26 20:54:46 -07006903status_t AudioFlinger::EffectModule::stop()
6904{
6905 Mutex::Autolock _l(mLock);
6906 return stop_l();
6907}
6908
Mathias Agopian65ab4712010-07-14 17:59:35 -07006909status_t AudioFlinger::EffectModule::stop_l()
6910{
6911 if (mEffectInterface == NULL) {
6912 return NO_INIT;
6913 }
6914 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006915 uint32_t size = sizeof(status_t);
6916 status_t status = (*mEffectInterface)->command(mEffectInterface,
6917 EFFECT_CMD_DISABLE,
6918 0,
6919 NULL,
6920 &size,
6921 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006922 if (status == 0) {
6923 status = cmdStatus;
6924 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006925 if (status == 0 &&
6926 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6927 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6928 sp<ThreadBase> thread = mThread.promote();
6929 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006930 audio_stream_t *stream = thread->stream();
6931 if (stream != NULL) {
6932 stream->remove_audio_effect(stream, mEffectInterface);
6933 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006934 }
6935 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006936 return status;
6937}
6938
Eric Laurent25f43952010-07-28 05:40:18 -07006939status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6940 uint32_t cmdSize,
6941 void *pCmdData,
6942 uint32_t *replySize,
6943 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006944{
6945 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006946// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006947
Eric Laurentec437d82011-07-26 20:54:46 -07006948 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006949 return NO_INIT;
6950 }
Eric Laurent25f43952010-07-28 05:40:18 -07006951 status_t status = (*mEffectInterface)->command(mEffectInterface,
6952 cmdCode,
6953 cmdSize,
6954 pCmdData,
6955 replySize,
6956 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006957 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006958 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006959 for (size_t i = 1; i < mHandles.size(); i++) {
6960 sp<EffectHandle> h = mHandles[i].promote();
6961 if (h != 0) {
6962 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6963 }
6964 }
6965 }
6966 return status;
6967}
6968
6969status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6970{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006971
Mathias Agopian65ab4712010-07-14 17:59:35 -07006972 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006973 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006974
6975 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006976 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6977 if (enabled && status != NO_ERROR) {
6978 return status;
6979 }
6980
Mathias Agopian65ab4712010-07-14 17:59:35 -07006981 switch (mState) {
6982 // going from disabled to enabled
6983 case IDLE:
6984 mState = STARTING;
6985 break;
6986 case STOPPED:
6987 mState = RESTART;
6988 break;
6989 case STOPPING:
6990 mState = ACTIVE;
6991 break;
6992
6993 // going from enabled to disabled
6994 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006995 mState = STOPPED;
6996 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006997 case STARTING:
6998 mState = IDLE;
6999 break;
7000 case ACTIVE:
7001 mState = STOPPING;
7002 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007003 case DESTROYED:
7004 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007005 }
7006 for (size_t i = 1; i < mHandles.size(); i++) {
7007 sp<EffectHandle> h = mHandles[i].promote();
7008 if (h != 0) {
7009 h->setEnabled(enabled);
7010 }
7011 }
7012 }
7013 return NO_ERROR;
7014}
7015
Glenn Kastenc59c0042012-02-02 14:06:11 -08007016bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007017{
7018 switch (mState) {
7019 case RESTART:
7020 case STARTING:
7021 case ACTIVE:
7022 return true;
7023 case IDLE:
7024 case STOPPING:
7025 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07007026 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07007027 default:
7028 return false;
7029 }
7030}
7031
Glenn Kastenc59c0042012-02-02 14:06:11 -08007032bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07007033{
7034 switch (mState) {
7035 case RESTART:
7036 case ACTIVE:
7037 case STOPPING:
7038 case STOPPED:
7039 return true;
7040 case IDLE:
7041 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07007042 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007043 default:
7044 return false;
7045 }
7046}
7047
Mathias Agopian65ab4712010-07-14 17:59:35 -07007048status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7049{
7050 Mutex::Autolock _l(mLock);
7051 status_t status = NO_ERROR;
7052
7053 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7054 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07007055 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07007056 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7057 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007058 status_t cmdStatus;
7059 uint32_t volume[2];
7060 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07007061 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007062 volume[0] = *left;
7063 volume[1] = *right;
7064 if (controller) {
7065 pVolume = volume;
7066 }
Eric Laurent25f43952010-07-28 05:40:18 -07007067 status = (*mEffectInterface)->command(mEffectInterface,
7068 EFFECT_CMD_SET_VOLUME,
7069 size,
7070 volume,
7071 &size,
7072 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007073 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7074 *left = volume[0];
7075 *right = volume[1];
7076 }
7077 }
7078 return status;
7079}
7080
7081status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7082{
7083 Mutex::Autolock _l(mLock);
7084 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007085 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7086 // audio pre processing modules on RecordThread can receive both output and
7087 // input device indication in the same call
7088 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7089 if (dev) {
7090 status_t cmdStatus;
7091 uint32_t size = sizeof(status_t);
7092
7093 status = (*mEffectInterface)->command(mEffectInterface,
7094 EFFECT_CMD_SET_DEVICE,
7095 sizeof(uint32_t),
7096 &dev,
7097 &size,
7098 &cmdStatus);
7099 if (status == NO_ERROR) {
7100 status = cmdStatus;
7101 }
7102 }
7103 dev = device & AUDIO_DEVICE_IN_ALL;
7104 if (dev) {
7105 status_t cmdStatus;
7106 uint32_t size = sizeof(status_t);
7107
7108 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7109 EFFECT_CMD_SET_INPUT_DEVICE,
7110 sizeof(uint32_t),
7111 &dev,
7112 &size,
7113 &cmdStatus);
7114 if (status2 == NO_ERROR) {
7115 status2 = cmdStatus;
7116 }
7117 if (status == NO_ERROR) {
7118 status = status2;
7119 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007120 }
7121 }
7122 return status;
7123}
7124
Glenn Kastenf78aee72012-01-04 11:00:47 -08007125status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007126{
7127 Mutex::Autolock _l(mLock);
7128 status_t status = NO_ERROR;
7129 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007130 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007131 uint32_t size = sizeof(status_t);
7132 status = (*mEffectInterface)->command(mEffectInterface,
7133 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08007134 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07007135 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07007136 &size,
7137 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007138 if (status == NO_ERROR) {
7139 status = cmdStatus;
7140 }
7141 }
7142 return status;
7143}
7144
Eric Laurent59255e42011-07-27 19:49:51 -07007145void AudioFlinger::EffectModule::setSuspended(bool suspended)
7146{
7147 Mutex::Autolock _l(mLock);
7148 mSuspended = suspended;
7149}
Glenn Kastena3a85482012-01-04 11:01:11 -08007150
7151bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07007152{
7153 Mutex::Autolock _l(mLock);
7154 return mSuspended;
7155}
7156
Mathias Agopian65ab4712010-07-14 17:59:35 -07007157status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7158{
7159 const size_t SIZE = 256;
7160 char buffer[SIZE];
7161 String8 result;
7162
7163 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7164 result.append(buffer);
7165
7166 bool locked = tryLock(mLock);
7167 // failed to lock - AudioFlinger is probably deadlocked
7168 if (!locked) {
7169 result.append("\t\tCould not lock Fx mutex:\n");
7170 }
7171
7172 result.append("\t\tSession Status State Engine:\n");
7173 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7174 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7175 result.append(buffer);
7176
7177 result.append("\t\tDescriptor:\n");
7178 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7179 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7180 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7181 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7182 result.append(buffer);
7183 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7184 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7185 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7186 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7187 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07007188 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007189 mDescriptor.apiVersion,
7190 mDescriptor.flags);
7191 result.append(buffer);
7192 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7193 mDescriptor.name);
7194 result.append(buffer);
7195 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7196 mDescriptor.implementor);
7197 result.append(buffer);
7198
7199 result.append("\t\t- Input configuration:\n");
7200 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7201 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7202 (uint32_t)mConfig.inputCfg.buffer.raw,
7203 mConfig.inputCfg.buffer.frameCount,
7204 mConfig.inputCfg.samplingRate,
7205 mConfig.inputCfg.channels,
7206 mConfig.inputCfg.format);
7207 result.append(buffer);
7208
7209 result.append("\t\t- Output configuration:\n");
7210 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7211 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7212 (uint32_t)mConfig.outputCfg.buffer.raw,
7213 mConfig.outputCfg.buffer.frameCount,
7214 mConfig.outputCfg.samplingRate,
7215 mConfig.outputCfg.channels,
7216 mConfig.outputCfg.format);
7217 result.append(buffer);
7218
7219 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7220 result.append(buffer);
7221 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7222 for (size_t i = 0; i < mHandles.size(); ++i) {
7223 sp<EffectHandle> handle = mHandles[i].promote();
7224 if (handle != 0) {
7225 handle->dump(buffer, SIZE);
7226 result.append(buffer);
7227 }
7228 }
7229
7230 result.append("\n");
7231
7232 write(fd, result.string(), result.length());
7233
7234 if (locked) {
7235 mLock.unlock();
7236 }
7237
7238 return NO_ERROR;
7239}
7240
7241// ----------------------------------------------------------------------------
7242// EffectHandle implementation
7243// ----------------------------------------------------------------------------
7244
7245#undef LOG_TAG
7246#define LOG_TAG "AudioFlinger::EffectHandle"
7247
7248AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7249 const sp<AudioFlinger::Client>& client,
7250 const sp<IEffectClient>& effectClient,
7251 int32_t priority)
7252 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007253 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007254 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007255{
Steve Block3856b092011-10-20 11:56:00 +01007256 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007257
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007258 if (client == 0) {
7259 return;
7260 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007261 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7262 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7263 if (mCblkMemory != 0) {
7264 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7265
Glenn Kastena0d68332012-01-27 16:47:15 -08007266 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007267 new(mCblk) effect_param_cblk_t();
7268 mBuffer = (uint8_t *)mCblk + bufOffset;
7269 }
7270 } else {
Steve Block29357bc2012-01-06 19:20:56 +00007271 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007272 return;
7273 }
7274}
7275
7276AudioFlinger::EffectHandle::~EffectHandle()
7277{
Steve Block3856b092011-10-20 11:56:00 +01007278 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007279 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01007280 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007281}
7282
7283status_t AudioFlinger::EffectHandle::enable()
7284{
Steve Block3856b092011-10-20 11:56:00 +01007285 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007286 if (!mHasControl) return INVALID_OPERATION;
7287 if (mEffect == 0) return DEAD_OBJECT;
7288
Eric Laurentdb7c0792011-08-10 10:37:50 -07007289 if (mEnabled) {
7290 return NO_ERROR;
7291 }
7292
Eric Laurent59255e42011-07-27 19:49:51 -07007293 mEnabled = true;
7294
7295 sp<ThreadBase> thread = mEffect->thread().promote();
7296 if (thread != 0) {
7297 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7298 }
7299
7300 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7301 if (mEffect->suspended()) {
7302 return NO_ERROR;
7303 }
7304
Eric Laurentdb7c0792011-08-10 10:37:50 -07007305 status_t status = mEffect->setEnabled(true);
7306 if (status != NO_ERROR) {
7307 if (thread != 0) {
7308 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7309 }
7310 mEnabled = false;
7311 }
7312 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007313}
7314
7315status_t AudioFlinger::EffectHandle::disable()
7316{
Steve Block3856b092011-10-20 11:56:00 +01007317 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007318 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07007319 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007320
Eric Laurentdb7c0792011-08-10 10:37:50 -07007321 if (!mEnabled) {
7322 return NO_ERROR;
7323 }
Eric Laurent59255e42011-07-27 19:49:51 -07007324 mEnabled = false;
7325
7326 if (mEffect->suspended()) {
7327 return NO_ERROR;
7328 }
7329
7330 status_t status = mEffect->setEnabled(false);
7331
7332 sp<ThreadBase> thread = mEffect->thread().promote();
7333 if (thread != 0) {
7334 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7335 }
7336
7337 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007338}
7339
7340void AudioFlinger::EffectHandle::disconnect()
7341{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007342 disconnect(true);
7343}
7344
Glenn Kasten58123c32012-02-03 10:32:24 -08007345void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007346{
Glenn Kasten58123c32012-02-03 10:32:24 -08007347 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007348 if (mEffect == 0) {
7349 return;
7350 }
Glenn Kasten58123c32012-02-03 10:32:24 -08007351 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07007352
Eric Laurenta85a74a2011-10-19 11:44:54 -07007353 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007354 sp<ThreadBase> thread = mEffect->thread().promote();
7355 if (thread != 0) {
7356 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7357 }
Eric Laurent59255e42011-07-27 19:49:51 -07007358 }
7359
Mathias Agopian65ab4712010-07-14 17:59:35 -07007360 // release sp on module => module destructor can be called now
7361 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007362 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08007363 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08007364 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007365 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7366 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08007367 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007368 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07007369 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7370 mClient.clear();
7371 }
7372}
7373
Eric Laurent25f43952010-07-28 05:40:18 -07007374status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7375 uint32_t cmdSize,
7376 void *pCmdData,
7377 uint32_t *replySize,
7378 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007379{
Steve Block3856b092011-10-20 11:56:00 +01007380// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07007381// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007382
7383 // only get parameter command is permitted for applications not controlling the effect
7384 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7385 return INVALID_OPERATION;
7386 }
7387 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007388 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007389
7390 // handle commands that are not forwarded transparently to effect engine
7391 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7392 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7393 // no risk to block the whole media server process or mixer threads is we are stuck here
7394 Mutex::Autolock _l(mCblk->lock);
7395 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7396 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7397 mCblk->serverIndex = 0;
7398 mCblk->clientIndex = 0;
7399 return BAD_VALUE;
7400 }
7401 status_t status = NO_ERROR;
7402 while (mCblk->serverIndex < mCblk->clientIndex) {
7403 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007404 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007405 int *p = (int *)(mBuffer + mCblk->serverIndex);
7406 int size = *p++;
7407 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007408 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007409 break;
7410 }
7411 effect_param_t *param = (effect_param_t *)p;
7412 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007413 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007414 mCblk->serverIndex += size;
7415 continue;
7416 }
Eric Laurent25f43952010-07-28 05:40:18 -07007417 uint32_t psize = sizeof(effect_param_t) +
7418 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7419 param->vsize;
7420 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7421 psize,
7422 p,
7423 &rsize,
7424 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007425 // stop at first error encountered
7426 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007427 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007428 *(int *)pReplyData = reply;
7429 break;
7430 } else if (reply != NO_ERROR) {
7431 *(int *)pReplyData = reply;
7432 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007433 }
7434 mCblk->serverIndex += size;
7435 }
7436 mCblk->serverIndex = 0;
7437 mCblk->clientIndex = 0;
7438 return status;
7439 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007440 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007441 return enable();
7442 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007443 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007444 return disable();
7445 }
7446
7447 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7448}
7449
Eric Laurent59255e42011-07-27 19:49:51 -07007450void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007451{
Steve Block3856b092011-10-20 11:56:00 +01007452 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007453
7454 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007455 mEnabled = enabled;
7456
Mathias Agopian65ab4712010-07-14 17:59:35 -07007457 if (signal && mEffectClient != 0) {
7458 mEffectClient->controlStatusChanged(hasControl);
7459 }
7460}
7461
Eric Laurent25f43952010-07-28 05:40:18 -07007462void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7463 uint32_t cmdSize,
7464 void *pCmdData,
7465 uint32_t replySize,
7466 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007467{
7468 if (mEffectClient != 0) {
7469 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7470 }
7471}
7472
7473
7474
7475void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7476{
7477 if (mEffectClient != 0) {
7478 mEffectClient->enableStatusChanged(enabled);
7479 }
7480}
7481
7482status_t AudioFlinger::EffectHandle::onTransact(
7483 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7484{
7485 return BnEffect::onTransact(code, data, reply, flags);
7486}
7487
7488
7489void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7490{
Glenn Kastena0d68332012-01-27 16:47:15 -08007491 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007492
7493 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08007494 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007495 mPriority,
7496 mHasControl,
7497 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007498 mCblk ? mCblk->clientIndex : 0,
7499 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007500 );
7501
7502 if (locked) {
7503 mCblk->lock.unlock();
7504 }
7505}
7506
7507#undef LOG_TAG
7508#define LOG_TAG "AudioFlinger::EffectChain"
7509
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007510AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007511 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007512 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007513 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7514 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007515{
Dima Zavinfce7a472011-04-19 22:30:36 -07007516 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007517 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007518 return;
7519 }
7520 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7521 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007522}
7523
7524AudioFlinger::EffectChain::~EffectChain()
7525{
7526 if (mOwnInBuffer) {
7527 delete mInBuffer;
7528 }
7529
7530}
7531
Eric Laurent59255e42011-07-27 19:49:51 -07007532// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007533sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007534{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007535 size_t size = mEffects.size();
7536
7537 for (size_t i = 0; i < size; i++) {
7538 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007539 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007540 }
7541 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007542 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007543}
7544
Eric Laurent59255e42011-07-27 19:49:51 -07007545// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007546sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007547{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007548 size_t size = mEffects.size();
7549
7550 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007551 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7552 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007553 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007554 }
7555 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007556 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007557}
7558
Eric Laurent59255e42011-07-27 19:49:51 -07007559// getEffectFromType_l() must be called with ThreadBase::mLock held
7560sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7561 const effect_uuid_t *type)
7562{
Eric Laurent59255e42011-07-27 19:49:51 -07007563 size_t size = mEffects.size();
7564
7565 for (size_t i = 0; i < size; i++) {
7566 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007567 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007568 }
7569 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007570 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007571}
7572
Mathias Agopian65ab4712010-07-14 17:59:35 -07007573// Must be called with EffectChain::mLock locked
7574void AudioFlinger::EffectChain::process_l()
7575{
Eric Laurentdac69112010-09-28 14:09:57 -07007576 sp<ThreadBase> thread = mThread.promote();
7577 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007578 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007579 return;
7580 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007581 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7582 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007583 // always process effects unless no more tracks are on the session and the effect tail
7584 // has been rendered
7585 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007586 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007587 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007588
Eric Laurent544fe9b2011-11-11 15:42:52 -08007589 if (!tracksOnSession && mTailBufferCount == 0) {
7590 doProcess = false;
7591 }
7592
7593 if (activeTrackCnt() == 0) {
7594 // if no track is active and the effect tail has not been rendered,
7595 // the input buffer must be cleared here as the mixer process will not do it
7596 if (tracksOnSession || mTailBufferCount > 0) {
7597 size_t numSamples = thread->frameCount() * thread->channelCount();
7598 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7599 if (mTailBufferCount > 0) {
7600 mTailBufferCount--;
7601 }
7602 }
7603 }
Eric Laurentdac69112010-09-28 14:09:57 -07007604 }
7605
Mathias Agopian65ab4712010-07-14 17:59:35 -07007606 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007607 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007608 for (size_t i = 0; i < size; i++) {
7609 mEffects[i]->process();
7610 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007611 }
7612 for (size_t i = 0; i < size; i++) {
7613 mEffects[i]->updateState();
7614 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007615}
7616
Eric Laurentcab11242010-07-15 12:50:15 -07007617// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007618status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007619{
7620 effect_descriptor_t desc = effect->desc();
7621 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7622
7623 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007624 effect->setChain(this);
7625 sp<ThreadBase> thread = mThread.promote();
7626 if (thread == 0) {
7627 return NO_INIT;
7628 }
7629 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007630
7631 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7632 // Auxiliary effects are inserted at the beginning of mEffects vector as
7633 // they are processed first and accumulated in chain input buffer
7634 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007635
Mathias Agopian65ab4712010-07-14 17:59:35 -07007636 // the input buffer for auxiliary effect contains mono samples in
7637 // 32 bit format. This is to avoid saturation in AudoMixer
7638 // accumulation stage. Saturation is done in EffectModule::process() before
7639 // calling the process in effect engine
7640 size_t numSamples = thread->frameCount();
7641 int32_t *buffer = new int32_t[numSamples];
7642 memset(buffer, 0, numSamples * sizeof(int32_t));
7643 effect->setInBuffer((int16_t *)buffer);
7644 // auxiliary effects output samples to chain input buffer for further processing
7645 // by insert effects
7646 effect->setOutBuffer(mInBuffer);
7647 } else {
7648 // Insert effects are inserted at the end of mEffects vector as they are processed
7649 // after track and auxiliary effects.
7650 // Insert effect order as a function of indicated preference:
7651 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7652 // another effect is present
7653 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7654 // last effect claiming first position
7655 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7656 // first effect claiming last position
7657 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7658 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7659 // already present
7660
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007661 size_t size = mEffects.size();
7662 size_t idx_insert = size;
7663 ssize_t idx_insert_first = -1;
7664 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007665
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007666 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007667 effect_descriptor_t d = mEffects[i]->desc();
7668 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7669 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7670 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7671 // check invalid effect chaining combinations
7672 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7673 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007674 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007675 return INVALID_OPERATION;
7676 }
7677 // remember position of first insert effect and by default
7678 // select this as insert position for new effect
7679 if (idx_insert == size) {
7680 idx_insert = i;
7681 }
7682 // remember position of last insert effect claiming
7683 // first position
7684 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7685 idx_insert_first = i;
7686 }
7687 // remember position of first insert effect claiming
7688 // last position
7689 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7690 idx_insert_last == -1) {
7691 idx_insert_last = i;
7692 }
7693 }
7694 }
7695
7696 // modify idx_insert from first position if needed
7697 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7698 if (idx_insert_last != -1) {
7699 idx_insert = idx_insert_last;
7700 } else {
7701 idx_insert = size;
7702 }
7703 } else {
7704 if (idx_insert_first != -1) {
7705 idx_insert = idx_insert_first + 1;
7706 }
7707 }
7708
7709 // always read samples from chain input buffer
7710 effect->setInBuffer(mInBuffer);
7711
7712 // if last effect in the chain, output samples to chain
7713 // output buffer, otherwise to chain input buffer
7714 if (idx_insert == size) {
7715 if (idx_insert != 0) {
7716 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7717 mEffects[idx_insert-1]->configure();
7718 }
7719 effect->setOutBuffer(mOutBuffer);
7720 } else {
7721 effect->setOutBuffer(mInBuffer);
7722 }
7723 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007724
Steve Block3856b092011-10-20 11:56:00 +01007725 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007726 }
7727 effect->configure();
7728 return NO_ERROR;
7729}
7730
Eric Laurentcab11242010-07-15 12:50:15 -07007731// removeEffect_l() must be called with PlaybackThread::mLock held
7732size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007733{
7734 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007735 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007736 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7737
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007738 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007739 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007740 // calling stop here will remove pre-processing effect from the audio HAL.
7741 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7742 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007743 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7744 mEffects[i]->state() == EffectModule::STOPPING) {
7745 mEffects[i]->stop();
7746 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007747 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7748 delete[] effect->inBuffer();
7749 } else {
7750 if (i == size - 1 && i != 0) {
7751 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7752 mEffects[i - 1]->configure();
7753 }
7754 }
7755 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007756 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007757 break;
7758 }
7759 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007760
7761 return mEffects.size();
7762}
7763
Eric Laurentcab11242010-07-15 12:50:15 -07007764// setDevice_l() must be called with PlaybackThread::mLock held
7765void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007766{
7767 size_t size = mEffects.size();
7768 for (size_t i = 0; i < size; i++) {
7769 mEffects[i]->setDevice(device);
7770 }
7771}
7772
Eric Laurentcab11242010-07-15 12:50:15 -07007773// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007774void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007775{
7776 size_t size = mEffects.size();
7777 for (size_t i = 0; i < size; i++) {
7778 mEffects[i]->setMode(mode);
7779 }
7780}
7781
Eric Laurentcab11242010-07-15 12:50:15 -07007782// setVolume_l() must be called with PlaybackThread::mLock held
7783bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007784{
7785 uint32_t newLeft = *left;
7786 uint32_t newRight = *right;
7787 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007788 int ctrlIdx = -1;
7789 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007790
Eric Laurentcab11242010-07-15 12:50:15 -07007791 // first update volume controller
7792 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007793 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007794 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7795 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007796 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007797 break;
7798 }
7799 }
7800
7801 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007802 if (hasControl) {
7803 *left = mNewLeftVolume;
7804 *right = mNewRightVolume;
7805 }
7806 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007807 }
7808
7809 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007810 mLeftVolume = newLeft;
7811 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007812
7813 // second get volume update from volume controller
7814 if (ctrlIdx >= 0) {
7815 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007816 mNewLeftVolume = newLeft;
7817 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007818 }
7819 // then indicate volume to all other effects in chain.
7820 // Pass altered volume to effects before volume controller
7821 // and requested volume to effects after controller
7822 uint32_t lVol = newLeft;
7823 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007824
Mathias Agopian65ab4712010-07-14 17:59:35 -07007825 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007826 if ((int)i == ctrlIdx) continue;
7827 // this also works for ctrlIdx == -1 when there is no volume controller
7828 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007829 lVol = *left;
7830 rVol = *right;
7831 }
7832 mEffects[i]->setVolume(&lVol, &rVol, false);
7833 }
7834 *left = newLeft;
7835 *right = newRight;
7836
7837 return hasControl;
7838}
7839
Mathias Agopian65ab4712010-07-14 17:59:35 -07007840status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7841{
7842 const size_t SIZE = 256;
7843 char buffer[SIZE];
7844 String8 result;
7845
7846 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7847 result.append(buffer);
7848
7849 bool locked = tryLock(mLock);
7850 // failed to lock - AudioFlinger is probably deadlocked
7851 if (!locked) {
7852 result.append("\tCould not lock mutex:\n");
7853 }
7854
Eric Laurentcab11242010-07-15 12:50:15 -07007855 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7856 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007857 mEffects.size(),
7858 (uint32_t)mInBuffer,
7859 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007860 mActiveTrackCnt);
7861 result.append(buffer);
7862 write(fd, result.string(), result.size());
7863
7864 for (size_t i = 0; i < mEffects.size(); ++i) {
7865 sp<EffectModule> effect = mEffects[i];
7866 if (effect != 0) {
7867 effect->dump(fd, args);
7868 }
7869 }
7870
7871 if (locked) {
7872 mLock.unlock();
7873 }
7874
7875 return NO_ERROR;
7876}
7877
Eric Laurent59255e42011-07-27 19:49:51 -07007878// must be called with ThreadBase::mLock held
7879void AudioFlinger::EffectChain::setEffectSuspended_l(
7880 const effect_uuid_t *type, bool suspend)
7881{
7882 sp<SuspendedEffectDesc> desc;
7883 // use effect type UUID timelow as key as there is no real risk of identical
7884 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007885 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007886 if (suspend) {
7887 if (index >= 0) {
7888 desc = mSuspendedEffects.valueAt(index);
7889 } else {
7890 desc = new SuspendedEffectDesc();
7891 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7892 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007893 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007894 }
7895 if (desc->mRefCount++ == 0) {
7896 sp<EffectModule> effect = getEffectIfEnabled(type);
7897 if (effect != 0) {
7898 desc->mEffect = effect;
7899 effect->setSuspended(true);
7900 effect->setEnabled(false);
7901 }
7902 }
7903 } else {
7904 if (index < 0) {
7905 return;
7906 }
7907 desc = mSuspendedEffects.valueAt(index);
7908 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007909 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007910 desc->mRefCount = 1;
7911 }
7912 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007913 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007914 if (desc->mEffect != 0) {
7915 sp<EffectModule> effect = desc->mEffect.promote();
7916 if (effect != 0) {
7917 effect->setSuspended(false);
7918 sp<EffectHandle> handle = effect->controlHandle();
7919 if (handle != 0) {
7920 effect->setEnabled(handle->enabled());
7921 }
7922 }
7923 desc->mEffect.clear();
7924 }
7925 mSuspendedEffects.removeItemsAt(index);
7926 }
7927 }
7928}
7929
7930// must be called with ThreadBase::mLock held
7931void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7932{
7933 sp<SuspendedEffectDesc> desc;
7934
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007935 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07007936 if (suspend) {
7937 if (index >= 0) {
7938 desc = mSuspendedEffects.valueAt(index);
7939 } else {
7940 desc = new SuspendedEffectDesc();
7941 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007942 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007943 }
7944 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08007945 Vector< sp<EffectModule> > effects;
7946 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07007947 for (size_t i = 0; i < effects.size(); i++) {
7948 setEffectSuspended_l(&effects[i]->desc().type, true);
7949 }
7950 }
7951 } else {
7952 if (index < 0) {
7953 return;
7954 }
7955 desc = mSuspendedEffects.valueAt(index);
7956 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007957 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007958 desc->mRefCount = 1;
7959 }
7960 if (--desc->mRefCount == 0) {
7961 Vector<const effect_uuid_t *> types;
7962 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7963 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7964 continue;
7965 }
7966 types.add(&mSuspendedEffects.valueAt(i)->mType);
7967 }
7968 for (size_t i = 0; i < types.size(); i++) {
7969 setEffectSuspended_l(types[i], false);
7970 }
Steve Block3856b092011-10-20 11:56:00 +01007971 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007972 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7973 }
7974 }
7975}
7976
Eric Laurent6bffdb82011-09-23 08:40:41 -07007977
7978// The volume effect is used for automated tests only
7979#ifndef OPENSL_ES_H_
7980static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7981 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7982const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7983#endif //OPENSL_ES_H_
7984
Eric Laurentdb7c0792011-08-10 10:37:50 -07007985bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7986{
7987 // auxiliary effects and visualizer are never suspended on output mix
7988 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7989 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007990 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7991 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007992 return false;
7993 }
7994 return true;
7995}
7996
Glenn Kastend0539712012-01-30 12:56:03 -08007997void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07007998{
Glenn Kastend0539712012-01-30 12:56:03 -08007999 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07008000 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08008001 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8002 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07008003 }
Eric Laurent59255e42011-07-27 19:49:51 -07008004 }
Eric Laurent59255e42011-07-27 19:49:51 -07008005}
8006
8007sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8008 const effect_uuid_t *type)
8009{
Glenn Kasten090f0192012-01-30 13:00:02 -08008010 sp<EffectModule> effect = getEffectFromType_l(type);
8011 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008012}
8013
8014void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8015 bool enabled)
8016{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008017 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008018 if (enabled) {
8019 if (index < 0) {
8020 // if the effect is not suspend check if all effects are suspended
8021 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8022 if (index < 0) {
8023 return;
8024 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07008025 if (!isEffectEligibleForSuspend(effect->desc())) {
8026 return;
8027 }
Eric Laurent59255e42011-07-27 19:49:51 -07008028 setEffectSuspended_l(&effect->desc().type, enabled);
8029 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07008030 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008031 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07008032 return;
8033 }
Eric Laurent59255e42011-07-27 19:49:51 -07008034 }
Steve Block3856b092011-10-20 11:56:00 +01008035 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07008036 effect->desc().type.timeLow);
8037 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8038 // if effect is requested to suspended but was not yet enabled, supend it now.
8039 if (desc->mEffect == 0) {
8040 desc->mEffect = effect;
8041 effect->setEnabled(false);
8042 effect->setSuspended(true);
8043 }
8044 } else {
8045 if (index < 0) {
8046 return;
8047 }
Steve Block3856b092011-10-20 11:56:00 +01008048 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07008049 effect->desc().type.timeLow);
8050 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8051 desc->mEffect.clear();
8052 effect->setSuspended(false);
8053 }
8054}
8055
Mathias Agopian65ab4712010-07-14 17:59:35 -07008056#undef LOG_TAG
8057#define LOG_TAG "AudioFlinger"
8058
8059// ----------------------------------------------------------------------------
8060
8061status_t AudioFlinger::onTransact(
8062 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8063{
8064 return BnAudioFlinger::onTransact(code, data, reply, flags);
8065}
8066
Mathias Agopian65ab4712010-07-14 17:59:35 -07008067}; // namespace android