blob: 2f49808774ce0ba993969d92510997c900677e1e [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;
726 assert(NULL != mPrimaryHardwareDev);
727 assert(NULL != mPrimaryHardwareDev->get_master_volume);
728
729 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
730 mHardwareStatus = AUDIO_HW_IDLE;
731 return ret_val;
732 }
733
734 return mMasterVolume;
735}
736
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800737status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
738 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700739{
740 // check calling permissions
741 if (!settingsAllowed()) {
742 return PERMISSION_DENIED;
743 }
744
Glenn Kasten263709e2012-01-06 08:40:01 -0800745 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000746 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700747 return BAD_VALUE;
748 }
749
750 AutoMutex lock(mLock);
751 PlaybackThread *thread = NULL;
752 if (output) {
753 thread = checkPlaybackThread_l(output);
754 if (thread == NULL) {
755 return BAD_VALUE;
756 }
757 }
758
759 mStreamTypes[stream].volume = value;
760
761 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800762 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700763 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
764 }
765 } else {
766 thread->setStreamVolume(stream, value);
767 }
768
769 return NO_ERROR;
770}
771
Glenn Kastenfff6d712012-01-12 16:38:12 -0800772status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700773{
774 // check calling permissions
775 if (!settingsAllowed()) {
776 return PERMISSION_DENIED;
777 }
778
Glenn Kasten263709e2012-01-06 08:40:01 -0800779 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700780 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000781 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700782 return BAD_VALUE;
783 }
784
Eric Laurent93575202011-01-18 18:39:02 -0800785 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700786 mStreamTypes[stream].mute = muted;
787 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
788 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
789
790 return NO_ERROR;
791}
792
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800793float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700794{
Glenn Kasten263709e2012-01-06 08:40:01 -0800795 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796 return 0.0f;
797 }
798
799 AutoMutex lock(mLock);
800 float volume;
801 if (output) {
802 PlaybackThread *thread = checkPlaybackThread_l(output);
803 if (thread == NULL) {
804 return 0.0f;
805 }
806 volume = thread->streamVolume(stream);
807 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800808 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700809 }
810
811 return volume;
812}
813
Glenn Kastenfff6d712012-01-12 16:38:12 -0800814bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700815{
Glenn Kasten263709e2012-01-06 08:40:01 -0800816 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700817 return true;
818 }
819
Glenn Kasten6637baa2012-01-09 09:40:36 -0800820 AutoMutex lock(mLock);
821 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700822}
823
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800824status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700825{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800826 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700827 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
828 // check calling permissions
829 if (!settingsAllowed()) {
830 return PERMISSION_DENIED;
831 }
832
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833 // ioHandle == 0 means the parameters are global to the audio hardware interface
834 if (ioHandle == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700835 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800836 {
837 AutoMutex lock(mHardwareLock);
838 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700839 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
840 audio_hw_device_t *dev = mAudioHwDevs[i];
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800841 status_t result = dev->set_parameters(dev, keyValuePairs.string());
Dima Zavin799a70e2011-04-18 16:57:27 -0700842 final_result = result ?: final_result;
843 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700844 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800845 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700846 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
847 AudioParameter param = AudioParameter(keyValuePairs);
848 String8 value;
849 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
850 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700851 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
852 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700853 for (size_t i = 0; i < mRecordThreads.size(); i++) {
854 sp<RecordThread> thread = mRecordThreads.valueAt(i);
855 RecordThread::RecordTrack *track = thread->track();
856 if (track != NULL) {
857 audio_devices_t device = (audio_devices_t)(
858 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700859 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700860 thread->setEffectSuspended(FX_IID_AEC,
861 suspend,
862 track->sessionId());
863 thread->setEffectSuspended(FX_IID_NS,
864 suspend,
865 track->sessionId());
866 }
867 }
Eric Laurentbee53372011-08-29 12:42:48 -0700868 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700869 }
870 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700871 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700872 }
873
874 // hold a strong ref on thread in case closeOutput() or closeInput() is called
875 // and the thread is exited once the lock is released
876 sp<ThreadBase> thread;
877 {
878 Mutex::Autolock _l(mLock);
879 thread = checkPlaybackThread_l(ioHandle);
880 if (thread == NULL) {
881 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800882 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700883 // indicate output device change to all input threads for pre processing
884 AudioParameter param = AudioParameter(keyValuePairs);
885 int value;
886 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
887 for (size_t i = 0; i < mRecordThreads.size(); i++) {
888 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
889 }
890 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700891 }
892 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800893 if (thread != 0) {
894 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700895 }
896 return BAD_VALUE;
897}
898
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800899String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700900{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800901// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700902// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
903
904 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700905 String8 out_s8;
906
Dima Zavin799a70e2011-04-18 16:57:27 -0700907 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800908 char *s;
909 {
910 AutoMutex lock(mHardwareLock);
911 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700912 audio_hw_device_t *dev = mAudioHwDevs[i];
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800913 s = dev->get_parameters(dev, keys.string());
914 mHardwareStatus = AUDIO_HW_IDLE;
915 }
John Grossmanef7740b2012-02-09 11:28:36 -0800916 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700917 free(s);
918 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700919 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700920 }
921
922 Mutex::Autolock _l(mLock);
923
924 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
925 if (playbackThread != NULL) {
926 return playbackThread->getParameters(keys);
927 }
928 RecordThread *recordThread = checkRecordThread_l(ioHandle);
929 if (recordThread != NULL) {
930 return recordThread->getParameters(keys);
931 }
932 return String8("");
933}
934
Glenn Kastenf587ba52012-01-26 16:25:10 -0800935size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700936{
Eric Laurenta1884f92011-08-23 08:25:03 -0700937 status_t ret = initCheck();
938 if (ret != NO_ERROR) {
939 return 0;
940 }
941
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800942 AutoMutex lock(mHardwareLock);
943 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
944 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
945 mHardwareStatus = AUDIO_HW_IDLE;
946 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700947}
948
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800949unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700950{
951 if (ioHandle == 0) {
952 return 0;
953 }
954
955 Mutex::Autolock _l(mLock);
956
957 RecordThread *recordThread = checkRecordThread_l(ioHandle);
958 if (recordThread != NULL) {
959 return recordThread->getInputFramesLost();
960 }
961 return 0;
962}
963
964status_t AudioFlinger::setVoiceVolume(float value)
965{
Eric Laurenta1884f92011-08-23 08:25:03 -0700966 status_t ret = initCheck();
967 if (ret != NO_ERROR) {
968 return ret;
969 }
970
Mathias Agopian65ab4712010-07-14 17:59:35 -0700971 // check calling permissions
972 if (!settingsAllowed()) {
973 return PERMISSION_DENIED;
974 }
975
976 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800977 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700978 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700979 mHardwareStatus = AUDIO_HW_IDLE;
980
981 return ret;
982}
983
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800984status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
985 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700986{
987 status_t status;
988
989 Mutex::Autolock _l(mLock);
990
991 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
992 if (playbackThread != NULL) {
993 return playbackThread->getRenderPosition(halFrames, dspFrames);
994 }
995
996 return BAD_VALUE;
997}
998
999void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1000{
1001
1002 Mutex::Autolock _l(mLock);
1003
Glenn Kastenbb001922012-02-03 11:10:26 -08001004 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001005 if (mNotificationClients.indexOfKey(pid) < 0) {
1006 sp<NotificationClient> notificationClient = new NotificationClient(this,
1007 client,
1008 pid);
Steve Block3856b092011-10-20 11:56:00 +01001009 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001010
1011 mNotificationClients.add(pid, notificationClient);
1012
1013 sp<IBinder> binder = client->asBinder();
1014 binder->linkToDeath(notificationClient);
1015
1016 // the config change is always sent from playback or record threads to avoid deadlock
1017 // with AudioSystem::gLock
1018 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1019 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1020 }
1021
1022 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1023 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1024 }
1025 }
1026}
1027
1028void AudioFlinger::removeNotificationClient(pid_t pid)
1029{
1030 Mutex::Autolock _l(mLock);
1031
Glenn Kastena3b09252012-01-20 09:19:01 -08001032 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001033
Steve Block3856b092011-10-20 11:56:00 +01001034 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001035 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001036 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001037 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001038 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001039 ALOGV(" pid %d @ %d", ref->mPid, i);
1040 if (ref->mPid == pid) {
1041 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001042 mAudioSessionRefs.removeAt(i);
1043 delete ref;
1044 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001045 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001046 } else {
1047 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001048 }
1049 }
1050 if (removed) {
1051 purgeStaleEffects_l();
1052 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001053}
1054
1055// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001056void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001057{
1058 size_t size = mNotificationClients.size();
1059 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001060 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1061 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001062 }
1063}
1064
1065// removeClient_l() must be called with AudioFlinger::mLock held
1066void AudioFlinger::removeClient_l(pid_t pid)
1067{
Steve Block3856b092011-10-20 11:56:00 +01001068 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001069 mClients.removeItem(pid);
1070}
1071
1072
1073// ----------------------------------------------------------------------------
1074
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001075AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1076 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001077 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001078 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001079 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
1080 // mChannelMask
1081 mChannelCount(0),
1082 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1083 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001084 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001085 mDevice(device),
1086 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001087{
1088}
1089
1090AudioFlinger::ThreadBase::~ThreadBase()
1091{
1092 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001093 // do not lock the mutex in destructor
1094 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001095 if (mPowerManager != 0) {
1096 sp<IBinder> binder = mPowerManager->asBinder();
1097 binder->unlinkToDeath(mDeathRecipient);
1098 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001099}
1100
1101void AudioFlinger::ThreadBase::exit()
1102{
Steve Block3856b092011-10-20 11:56:00 +01001103 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001104 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001105 // This lock prevents the following race in thread (uniprocessor for illustration):
1106 // if (!exitPending()) {
1107 // // context switch from here to exit()
1108 // // exit() calls requestExit(), what exitPending() observes
1109 // // exit() calls signal(), which is dropped since no waiters
1110 // // context switch back from exit() to here
1111 // mWaitWorkCV.wait(...);
1112 // // now thread is hung
1113 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001114 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001115 requestExit();
1116 mWaitWorkCV.signal();
1117 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001118 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1119 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001120 requestExitAndWait();
1121}
1122
Mathias Agopian65ab4712010-07-14 17:59:35 -07001123status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1124{
1125 status_t status;
1126
Steve Block3856b092011-10-20 11:56:00 +01001127 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001128 Mutex::Autolock _l(mLock);
1129
1130 mNewParameters.add(keyValuePairs);
1131 mWaitWorkCV.signal();
1132 // wait condition with timeout in case the thread loop has exited
1133 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001134 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001135 status = mParamStatus;
1136 mWaitWorkCV.signal();
1137 } else {
1138 status = TIMED_OUT;
1139 }
1140 return status;
1141}
1142
1143void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1144{
1145 Mutex::Autolock _l(mLock);
1146 sendConfigEvent_l(event, param);
1147}
1148
1149// sendConfigEvent_l() must be called with ThreadBase::mLock held
1150void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1151{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001152 ConfigEvent configEvent;
1153 configEvent.mEvent = event;
1154 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001155 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001156 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001157 mWaitWorkCV.signal();
1158}
1159
1160void AudioFlinger::ThreadBase::processConfigEvents()
1161{
1162 mLock.lock();
1163 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001164 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001165 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001166 mConfigEvents.removeAt(0);
1167 // release mLock before locking AudioFlinger mLock: lock order is always
1168 // AudioFlinger then ThreadBase to avoid cross deadlock
1169 mLock.unlock();
1170 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001171 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001172 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001173 mLock.lock();
1174 }
1175 mLock.unlock();
1176}
1177
1178status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1179{
1180 const size_t SIZE = 256;
1181 char buffer[SIZE];
1182 String8 result;
1183
1184 bool locked = tryLock(mLock);
1185 if (!locked) {
1186 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1187 write(fd, buffer, strlen(buffer));
1188 }
1189
1190 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1191 result.append(buffer);
1192 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1193 result.append(buffer);
1194 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1195 result.append(buffer);
1196 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1197 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001198 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1199 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001200 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1201 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001202 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001203 result.append(buffer);
1204
1205 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1206 result.append(buffer);
1207 result.append(" Index Command");
1208 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1209 snprintf(buffer, SIZE, "\n %02d ", i);
1210 result.append(buffer);
1211 result.append(mNewParameters[i]);
1212 }
1213
1214 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1215 result.append(buffer);
1216 snprintf(buffer, SIZE, " Index event param\n");
1217 result.append(buffer);
1218 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001219 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001220 result.append(buffer);
1221 }
1222 result.append("\n");
1223
1224 write(fd, result.string(), result.size());
1225
1226 if (locked) {
1227 mLock.unlock();
1228 }
1229 return NO_ERROR;
1230}
1231
Eric Laurent1d2bff02011-07-24 17:49:51 -07001232status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1233{
1234 const size_t SIZE = 256;
1235 char buffer[SIZE];
1236 String8 result;
1237
1238 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1239 write(fd, buffer, strlen(buffer));
1240
1241 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1242 sp<EffectChain> chain = mEffectChains[i];
1243 if (chain != 0) {
1244 chain->dump(fd, args);
1245 }
1246 }
1247 return NO_ERROR;
1248}
1249
Eric Laurentfeb0db62011-07-22 09:04:31 -07001250void AudioFlinger::ThreadBase::acquireWakeLock()
1251{
1252 Mutex::Autolock _l(mLock);
1253 acquireWakeLock_l();
1254}
1255
1256void AudioFlinger::ThreadBase::acquireWakeLock_l()
1257{
1258 if (mPowerManager == 0) {
1259 // use checkService() to avoid blocking if power service is not up yet
1260 sp<IBinder> binder =
1261 defaultServiceManager()->checkService(String16("power"));
1262 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001263 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001264 } else {
1265 mPowerManager = interface_cast<IPowerManager>(binder);
1266 binder->linkToDeath(mDeathRecipient);
1267 }
1268 }
1269 if (mPowerManager != 0) {
1270 sp<IBinder> binder = new BBinder();
1271 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1272 binder,
1273 String16(mName));
1274 if (status == NO_ERROR) {
1275 mWakeLockToken = binder;
1276 }
Steve Block3856b092011-10-20 11:56:00 +01001277 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001278 }
1279}
1280
1281void AudioFlinger::ThreadBase::releaseWakeLock()
1282{
1283 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001284 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001285}
1286
1287void AudioFlinger::ThreadBase::releaseWakeLock_l()
1288{
1289 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001290 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001291 if (mPowerManager != 0) {
1292 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1293 }
1294 mWakeLockToken.clear();
1295 }
1296}
1297
1298void AudioFlinger::ThreadBase::clearPowerManager()
1299{
1300 Mutex::Autolock _l(mLock);
1301 releaseWakeLock_l();
1302 mPowerManager.clear();
1303}
1304
1305void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1306{
1307 sp<ThreadBase> thread = mThread.promote();
1308 if (thread != 0) {
1309 thread->clearPowerManager();
1310 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001311 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001312}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001313
Eric Laurent59255e42011-07-27 19:49:51 -07001314void AudioFlinger::ThreadBase::setEffectSuspended(
1315 const effect_uuid_t *type, bool suspend, int sessionId)
1316{
1317 Mutex::Autolock _l(mLock);
1318 setEffectSuspended_l(type, suspend, sessionId);
1319}
1320
1321void AudioFlinger::ThreadBase::setEffectSuspended_l(
1322 const effect_uuid_t *type, bool suspend, int sessionId)
1323{
Glenn Kasten090f0192012-01-30 13:00:02 -08001324 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001325 if (chain != 0) {
1326 if (type != NULL) {
1327 chain->setEffectSuspended_l(type, suspend);
1328 } else {
1329 chain->setEffectSuspendedAll_l(suspend);
1330 }
1331 }
1332
1333 updateSuspendedSessions_l(type, suspend, sessionId);
1334}
1335
1336void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1337{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001338 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001339 if (index < 0) {
1340 return;
1341 }
1342
1343 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1344 mSuspendedSessions.editValueAt(index);
1345
1346 for (size_t i = 0; i < sessionEffects.size(); i++) {
1347 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1348 for (int j = 0; j < desc->mRefCount; j++) {
1349 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1350 chain->setEffectSuspendedAll_l(true);
1351 } else {
Steve Block3856b092011-10-20 11:56:00 +01001352 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001353 desc->mType.timeLow);
1354 chain->setEffectSuspended_l(&desc->mType, true);
1355 }
1356 }
1357 }
1358}
1359
Eric Laurent59255e42011-07-27 19:49:51 -07001360void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1361 bool suspend,
1362 int sessionId)
1363{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001364 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001365
1366 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1367
1368 if (suspend) {
1369 if (index >= 0) {
1370 sessionEffects = mSuspendedSessions.editValueAt(index);
1371 } else {
1372 mSuspendedSessions.add(sessionId, sessionEffects);
1373 }
1374 } else {
1375 if (index < 0) {
1376 return;
1377 }
1378 sessionEffects = mSuspendedSessions.editValueAt(index);
1379 }
1380
1381
1382 int key = EffectChain::kKeyForSuspendAll;
1383 if (type != NULL) {
1384 key = type->timeLow;
1385 }
1386 index = sessionEffects.indexOfKey(key);
1387
1388 sp <SuspendedSessionDesc> desc;
1389 if (suspend) {
1390 if (index >= 0) {
1391 desc = sessionEffects.valueAt(index);
1392 } else {
1393 desc = new SuspendedSessionDesc();
1394 if (type != NULL) {
1395 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1396 }
1397 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001398 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001399 }
1400 desc->mRefCount++;
1401 } else {
1402 if (index < 0) {
1403 return;
1404 }
1405 desc = sessionEffects.valueAt(index);
1406 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001407 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001408 sessionEffects.removeItemsAt(index);
1409 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001410 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001411 sessionId);
1412 mSuspendedSessions.removeItem(sessionId);
1413 }
1414 }
1415 }
1416 if (!sessionEffects.isEmpty()) {
1417 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1418 }
1419}
1420
1421void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1422 bool enabled,
1423 int sessionId)
1424{
1425 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001426 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1427}
Eric Laurent59255e42011-07-27 19:49:51 -07001428
Eric Laurenta85a74a2011-10-19 11:44:54 -07001429void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1430 bool enabled,
1431 int sessionId)
1432{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001433 if (mType != RECORD) {
1434 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1435 // another session. This gives the priority to well behaved effect control panels
1436 // and applications not using global effects.
1437 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1438 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1439 }
1440 }
Eric Laurent59255e42011-07-27 19:49:51 -07001441
1442 sp<EffectChain> chain = getEffectChain_l(sessionId);
1443 if (chain != 0) {
1444 chain->checkSuspendOnEffectEnabled(effect, enabled);
1445 }
1446}
1447
Mathias Agopian65ab4712010-07-14 17:59:35 -07001448// ----------------------------------------------------------------------------
1449
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001450AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1451 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001452 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001453 uint32_t device,
1454 type_t type)
1455 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001456 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1457 // Assumes constructor is called by AudioFlinger with it's mLock held,
1458 // but it would be safer to explicitly pass initial masterMute as parameter
1459 mMasterMute(audioFlinger->masterMute_l()),
1460 // mStreamTypes[] initialized in constructor body
1461 mOutput(output),
1462 // Assumes constructor is called by AudioFlinger with it's mLock held,
1463 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001464 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001465 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1466 // mMixerStatus
Glenn Kasten66fcab92012-02-24 14:59:21 -08001467 mPrevMixerStatus(MIXER_IDLE),
1468 standbyDelay(AudioFlinger::mStandbyTimeInNsecs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001469{
Glenn Kasten480b4682012-02-28 12:30:08 -08001470 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001471
Mathias Agopian65ab4712010-07-14 17:59:35 -07001472 readOutputParameters();
1473
Glenn Kasten263709e2012-01-06 08:40:01 -08001474 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001475 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1476 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1477 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001478 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1479 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001480 // initialized by stream_type_t default constructor
1481 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001482 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001483 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1484 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001485}
1486
1487AudioFlinger::PlaybackThread::~PlaybackThread()
1488{
1489 delete [] mMixBuffer;
1490}
1491
1492status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1493{
1494 dumpInternals(fd, args);
1495 dumpTracks(fd, args);
1496 dumpEffectChains(fd, args);
1497 return NO_ERROR;
1498}
1499
1500status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1501{
1502 const size_t SIZE = 256;
1503 char buffer[SIZE];
1504 String8 result;
1505
1506 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1507 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001508 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 -07001509 for (size_t i = 0; i < mTracks.size(); ++i) {
1510 sp<Track> track = mTracks[i];
1511 if (track != 0) {
1512 track->dump(buffer, SIZE);
1513 result.append(buffer);
1514 }
1515 }
1516
1517 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1518 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001519 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 -07001520 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001521 sp<Track> track = mActiveTracks[i].promote();
1522 if (track != 0) {
1523 track->dump(buffer, SIZE);
1524 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001525 }
1526 }
1527 write(fd, result.string(), result.size());
1528 return NO_ERROR;
1529}
1530
Mathias Agopian65ab4712010-07-14 17:59:35 -07001531status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1532{
1533 const size_t SIZE = 256;
1534 char buffer[SIZE];
1535 String8 result;
1536
1537 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1538 result.append(buffer);
1539 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1540 result.append(buffer);
1541 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1542 result.append(buffer);
1543 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1544 result.append(buffer);
1545 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1546 result.append(buffer);
1547 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1548 result.append(buffer);
1549 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1550 result.append(buffer);
1551 write(fd, result.string(), result.size());
1552
1553 dumpBase(fd, args);
1554
1555 return NO_ERROR;
1556}
1557
1558// Thread virtuals
1559status_t AudioFlinger::PlaybackThread::readyToRun()
1560{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001561 status_t status = initCheck();
1562 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001563 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001564 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001565 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001566 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001567 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568}
1569
1570void AudioFlinger::PlaybackThread::onFirstRef()
1571{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001572 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001573}
1574
1575// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1576sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1577 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001578 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001579 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001580 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001581 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001582 int frameCount,
1583 const sp<IMemory>& sharedBuffer,
1584 int sessionId,
John Grossman4ff14ba2012-02-08 16:37:41 -08001585 bool isTimed,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001586 status_t *status)
1587{
1588 sp<Track> track;
1589 status_t lStatus;
1590
1591 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001592 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1593 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001594 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001595 "for output %p with format %d",
1596 sampleRate, format, channelMask, mOutput, mFormat);
1597 lStatus = BAD_VALUE;
1598 goto Exit;
1599 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600 }
1601 } else {
1602 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1603 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001604 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001605 lStatus = BAD_VALUE;
1606 goto Exit;
1607 }
1608 }
1609
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001610 lStatus = initCheck();
1611 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001612 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001613 goto Exit;
1614 }
1615
1616 { // scope for mLock
1617 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001618
1619 // all tracks in same audio session must share the same routing strategy otherwise
1620 // conflicts will happen when tracks are moved from one output to another by audio policy
1621 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001622 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001623 for (size_t i = 0; i < mTracks.size(); ++i) {
1624 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001625 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001626 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001627 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001628 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001629 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001630 lStatus = BAD_VALUE;
1631 goto Exit;
1632 }
1633 }
1634 }
1635
John Grossman4ff14ba2012-02-08 16:37:41 -08001636 if (!isTimed) {
1637 track = new Track(this, client, streamType, sampleRate, format,
1638 channelMask, frameCount, sharedBuffer, sessionId);
1639 } else {
1640 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1641 channelMask, frameCount, sharedBuffer, sessionId);
1642 }
1643 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001644 lStatus = NO_MEMORY;
1645 goto Exit;
1646 }
1647 mTracks.add(track);
1648
1649 sp<EffectChain> chain = getEffectChain_l(sessionId);
1650 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001651 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001652 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001653 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001654 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001655 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001656
1657 // invalidate track immediately if the stream type was moved to another thread since
1658 // createTrack() was called by the client process.
1659 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001660 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001661 this, streamType);
1662 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1663 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001664 }
1665 lStatus = NO_ERROR;
1666
1667Exit:
1668 if(status) {
1669 *status = lStatus;
1670 }
1671 return track;
1672}
1673
1674uint32_t AudioFlinger::PlaybackThread::latency() const
1675{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001676 Mutex::Autolock _l(mLock);
1677 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001678 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001679 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001680 return 0;
1681 }
1682}
1683
Glenn Kasten6637baa2012-01-09 09:40:36 -08001684void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001686 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001687 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001688}
1689
Glenn Kasten6637baa2012-01-09 09:40:36 -08001690void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001691{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001692 Mutex::Autolock _l(mLock);
1693 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001694}
1695
Glenn Kasten6637baa2012-01-09 09:40:36 -08001696void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001697{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001698 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001699 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001700}
1701
Glenn Kasten6637baa2012-01-09 09:40:36 -08001702void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001703{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001704 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001705 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001706}
1707
Glenn Kastenfff6d712012-01-12 16:38:12 -08001708float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001709{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001710 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001711 return mStreamTypes[stream].volume;
1712}
1713
Mathias Agopian65ab4712010-07-14 17:59:35 -07001714// addTrack_l() must be called with ThreadBase::mLock held
1715status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1716{
1717 status_t status = ALREADY_EXISTS;
1718
1719 // set retry count for buffer fill
1720 track->mRetryCount = kMaxTrackStartupRetries;
1721 if (mActiveTracks.indexOf(track) < 0) {
1722 // the track is newly added, make sure it fills up all its
1723 // buffers before playing. This is to ensure the client will
1724 // effectively get the latency it requested.
1725 track->mFillingUpStatus = Track::FS_FILLING;
1726 track->mResetDone = false;
1727 mActiveTracks.add(track);
1728 if (track->mainBuffer() != mMixBuffer) {
1729 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1730 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001731 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001732 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001733 }
1734 }
1735
1736 status = NO_ERROR;
1737 }
1738
Steve Block3856b092011-10-20 11:56:00 +01001739 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001740 mWaitWorkCV.broadcast();
1741
1742 return status;
1743}
1744
1745// destroyTrack_l() must be called with ThreadBase::mLock held
1746void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1747{
1748 track->mState = TrackBase::TERMINATED;
1749 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001750 removeTrack_l(track);
1751 }
1752}
1753
1754void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1755{
1756 mTracks.remove(track);
1757 deleteTrackName_l(track->name());
1758 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1759 if (chain != 0) {
1760 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001761 }
1762}
1763
1764String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1765{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001766 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001767 char *s;
1768
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001769 Mutex::Autolock _l(mLock);
1770 if (initCheck() != NO_ERROR) {
1771 return out_s8;
1772 }
1773
Dima Zavin799a70e2011-04-18 16:57:27 -07001774 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001775 out_s8 = String8(s);
1776 free(s);
1777 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001778}
1779
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001780// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001781void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1782 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001783 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001784
Steve Block3856b092011-10-20 11:56:00 +01001785 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001786
1787 switch (event) {
1788 case AudioSystem::OUTPUT_OPENED:
1789 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001790 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001791 desc.samplingRate = mSampleRate;
1792 desc.format = mFormat;
1793 desc.frameCount = mFrameCount;
1794 desc.latency = latency();
1795 param2 = &desc;
1796 break;
1797
1798 case AudioSystem::STREAM_CONFIG_CHANGED:
1799 param2 = &param;
1800 case AudioSystem::OUTPUT_CLOSED:
1801 default:
1802 break;
1803 }
1804 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1805}
1806
1807void AudioFlinger::PlaybackThread::readOutputParameters()
1808{
Dima Zavin799a70e2011-04-18 16:57:27 -07001809 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001810 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1811 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001812 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001813 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001814 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001815
1816 // FIXME - Current mixer implementation only supports stereo output: Always
1817 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001818 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001819 mMixBuffer = new int16_t[mFrameCount * 2];
1820 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1821
Eric Laurentde070132010-07-13 04:45:46 -07001822 // force reconfiguration of effect chains and engines to take new buffer size and audio
1823 // parameters into account
1824 // Note that mLock is not held when readOutputParameters() is called from the constructor
1825 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1826 // matter.
1827 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1828 Vector< sp<EffectChain> > effectChains = mEffectChains;
1829 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001830 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001831 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001832}
1833
1834status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1835{
Glenn Kastena0d68332012-01-27 16:47:15 -08001836 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001837 return BAD_VALUE;
1838 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001839 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001840 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001841 return INVALID_OPERATION;
1842 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001843 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001844
Dima Zavin799a70e2011-04-18 16:57:27 -07001845 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001846}
1847
Eric Laurent39e94f82010-07-28 01:32:47 -07001848uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001849{
1850 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001851 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001852 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001853 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001854 }
1855
1856 for (size_t i = 0; i < mTracks.size(); ++i) {
1857 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001858 if (sessionId == track->sessionId() &&
1859 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001860 result |= TRACK_SESSION;
1861 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001862 }
1863 }
1864
Eric Laurent39e94f82010-07-28 01:32:47 -07001865 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001866}
1867
Eric Laurentde070132010-07-13 04:45:46 -07001868uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1869{
Dima Zavinfce7a472011-04-19 22:30:36 -07001870 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001871 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001872 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1873 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001874 }
1875 for (size_t i = 0; i < mTracks.size(); i++) {
1876 sp<Track> track = mTracks[i];
1877 if (sessionId == track->sessionId() &&
1878 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001879 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07001880 }
1881 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001882 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001883}
1884
Mathias Agopian65ab4712010-07-14 17:59:35 -07001885
Glenn Kastenaed850d2012-01-26 09:46:34 -08001886AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001887{
1888 Mutex::Autolock _l(mLock);
1889 return mOutput;
1890}
1891
1892AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1893{
1894 Mutex::Autolock _l(mLock);
1895 AudioStreamOut *output = mOutput;
1896 mOutput = NULL;
1897 return output;
1898}
1899
1900// this method must always be called either with ThreadBase mLock held or inside the thread loop
1901audio_stream_t* AudioFlinger::PlaybackThread::stream()
1902{
1903 if (mOutput == NULL) {
1904 return NULL;
1905 }
1906 return &mOutput->stream->common;
1907}
1908
Eric Laurent162b40b2011-12-05 09:47:19 -08001909uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1910{
1911 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1912 // decoding and transfer time. So sleeping for half of the latency would likely cause
1913 // underruns
1914 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1915 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1916 } else {
1917 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1918 }
1919}
1920
Mathias Agopian65ab4712010-07-14 17:59:35 -07001921// ----------------------------------------------------------------------------
1922
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001923AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001924 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten000f0e32012-03-01 17:10:56 -08001925 : PlaybackThread(audioFlinger, output, id, device, type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001926{
Glenn Kasten000f0e32012-03-01 17:10:56 -08001927 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001928 // FIXME - Current mixer implementation only supports stereo output
1929 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001930 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001931 }
1932}
1933
1934AudioFlinger::MixerThread::~MixerThread()
1935{
1936 delete mAudioMixer;
1937}
1938
Glenn Kasten83efdd02012-02-24 07:21:32 -08001939class CpuStats {
1940public:
1941 void sample();
1942#ifdef DEBUG_CPU_USAGE
1943private:
1944 ThreadCpuUsage mCpu;
1945#endif
1946};
1947
1948void CpuStats::sample() {
1949#ifdef DEBUG_CPU_USAGE
1950 const CentralTendencyStatistics& stats = mCpu.statistics();
1951 mCpu.sampleAndEnable();
1952 unsigned n = stats.n();
1953 // mCpu.elapsed() is expensive, so don't call it every loop
1954 if ((n & 127) == 1) {
1955 long long elapsed = mCpu.elapsed();
1956 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1957 double perLoop = elapsed / (double) n;
1958 double perLoop100 = perLoop * 0.01;
1959 double mean = stats.mean();
1960 double stddev = stats.stddev();
1961 double minimum = stats.minimum();
1962 double maximum = stats.maximum();
1963 mCpu.resetStatistics();
1964 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",
1965 elapsed * .000000001, n, perLoop * .000001,
1966 mean * .001,
1967 stddev * .001,
1968 minimum * .001,
1969 maximum * .001,
1970 mean / perLoop100,
1971 stddev / perLoop100,
1972 minimum / perLoop100,
1973 maximum / perLoop100);
1974 }
1975 }
1976#endif
1977};
1978
Glenn Kasten37d825e2012-02-24 07:21:48 -08001979void AudioFlinger::PlaybackThread::checkSilentMode_l()
1980{
1981 if (!mMasterMute) {
1982 char value[PROPERTY_VALUE_MAX];
1983 if (property_get("ro.audio.silent", value, "0") > 0) {
1984 char *endptr;
1985 unsigned long ul = strtoul(value, &endptr, 0);
1986 if (*endptr == '\0' && ul != 0) {
1987 ALOGD("Silence is golden");
1988 // The setprop command will not allow a property to be changed after
1989 // the first time it is set, so we don't have to worry about un-muting.
1990 setMasterMute_l(true);
1991 }
1992 }
1993 }
1994}
1995
Glenn Kasten000f0e32012-03-01 17:10:56 -08001996bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001997{
1998 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08001999
Glenn Kasten000f0e32012-03-01 17:10:56 -08002000 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002001
2002 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002003 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002004if (mType == MIXER) {
2005 longStandbyExit = false;
2006}
Glenn Kasten688a6402012-02-29 07:57:06 -08002007
Glenn Kasten000f0e32012-03-01 17:10:56 -08002008 // DUPLICATING
2009 // FIXME could this be made local to while loop?
2010 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002011
Glenn Kasten66fcab92012-02-24 14:59:21 -08002012 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002013 sleepTime = idleSleepTime;
2014
2015if (mType == MIXER) {
2016 sleepTimeShift = 0;
2017}
2018
2019 // MIXER
Glenn Kasten83efdd02012-02-24 07:21:32 -08002020 CpuStats cpuStats;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002021
Eric Laurentfeb0db62011-07-22 09:04:31 -07002022 acquireWakeLock();
2023
Mathias Agopian65ab4712010-07-14 17:59:35 -07002024 while (!exitPending())
2025 {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002026if (mType == MIXER) {
Glenn Kasten83efdd02012-02-24 07:21:32 -08002027 cpuStats.sample();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002028}
Glenn Kasten688a6402012-02-29 07:57:06 -08002029
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002030 Vector< sp<EffectChain> > effectChains;
2031
Mathias Agopian65ab4712010-07-14 17:59:35 -07002032 processConfigEvents();
2033
Glenn Kastenfec279f2012-03-08 07:47:15 -08002034 mMixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002035 { // scope for mLock
2036
2037 Mutex::Autolock _l(mLock);
2038
2039 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002040 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002041 }
2042
Glenn Kastenfa26a852012-03-06 11:28:04 -08002043 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002044
Mathias Agopian65ab4712010-07-14 17:59:35 -07002045 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002046 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002047 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002048 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002049
2050 threadLoop_standby();
2051
Mathias Agopian65ab4712010-07-14 17:59:35 -07002052 mStandby = true;
2053 mBytesWritten = 0;
2054 }
2055
Glenn Kasten3e074702012-02-28 18:40:35 -08002056 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002057 // we're about to wait, flush the binder command buffer
2058 IPCThreadState::self()->flushCommands();
2059
Glenn Kastenfa26a852012-03-06 11:28:04 -08002060 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002061
Mathias Agopian65ab4712010-07-14 17:59:35 -07002062 if (exitPending()) break;
2063
Eric Laurentfeb0db62011-07-22 09:04:31 -07002064 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002065 // wait until we have something to do...
Glenn Kastenc0b52832012-02-24 11:18:09 -08002066 ALOGV("Thread %p type %d TID %d going to sleep", this, mType, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002067 mWaitWorkCV.wait(mLock);
Glenn Kastenc0b52832012-02-24 11:18:09 -08002068 ALOGV("Thread %p type %d TID %d waking up", this, mType, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002069 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002070
Eric Laurent27741442012-01-17 19:20:12 -08002071 mPrevMixerStatus = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002072
Glenn Kasten37d825e2012-02-24 07:21:48 -08002073 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002074
Glenn Kasten000f0e32012-03-01 17:10:56 -08002075 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002076 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002077 if (mType == MIXER) {
2078 sleepTimeShift = 0;
2079 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002080
Mathias Agopian65ab4712010-07-14 17:59:35 -07002081 continue;
2082 }
2083 }
2084
Glenn Kastenfec279f2012-03-08 07:47:15 -08002085 mixer_state newMixerStatus = prepareTracks_l(&tracksToRemove);
2086 // Shift in the new status; this could be a queue if it's
2087 // useful to filter the mixer status over several cycles.
2088 mPrevMixerStatus = mMixerStatus;
2089 mMixerStatus = newMixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002090
2091 // prevent any changes in effect chain list and in each effect chain
2092 // during mixing and effect process as the audio buffers could be deleted
2093 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002094 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002095 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002096
Glenn Kastenfec279f2012-03-08 07:47:15 -08002097 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002098 threadLoop_mix();
2099 } else {
2100 threadLoop_sleepTime();
2101 }
2102
2103 if (mSuspended > 0) {
2104 sleepTime = suspendSleepTimeUs();
2105 }
2106
2107 // only process effects if we're going to write
2108 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002109 for (size_t i = 0; i < effectChains.size(); i ++) {
2110 effectChains[i]->process_l();
2111 }
2112 }
2113
2114 // enable changes in effect chain
2115 unlockEffectChains(effectChains);
2116
2117 // sleepTime == 0 means we must write to audio hardware
2118 if (sleepTime == 0) {
2119
2120 threadLoop_write();
2121
2122if (mType == MIXER) {
2123 // write blocked detection
2124 nsecs_t now = systemTime();
2125 nsecs_t delta = now - mLastWriteTime;
2126 if (!mStandby && delta > maxPeriod) {
2127 mNumDelayedWrites++;
2128 if ((now - lastWarning) > kWarningThrottleNs) {
2129 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2130 ns2ms(delta), mNumDelayedWrites, this);
2131 lastWarning = now;
2132 }
2133 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2134 // a different threshold. Or completely removed for what it is worth anyway...
2135 if (mStandby) {
2136 longStandbyExit = true;
2137 }
2138 }
2139}
2140
2141 mStandby = false;
2142 } else {
2143 usleep(sleepTime);
2144 }
2145
2146 // finally let go of removed track(s), without the lock held
2147 // since we can't guarantee the destructors won't acquire that
2148 // same lock.
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002149 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002150
Glenn Kastenfa26a852012-03-06 11:28:04 -08002151 // FIXME I don't understand the need for this here;
2152 // it was in the original code but maybe the
2153 // assignment in saveOutputTracks() makes this unnecessary?
2154 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002155
2156 // Effect chains will be actually deleted here if they were removed from
2157 // mEffectChains list during mixing or effects processing
2158 effectChains.clear();
2159
2160 // FIXME Note that the above .clear() is no longer necessary since effectChains
2161 // is now local to this block, but will keep it for now (at least until merge done).
2162 }
2163
2164if (mType == MIXER || mType == DIRECT) {
2165 // put output stream into standby mode
2166 if (!mStandby) {
2167 mOutput->stream->common.standby(&mOutput->stream->common);
2168 }
2169}
2170if (mType == DUPLICATING) {
2171 // for DuplicatingThread, standby mode is handled by the outputTracks
2172}
2173
2174 releaseWakeLock();
2175
2176 ALOGV("Thread %p type %d exiting", this, mType);
2177 return false;
2178}
2179
2180// shared by MIXER and DIRECT, overridden by DUPLICATING
2181void AudioFlinger::PlaybackThread::threadLoop_write()
2182{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002183 // FIXME rewrite to reduce number of system calls
2184 mLastWriteTime = systemTime();
2185 mInWrite = true;
2186 mBytesWritten += mixBufferSize;
2187 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2188 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2189 mNumWrites++;
2190 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002191}
2192
2193// shared by MIXER and DIRECT, overridden by DUPLICATING
2194void AudioFlinger::PlaybackThread::threadLoop_standby()
2195{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002196 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2197 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002198}
2199
2200void AudioFlinger::MixerThread::threadLoop_mix()
2201{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002202 // obtain the presentation timestamp of the next output buffer
2203 int64_t pts;
2204 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002205
Glenn Kasten952eeb22012-03-06 11:30:57 -08002206 if (NULL != mOutput->stream->get_next_write_timestamp) {
2207 status = mOutput->stream->get_next_write_timestamp(
2208 mOutput->stream, &pts);
2209 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002210
Glenn Kasten952eeb22012-03-06 11:30:57 -08002211 if (status != NO_ERROR) {
2212 pts = AudioBufferProvider::kInvalidPTS;
2213 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002214
Glenn Kasten952eeb22012-03-06 11:30:57 -08002215 // mix buffers...
2216 mAudioMixer->process(pts);
2217 // increase sleep time progressively when application underrun condition clears.
2218 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2219 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2220 // such that we would underrun the audio HAL.
2221 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2222 sleepTimeShift--;
2223 }
2224 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002225 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002226 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002227}
2228
2229void AudioFlinger::MixerThread::threadLoop_sleepTime()
2230{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002231 // If no tracks are ready, sleep once for the duration of an output
2232 // buffer size, then write 0s to the output
2233 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002234 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002235 sleepTime = activeSleepTime >> sleepTimeShift;
2236 if (sleepTime < kMinThreadSleepTimeUs) {
2237 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002238 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002239 // reduce sleep time in case of consecutive application underruns to avoid
2240 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2241 // duration we would end up writing less data than needed by the audio HAL if
2242 // the condition persists.
2243 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2244 sleepTimeShift++;
2245 }
2246 } else {
2247 sleepTime = idleSleepTime;
2248 }
2249 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002250 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002251 memset (mMixBuffer, 0, mixBufferSize);
2252 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002253 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002254 }
2255 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002256}
2257
2258// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002259AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002260 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002261{
2262
Glenn Kasten29c23c32012-01-26 13:37:52 -08002263 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002264 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002265 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002266 size_t mixedTracks = 0;
2267 size_t tracksWithEffect = 0;
2268
2269 float masterVolume = mMasterVolume;
2270 bool masterMute = mMasterMute;
2271
Eric Laurent571d49c2010-08-11 05:20:11 -07002272 if (masterMute) {
2273 masterVolume = 0;
2274 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002275 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002276 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002277 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002278 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002279 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002280 masterVolume = (float)((v + (1 << 23)) >> 24);
2281 chain.clear();
2282 }
2283
2284 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002285 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002286 if (t == 0) continue;
2287
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002288 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002289 Track* const track = t.get();
2290 audio_track_cblk_t* cblk = track->cblk();
2291
2292 // The first time a track is added we wait
2293 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002294 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002295 // make sure that we have enough frames to mix one full buffer.
2296 // enforce this condition only once to enable draining the buffer in case the client
2297 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002298 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002299 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002300 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002301 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002302 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002303 if (t->sampleRate() == (int)mSampleRate) {
2304 minFrames = mFrameCount;
2305 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002306 // +1 for rounding and +1 for additional sample needed for interpolation
2307 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2308 // add frames already consumed but not yet released by the resampler
2309 // because cblk->framesReady() will include these frames
2310 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2311 // the minimum track buffer size is normally twice the number of frames necessary
2312 // to fill one buffer and the resampler should not leave more than one buffer worth
2313 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002314 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002315 }
2316 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002317 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002318 !track->isPaused() && !track->isTerminated())
2319 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002320 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002321
2322 mixedTracks++;
2323
2324 // track->mainBuffer() != mMixBuffer means there is an effect chain
2325 // connected to the track
2326 chain.clear();
2327 if (track->mainBuffer() != mMixBuffer) {
2328 chain = getEffectChain_l(track->sessionId());
2329 // Delegate volume control to effect in track effect chain if needed
2330 if (chain != 0) {
2331 tracksWithEffect++;
2332 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002333 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002334 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002335 }
2336 }
2337
2338
2339 int param = AudioMixer::VOLUME;
2340 if (track->mFillingUpStatus == Track::FS_FILLED) {
2341 // no ramp for the first volume setting
2342 track->mFillingUpStatus = Track::FS_ACTIVE;
2343 if (track->mState == TrackBase::RESUMING) {
2344 track->mState = TrackBase::ACTIVE;
2345 param = AudioMixer::RAMP_VOLUME;
2346 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002347 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002348 } else if (cblk->server != 0) {
2349 // If the track is stopped before the first frame was mixed,
2350 // do not apply ramp
2351 param = AudioMixer::RAMP_VOLUME;
2352 }
2353
2354 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002355 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002356 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002357 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002358 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002359 if (track->isPausing()) {
2360 track->setPaused();
2361 }
2362 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002363
Mathias Agopian65ab4712010-07-14 17:59:35 -07002364 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002365 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002366 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002367 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002368 vl = vlr & 0xFFFF;
2369 vr = vlr >> 16;
2370 // track volumes come from shared memory, so can't be trusted and must be clamped
2371 if (vl > MAX_GAIN_INT) {
2372 ALOGV("Track left volume out of range: %04X", vl);
2373 vl = MAX_GAIN_INT;
2374 }
2375 if (vr > MAX_GAIN_INT) {
2376 ALOGV("Track right volume out of range: %04X", vr);
2377 vr = MAX_GAIN_INT;
2378 }
2379 // now apply the master volume and stream type volume
2380 vl = (uint32_t)(v * vl) << 12;
2381 vr = (uint32_t)(v * vr) << 12;
2382 // assuming master volume and stream type volume each go up to 1.0,
2383 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002384
Glenn Kasten05632a52012-01-03 14:22:33 -08002385 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2386 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002387 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002388 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002389 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002390 }
2391 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002392 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002393 // Delegate volume control to effect in track effect chain if needed
2394 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2395 // Do not ramp volume if volume is controlled by effect
2396 param = AudioMixer::VOLUME;
2397 track->mHasVolumeController = true;
2398 } else {
2399 // force no volume ramp when volume controller was just disabled or removed
2400 // from effect chain to avoid volume spike
2401 if (track->mHasVolumeController) {
2402 param = AudioMixer::VOLUME;
2403 }
2404 track->mHasVolumeController = false;
2405 }
2406
2407 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002408 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002409 vl = (vl + (1 << 11)) >> 12;
2410 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2411 vr = (vr + (1 << 11)) >> 12;
2412 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002413
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002414 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 -07002415
Mathias Agopian65ab4712010-07-14 17:59:35 -07002416 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002417 mAudioMixer->setBufferProvider(name, track);
2418 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002419
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002420 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2421 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2422 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002423 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002424 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002425 AudioMixer::TRACK,
2426 AudioMixer::FORMAT, (void *)track->format());
2427 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002428 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002429 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002430 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002431 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002432 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002433 AudioMixer::RESAMPLE,
2434 AudioMixer::SAMPLE_RATE,
2435 (void *)(cblk->sampleRate));
2436 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002437 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002438 AudioMixer::TRACK,
2439 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2440 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002441 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002442 AudioMixer::TRACK,
2443 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2444
2445 // reset retry count
2446 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002447 // If one track is ready, set the mixer ready if:
2448 // - the mixer was not ready during previous round OR
2449 // - no other track is not ready
2450 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2451 mixerStatus != MIXER_TRACKS_ENABLED) {
2452 mixerStatus = MIXER_TRACKS_READY;
2453 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002454 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002455 //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 -07002456 if (track->isStopped()) {
2457 track->reset();
2458 }
2459 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2460 // We have consumed all the buffers of this track.
2461 // Remove it from the list of active tracks.
2462 tracksToRemove->add(track);
2463 } else {
2464 // No buffers for this track. Give it a few chances to
2465 // fill a buffer, then remove it from active list.
2466 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002467 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002468 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002469 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002470 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002471 // If one track is not ready, mark the mixer also not ready if:
2472 // - the mixer was ready during previous round OR
2473 // - no other track is ready
2474 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2475 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002476 mixerStatus = MIXER_TRACKS_ENABLED;
2477 }
2478 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002479 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002480 }
2481 }
2482
2483 // remove all the tracks that need to be...
2484 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002485 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002486 for (size_t i=0 ; i<count ; i++) {
2487 const sp<Track>& track = tracksToRemove->itemAt(i);
2488 mActiveTracks.remove(track);
2489 if (track->mainBuffer() != mMixBuffer) {
2490 chain = getEffectChain_l(track->sessionId());
2491 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002492 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002493 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002494 }
2495 }
2496 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002497 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002498 }
2499 }
2500 }
2501
2502 // mix buffer must be cleared if all tracks are connected to an
2503 // effect chain as in this case the mixer will not write to
2504 // mix buffer and track effects will accumulate into it
2505 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2506 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2507 }
2508
2509 return mixerStatus;
2510}
2511
Glenn Kasten66fcab92012-02-24 14:59:21 -08002512/*
2513The derived values that are cached:
2514 - mixBufferSize from frame count * frame size
2515 - activeSleepTime from activeSleepTimeUs()
2516 - idleSleepTime from idleSleepTimeUs()
2517 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2518 - maxPeriod from frame count and sample rate (MIXER only)
2519
2520The parameters that affect these derived values are:
2521 - frame count
2522 - frame size
2523 - sample rate
2524 - device type: A2DP or not
2525 - device latency
2526 - format: PCM or not
2527 - active sleep time
2528 - idle sleep time
2529*/
2530
2531void AudioFlinger::PlaybackThread::cacheParameters_l()
2532{
2533 mixBufferSize = mFrameCount * mFrameSize;
2534 activeSleepTime = activeSleepTimeUs();
2535 idleSleepTime = idleSleepTimeUs();
2536}
2537
Glenn Kastenfff6d712012-01-12 16:38:12 -08002538void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002539{
Steve Block3856b092011-10-20 11:56:00 +01002540 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002541 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002542 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002543
Mathias Agopian65ab4712010-07-14 17:59:35 -07002544 size_t size = mTracks.size();
2545 for (size_t i = 0; i < size; i++) {
2546 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08002547 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002548 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002549 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002550 }
2551 }
2552}
2553
Glenn Kastenfff6d712012-01-12 16:38:12 -08002554void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002555{
Steve Block3856b092011-10-20 11:56:00 +01002556 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002557 this, streamType, valid);
2558 Mutex::Autolock _l(mLock);
2559
2560 mStreamTypes[streamType].valid = valid;
2561}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002562
2563// getTrackName_l() must be called with ThreadBase::mLock held
2564int AudioFlinger::MixerThread::getTrackName_l()
2565{
2566 return mAudioMixer->getTrackName();
2567}
2568
2569// deleteTrackName_l() must be called with ThreadBase::mLock held
2570void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2571{
Steve Block3856b092011-10-20 11:56:00 +01002572 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002573 mAudioMixer->deleteTrackName(name);
2574}
2575
2576// checkForNewParameters_l() must be called with ThreadBase::mLock held
2577bool AudioFlinger::MixerThread::checkForNewParameters_l()
2578{
2579 bool reconfig = false;
2580
2581 while (!mNewParameters.isEmpty()) {
2582 status_t status = NO_ERROR;
2583 String8 keyValuePair = mNewParameters[0];
2584 AudioParameter param = AudioParameter(keyValuePair);
2585 int value;
2586
2587 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2588 reconfig = true;
2589 }
2590 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002591 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002592 status = BAD_VALUE;
2593 } else {
2594 reconfig = true;
2595 }
2596 }
2597 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002598 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002599 status = BAD_VALUE;
2600 } else {
2601 reconfig = true;
2602 }
2603 }
2604 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2605 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002606 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002607 // if frame count is changed after track creation
2608 if (!mTracks.isEmpty()) {
2609 status = INVALID_OPERATION;
2610 } else {
2611 reconfig = true;
2612 }
2613 }
2614 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002615 // when changing the audio output device, call addBatteryData to notify
2616 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002617 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002618 uint32_t params = 0;
2619 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002620 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002621 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2622 }
2623
2624 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002625 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002626 // check if any other device (except speaker) is on
2627 if (value & deviceWithoutSpeaker ) {
2628 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2629 }
2630
2631 if (params != 0) {
2632 addBatteryData(params);
2633 }
2634 }
2635
Mathias Agopian65ab4712010-07-14 17:59:35 -07002636 // forward device change to effects that have requested to be
2637 // aware of attached audio device.
2638 mDevice = (uint32_t)value;
2639 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002640 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002641 }
2642 }
2643
2644 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002645 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002646 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002647 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002648 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002649 mStandby = true;
2650 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002651 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002652 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002653 }
2654 if (status == NO_ERROR && reconfig) {
2655 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002656 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2657 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002658 readOutputParameters();
2659 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2660 for (size_t i = 0; i < mTracks.size() ; i++) {
2661 int name = getTrackName_l();
2662 if (name < 0) break;
2663 mTracks[i]->mName = name;
2664 // limit track sample rate to 2 x new output sample rate
2665 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2666 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2667 }
2668 }
2669 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2670 }
2671 }
2672
2673 mNewParameters.removeAt(0);
2674
2675 mParamStatus = status;
2676 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002677 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2678 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002679 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002680 }
2681 return reconfig;
2682}
2683
2684status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2685{
2686 const size_t SIZE = 256;
2687 char buffer[SIZE];
2688 String8 result;
2689
2690 PlaybackThread::dumpInternals(fd, args);
2691
2692 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2693 result.append(buffer);
2694 write(fd, result.string(), result.size());
2695 return NO_ERROR;
2696}
2697
Mathias Agopian65ab4712010-07-14 17:59:35 -07002698uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2699{
Eric Laurent60e18242010-07-29 06:50:24 -07002700 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002701}
2702
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002703uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2704{
2705 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2706}
2707
Glenn Kasten66fcab92012-02-24 14:59:21 -08002708void AudioFlinger::MixerThread::cacheParameters_l()
2709{
2710 PlaybackThread::cacheParameters_l();
2711
2712 // FIXME: Relaxed timing because of a certain device that can't meet latency
2713 // Should be reduced to 2x after the vendor fixes the driver issue
2714 // increase threshold again due to low power audio mode. The way this warning
2715 // threshold is calculated and its usefulness should be reconsidered anyway.
2716 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
2717}
2718
Mathias Agopian65ab4712010-07-14 17:59:35 -07002719// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002720AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2721 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002722 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002723 // mLeftVolFloat, mRightVolFloat
2724 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002725{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002726}
2727
2728AudioFlinger::DirectOutputThread::~DirectOutputThread()
2729{
2730}
2731
Glenn Kasten000f0e32012-03-01 17:10:56 -08002732void AudioFlinger::DirectOutputThread::applyVolume()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002733{
2734 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002735 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002736 return;
2737 }
2738
2739 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002740 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002741 size_t count = mFrameCount * mChannelCount;
2742 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2743 int16_t *dst = mMixBuffer + count-1;
2744 while(count--) {
2745 *dst-- = (int16_t)(*src--^0x80) << 8;
2746 }
2747 }
2748
2749 size_t frameCount = mFrameCount;
2750 int16_t *out = mMixBuffer;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002751 if (rampVolume) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002752 if (mChannelCount == 1) {
2753 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2754 int32_t vlInc = d / (int32_t)frameCount;
2755 int32_t vl = ((int32_t)mLeftVolShort << 16);
2756 do {
2757 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2758 out++;
2759 vl += vlInc;
2760 } while (--frameCount);
2761
2762 } else {
2763 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2764 int32_t vlInc = d / (int32_t)frameCount;
2765 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2766 int32_t vrInc = d / (int32_t)frameCount;
2767 int32_t vl = ((int32_t)mLeftVolShort << 16);
2768 int32_t vr = ((int32_t)mRightVolShort << 16);
2769 do {
2770 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2771 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2772 out += 2;
2773 vl += vlInc;
2774 vr += vrInc;
2775 } while (--frameCount);
2776 }
2777 } else {
2778 if (mChannelCount == 1) {
2779 do {
2780 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2781 out++;
2782 } while (--frameCount);
2783 } else {
2784 do {
2785 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2786 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2787 out += 2;
2788 } while (--frameCount);
2789 }
2790 }
2791
2792 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002793 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002794 size_t count = mFrameCount * mChannelCount;
2795 int16_t *src = mMixBuffer;
2796 uint8_t *dst = (uint8_t *)mMixBuffer;
2797 while(count--) {
2798 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2799 }
2800 }
2801
2802 mLeftVolShort = leftVol;
2803 mRightVolShort = rightVol;
2804}
2805
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002806AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
2807 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08002808)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002809{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002810 sp<Track> trackToRemove;
2811
Glenn Kastenfec279f2012-03-08 07:47:15 -08002812 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002813
Glenn Kasten952eeb22012-03-06 11:30:57 -08002814 // find out which tracks need to be processed
2815 if (mActiveTracks.size() != 0) {
2816 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08002817 // The track died recently
2818 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002819
Glenn Kasten952eeb22012-03-06 11:30:57 -08002820 Track* const track = t.get();
2821 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002822
Glenn Kasten952eeb22012-03-06 11:30:57 -08002823 // The first time a track is added we wait
2824 // for all its buffers to be filled before processing it
2825 if (cblk->framesReady() && track->isReady() &&
2826 !track->isPaused() && !track->isTerminated())
2827 {
2828 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002829
Glenn Kasten952eeb22012-03-06 11:30:57 -08002830 if (track->mFillingUpStatus == Track::FS_FILLED) {
2831 track->mFillingUpStatus = Track::FS_ACTIVE;
2832 mLeftVolFloat = mRightVolFloat = 0;
2833 mLeftVolShort = mRightVolShort = 0;
2834 if (track->mState == TrackBase::RESUMING) {
2835 track->mState = TrackBase::ACTIVE;
2836 rampVolume = true;
2837 }
2838 } else if (cblk->server != 0) {
2839 // If the track is stopped before the first frame was mixed,
2840 // do not apply ramp
2841 rampVolume = true;
2842 }
2843 // compute volume for this track
2844 float left, right;
2845 if (track->isMuted() || mMasterMute || track->isPausing() ||
2846 mStreamTypes[track->streamType()].mute) {
2847 left = right = 0;
2848 if (track->isPausing()) {
2849 track->setPaused();
2850 }
2851 } else {
2852 float typeVolume = mStreamTypes[track->streamType()].volume;
2853 float v = mMasterVolume * typeVolume;
2854 uint32_t vlr = cblk->getVolumeLR();
2855 float v_clamped = v * (vlr & 0xFFFF);
2856 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2857 left = v_clamped/MAX_GAIN;
2858 v_clamped = v * (vlr >> 16);
2859 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2860 right = v_clamped/MAX_GAIN;
2861 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002862
Glenn Kasten952eeb22012-03-06 11:30:57 -08002863 if (left != mLeftVolFloat || right != mRightVolFloat) {
2864 mLeftVolFloat = left;
2865 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002866
Glenn Kasten952eeb22012-03-06 11:30:57 -08002867 // If audio HAL implements volume control,
2868 // force software volume to nominal value
2869 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
2870 left = 1.0f;
2871 right = 1.0f;
2872 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002873
Glenn Kasten952eeb22012-03-06 11:30:57 -08002874 // Convert volumes from float to 8.24
2875 uint32_t vl = (uint32_t)(left * (1 << 24));
2876 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002877
Glenn Kasten952eeb22012-03-06 11:30:57 -08002878 // Delegate volume control to effect in track effect chain if needed
2879 // only one effect chain can be present on DirectOutputThread, so if
2880 // there is one, the track is connected to it
2881 if (!mEffectChains.isEmpty()) {
2882 // Do not ramp volume if volume is controlled by effect
2883 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002884 rampVolume = false;
2885 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002886 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002887
Glenn Kasten952eeb22012-03-06 11:30:57 -08002888 // Convert volumes from 8.24 to 4.12 format
2889 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2890 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2891 leftVol = (uint16_t)v_clamped;
2892 v_clamped = (vr + (1 << 11)) >> 12;
2893 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2894 rightVol = (uint16_t)v_clamped;
2895 } else {
2896 leftVol = mLeftVolShort;
2897 rightVol = mRightVolShort;
2898 rampVolume = false;
2899 }
2900
2901 // reset retry count
2902 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002903 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002904 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002905 } else {
2906 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2907 if (track->isStopped()) {
2908 track->reset();
2909 }
2910 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2911 // We have consumed all the buffers of this track.
2912 // Remove it from the list of active tracks.
2913 trackToRemove = track;
2914 } else {
2915 // No buffers for this track. Give it a few chances to
2916 // fill a buffer, then remove it from active list.
2917 if (--(track->mRetryCount) <= 0) {
2918 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2919 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002920 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002921 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002922 }
2923 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002924 }
2925 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002926
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002927 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08002928 // remove all the tracks that need to be...
2929 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002930 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002931 mActiveTracks.remove(trackToRemove);
2932 if (!mEffectChains.isEmpty()) {
2933 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2934 trackToRemove->sessionId());
2935 mEffectChains[0]->decActiveTrackCnt();
2936 }
2937 if (trackToRemove->isTerminated()) {
2938 removeTrack_l(trackToRemove);
2939 }
2940 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002941
Glenn Kastenfec279f2012-03-08 07:47:15 -08002942 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002943}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002944
Glenn Kasten000f0e32012-03-01 17:10:56 -08002945void AudioFlinger::DirectOutputThread::threadLoop_mix()
2946{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002947 AudioBufferProvider::Buffer buffer;
2948 size_t frameCount = mFrameCount;
2949 int8_t *curBuf = (int8_t *)mMixBuffer;
2950 // output audio to hardware
2951 while (frameCount) {
2952 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002953 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002954 if (CC_UNLIKELY(buffer.raw == NULL)) {
2955 memset(curBuf, 0, frameCount * mFrameSize);
2956 break;
2957 }
2958 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2959 frameCount -= buffer.frameCount;
2960 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002961 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002962 }
2963 sleepTime = 0;
2964 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002965 mActiveTrack.clear();
Glenn Kastend4513b02012-03-06 15:52:35 -08002966 applyVolume();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002967}
2968
2969void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
2970{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002971 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002972 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002973 sleepTime = activeSleepTime;
2974 } else {
2975 sleepTime = idleSleepTime;
2976 }
2977 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
2978 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2979 sleepTime = 0;
2980 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002981}
2982
2983// getTrackName_l() must be called with ThreadBase::mLock held
2984int AudioFlinger::DirectOutputThread::getTrackName_l()
2985{
2986 return 0;
2987}
2988
2989// deleteTrackName_l() must be called with ThreadBase::mLock held
2990void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2991{
2992}
2993
2994// checkForNewParameters_l() must be called with ThreadBase::mLock held
2995bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2996{
2997 bool reconfig = false;
2998
2999 while (!mNewParameters.isEmpty()) {
3000 status_t status = NO_ERROR;
3001 String8 keyValuePair = mNewParameters[0];
3002 AudioParameter param = AudioParameter(keyValuePair);
3003 int value;
3004
3005 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3006 // do not accept frame count changes if tracks are open as the track buffer
3007 // size depends on frame count and correct behavior would not be garantied
3008 // if frame count is changed after track creation
3009 if (!mTracks.isEmpty()) {
3010 status = INVALID_OPERATION;
3011 } else {
3012 reconfig = true;
3013 }
3014 }
3015 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003016 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003017 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003018 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003019 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003020 mStandby = true;
3021 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07003022 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003023 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003024 }
3025 if (status == NO_ERROR && reconfig) {
3026 readOutputParameters();
3027 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3028 }
3029 }
3030
3031 mNewParameters.removeAt(0);
3032
3033 mParamStatus = status;
3034 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003035 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3036 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003037 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003038 }
3039 return reconfig;
3040}
3041
3042uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
3043{
3044 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003045 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003046 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003047 } else {
3048 time = 10000;
3049 }
3050 return time;
3051}
3052
3053uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
3054{
3055 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003056 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003057 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003058 } else {
3059 time = 10000;
3060 }
3061 return time;
3062}
3063
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003064uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
3065{
3066 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003067 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003068 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3069 } else {
3070 time = 10000;
3071 }
3072 return time;
3073}
3074
Glenn Kasten66fcab92012-02-24 14:59:21 -08003075void AudioFlinger::DirectOutputThread::cacheParameters_l()
3076{
3077 PlaybackThread::cacheParameters_l();
3078
3079 // use shorter standby delay as on normal output to release
3080 // hardware resources as soon as possible
3081 standbyDelay = microseconds(activeSleepTime*2);
3082}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003083
Mathias Agopian65ab4712010-07-14 17:59:35 -07003084// ----------------------------------------------------------------------------
3085
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003086AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003087 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003088 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3089 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003090{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003091 addOutputTrack(mainThread);
3092}
3093
3094AudioFlinger::DuplicatingThread::~DuplicatingThread()
3095{
3096 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3097 mOutputTracks[i]->destroy();
3098 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003099}
3100
Glenn Kasten000f0e32012-03-01 17:10:56 -08003101void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003102{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003103 // mix buffers...
3104 if (outputsReady(outputTracks)) {
3105 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3106 } else {
3107 memset(mMixBuffer, 0, mixBufferSize);
3108 }
3109 sleepTime = 0;
3110 writeFrames = mFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003111}
3112
3113void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3114{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003115 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003116 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003117 sleepTime = activeSleepTime;
3118 } else {
3119 sleepTime = idleSleepTime;
3120 }
3121 } else if (mBytesWritten != 0) {
3122 // flush remaining overflow buffers in output tracks
3123 for (size_t i = 0; i < outputTracks.size(); i++) {
3124 if (outputTracks[i]->isActive()) {
3125 sleepTime = 0;
3126 writeFrames = 0;
3127 memset(mMixBuffer, 0, mixBufferSize);
3128 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003129 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003130 }
3131 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003132}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003133
Glenn Kasten000f0e32012-03-01 17:10:56 -08003134void AudioFlinger::DuplicatingThread::threadLoop_write()
3135{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003136 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003137 for (size_t i = 0; i < outputTracks.size(); i++) {
3138 outputTracks[i]->write(mMixBuffer, writeFrames);
3139 }
3140 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003141}
Glenn Kasten688a6402012-02-29 07:57:06 -08003142
Glenn Kasten000f0e32012-03-01 17:10:56 -08003143void AudioFlinger::DuplicatingThread::threadLoop_standby()
3144{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003145 // DuplicatingThread implements standby by stopping all tracks
3146 for (size_t i = 0; i < outputTracks.size(); i++) {
3147 outputTracks[i]->stop();
3148 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003149}
3150
Glenn Kastenfa26a852012-03-06 11:28:04 -08003151void AudioFlinger::DuplicatingThread::saveOutputTracks()
3152{
3153 outputTracks = mOutputTracks;
3154}
3155
3156void AudioFlinger::DuplicatingThread::clearOutputTracks()
3157{
3158 outputTracks.clear();
3159}
3160
Mathias Agopian65ab4712010-07-14 17:59:35 -07003161void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3162{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003163 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003164 // FIXME explain this formula
Mathias Agopian65ab4712010-07-14 17:59:35 -07003165 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003166 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003167 this,
3168 mSampleRate,
3169 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003170 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003171 frameCount);
3172 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003173 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003174 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003175 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003176 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003177 }
3178}
3179
3180void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3181{
3182 Mutex::Autolock _l(mLock);
3183 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003184 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003185 mOutputTracks[i]->destroy();
3186 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003187 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003188 return;
3189 }
3190 }
Steve Block3856b092011-10-20 11:56:00 +01003191 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003192}
3193
Glenn Kasten438b0362012-03-06 11:24:48 -08003194// caller must hold mLock
3195void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003196{
3197 mWaitTimeMs = UINT_MAX;
3198 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3199 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003200 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003201 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3202 if (waitTimeMs < mWaitTimeMs) {
3203 mWaitTimeMs = waitTimeMs;
3204 }
3205 }
3206 }
3207}
3208
3209
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003210bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003211{
3212 for (size_t i = 0; i < outputTracks.size(); i++) {
3213 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3214 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003215 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003216 return false;
3217 }
3218 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3219 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003220 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003221 return false;
3222 }
3223 }
3224 return true;
3225}
3226
3227uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3228{
3229 return (mWaitTimeMs * 1000) / 2;
3230}
3231
Glenn Kasten66fcab92012-02-24 14:59:21 -08003232void AudioFlinger::DuplicatingThread::cacheParameters_l()
3233{
3234 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3235 updateWaitTime_l();
3236
3237 MixerThread::cacheParameters_l();
3238}
3239
Mathias Agopian65ab4712010-07-14 17:59:35 -07003240// ----------------------------------------------------------------------------
3241
3242// TrackBase constructor must be called with AudioFlinger::mLock held
3243AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003244 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003245 const sp<Client>& client,
3246 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003247 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003248 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003249 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003250 const sp<IMemory>& sharedBuffer,
3251 int sessionId)
3252 : RefBase(),
3253 mThread(thread),
3254 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003255 mCblk(NULL),
3256 // mBuffer
3257 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003258 mFrameCount(0),
3259 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003260 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003261 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003262 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003263 // mChannelCount
3264 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003265{
Steve Block3856b092011-10-20 11:56:00 +01003266 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003267
Steve Blockb8a80522011-12-20 16:23:08 +00003268 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003269 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003270 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003271 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3272 if (sharedBuffer == 0) {
3273 size += bufferSize;
3274 }
3275
3276 if (client != NULL) {
3277 mCblkMemory = client->heap()->allocate(size);
3278 if (mCblkMemory != 0) {
3279 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003280 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003281 new(mCblk) audio_track_cblk_t();
3282 // clear all buffers
3283 mCblk->frameCount = frameCount;
3284 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003285 mChannelCount = channelCount;
3286 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003287 if (sharedBuffer == 0) {
3288 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3289 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3290 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003291 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003292 mCblk->flags = CBLK_UNDERRUN_ON;
3293 } else {
3294 mBuffer = sharedBuffer->pointer();
3295 }
3296 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3297 }
3298 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003299 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003300 client->heap()->dump("AudioTrack");
3301 return;
3302 }
3303 } else {
3304 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003305 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003306 new(mCblk) audio_track_cblk_t();
3307 // clear all buffers
3308 mCblk->frameCount = frameCount;
3309 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003310 mChannelCount = channelCount;
3311 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003312 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3313 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3314 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003315 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003316 mCblk->flags = CBLK_UNDERRUN_ON;
3317 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003318 }
3319}
3320
3321AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3322{
Glenn Kastena0d68332012-01-27 16:47:15 -08003323 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003324 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003325 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003326 } else {
3327 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003328 }
3329 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003330 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003331 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003332 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003333 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003334 // If the client's reference count drops to zero, the associated destructor
3335 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3336 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003337 mClient.clear();
3338 }
3339}
3340
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003341// AudioBufferProvider interface
3342// getNextBuffer() = 0;
3343// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07003344void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3345{
Glenn Kastene0feee32011-12-13 11:53:26 -08003346 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003347 mFrameCount = buffer->frameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003348 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003349 buffer->frameCount = 0;
3350}
3351
3352bool AudioFlinger::ThreadBase::TrackBase::step() {
3353 bool result;
3354 audio_track_cblk_t* cblk = this->cblk();
3355
3356 result = cblk->stepServer(mFrameCount);
3357 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003358 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003359 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003360 }
3361 return result;
3362}
3363
3364void AudioFlinger::ThreadBase::TrackBase::reset() {
3365 audio_track_cblk_t* cblk = this->cblk();
3366
3367 cblk->user = 0;
3368 cblk->server = 0;
3369 cblk->userBase = 0;
3370 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003371 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01003372 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003373}
3374
Mathias Agopian65ab4712010-07-14 17:59:35 -07003375int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3376 return (int)mCblk->sampleRate;
3377}
3378
Mathias Agopian65ab4712010-07-14 17:59:35 -07003379void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3380 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003381 size_t frameSize = cblk->frameSize;
3382 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3383 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003384
3385 // Check validity of returned pointer in case the track control block would have been corrupted.
3386 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003387 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003388 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 -07003389 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003390 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003391 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003392 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003393 }
3394
3395 return bufferStart;
3396}
3397
3398// ----------------------------------------------------------------------------
3399
3400// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3401AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003402 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003403 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003404 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003405 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003406 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003407 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003408 int frameCount,
3409 const sp<IMemory>& sharedBuffer,
3410 int sessionId)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003411 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003412 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3413 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003414{
3415 if (mCblk != NULL) {
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003416 if (thread != NULL) {
3417 mName = thread->getTrackName_l();
3418 mMainBuffer = thread->mixBuffer();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003419 }
Glenn Kasten23d82a92012-02-03 11:10:00 -08003420 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003421 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003422 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003423 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003424 mStreamType = streamType;
3425 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3426 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003427 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003428 }
3429}
3430
3431AudioFlinger::PlaybackThread::Track::~Track()
3432{
Steve Block3856b092011-10-20 11:56:00 +01003433 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003434 sp<ThreadBase> thread = mThread.promote();
3435 if (thread != 0) {
3436 Mutex::Autolock _l(thread->mLock);
3437 mState = TERMINATED;
3438 }
3439}
3440
3441void AudioFlinger::PlaybackThread::Track::destroy()
3442{
3443 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3444 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08003445 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003446 // we must acquire a strong reference on this Track before locking mLock
3447 // here so that the destructor is called only when exiting this function.
3448 // On the other hand, as long as Track::destroy() is only called by
3449 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3450 // this Track with its member mTrack.
3451 sp<Track> keep(this);
3452 { // scope for mLock
3453 sp<ThreadBase> thread = mThread.promote();
3454 if (thread != 0) {
3455 if (!isOutputTrack()) {
3456 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08003457 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003458
3459 // to track the speaker usage
3460 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003461 }
3462 AudioSystem::releaseOutput(thread->id());
3463 }
3464 Mutex::Autolock _l(thread->mLock);
3465 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3466 playbackThread->destroyTrack_l(this);
3467 }
3468 }
3469}
3470
3471void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3472{
Glenn Kasten83d86532012-01-17 14:39:34 -08003473 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003474 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 -07003475 mName - AudioMixer::TRACK0,
Glenn Kasten44deb052012-02-05 18:09:08 -08003476 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003477 mStreamType,
3478 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003479 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003480 mSessionId,
3481 mFrameCount,
3482 mState,
3483 mMute,
3484 mFillingUpStatus,
3485 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003486 vlr & 0xFFFF,
3487 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003488 mCblk->server,
3489 mCblk->user,
3490 (int)mMainBuffer,
3491 (int)mAuxBuffer);
3492}
3493
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003494// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08003495status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
3496 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003497{
3498 audio_track_cblk_t* cblk = this->cblk();
3499 uint32_t framesReady;
3500 uint32_t framesReq = buffer->frameCount;
3501
3502 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003503 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003504 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003505 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003506 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003507 }
3508
3509 framesReady = cblk->framesReady();
3510
Glenn Kastenf6b16782011-12-15 09:51:17 -08003511 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003512 uint32_t s = cblk->server;
3513 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3514
3515 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3516 if (framesReq > framesReady) {
3517 framesReq = framesReady;
3518 }
3519 if (s + framesReq > bufferEnd) {
3520 framesReq = bufferEnd - s;
3521 }
3522
3523 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003524 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003525
3526 buffer->frameCount = framesReq;
3527 return NO_ERROR;
3528 }
3529
3530getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003531 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003532 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003533 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003534 return NOT_ENOUGH_DATA;
3535}
3536
John Grossman4ff14ba2012-02-08 16:37:41 -08003537uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const{
3538 return mCblk->framesReady();
3539}
3540
Mathias Agopian65ab4712010-07-14 17:59:35 -07003541bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003542 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003543
John Grossman4ff14ba2012-02-08 16:37:41 -08003544 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003545 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3546 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003547 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003548 return true;
3549 }
3550 return false;
3551}
3552
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003553status_t AudioFlinger::PlaybackThread::Track::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003554{
3555 status_t status = NO_ERROR;
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003556 ALOGV("start(%d), calling pid %d session %d tid %d",
3557 mName, IPCThreadState::self()->getCallingPid(), mSessionId, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003558 sp<ThreadBase> thread = mThread.promote();
3559 if (thread != 0) {
3560 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003561 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003562 // here the track could be either new, or restarted
3563 // in both cases "unstop" the track
3564 if (mState == PAUSED) {
3565 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003566 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003567 } else {
3568 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003569 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003570 }
3571
3572 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3573 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003574 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003575 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003576
3577 // to track the speaker usage
3578 if (status == NO_ERROR) {
3579 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3580 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003581 }
3582 if (status == NO_ERROR) {
3583 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3584 playbackThread->addTrack_l(this);
3585 } else {
3586 mState = state;
3587 }
3588 } else {
3589 status = BAD_VALUE;
3590 }
3591 return status;
3592}
3593
3594void AudioFlinger::PlaybackThread::Track::stop()
3595{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003596 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003597 sp<ThreadBase> thread = mThread.promote();
3598 if (thread != 0) {
3599 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003600 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003601 if (mState > STOPPED) {
3602 mState = STOPPED;
3603 // If the track is not active (PAUSED and buffers full), flush buffers
3604 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3605 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3606 reset();
3607 }
Steve Block3856b092011-10-20 11:56:00 +01003608 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003609 }
3610 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3611 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003612 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003613 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003614
3615 // to track the speaker usage
3616 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003617 }
3618 }
3619}
3620
3621void AudioFlinger::PlaybackThread::Track::pause()
3622{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003623 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003624 sp<ThreadBase> thread = mThread.promote();
3625 if (thread != 0) {
3626 Mutex::Autolock _l(thread->mLock);
3627 if (mState == ACTIVE || mState == RESUMING) {
3628 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003629 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003630 if (!isOutputTrack()) {
3631 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003632 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003633 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003634
3635 // to track the speaker usage
3636 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003637 }
3638 }
3639 }
3640}
3641
3642void AudioFlinger::PlaybackThread::Track::flush()
3643{
Steve Block3856b092011-10-20 11:56:00 +01003644 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003645 sp<ThreadBase> thread = mThread.promote();
3646 if (thread != 0) {
3647 Mutex::Autolock _l(thread->mLock);
3648 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3649 return;
3650 }
3651 // No point remaining in PAUSED state after a flush => go to
3652 // STOPPED state
3653 mState = STOPPED;
3654
Eric Laurent38ccae22011-03-28 18:37:07 -07003655 // do not reset the track if it is still in the process of being stopped or paused.
3656 // this will be done by prepareTracks_l() when the track is stopped.
3657 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3658 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3659 reset();
3660 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003661 }
3662}
3663
3664void AudioFlinger::PlaybackThread::Track::reset()
3665{
3666 // Do not reset twice to avoid discarding data written just after a flush and before
3667 // the audioflinger thread detects the track is stopped.
3668 if (!mResetDone) {
3669 TrackBase::reset();
3670 // Force underrun condition to avoid false underrun callback until first data is
3671 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003672 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3673 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003674 mFillingUpStatus = FS_FILLING;
3675 mResetDone = true;
3676 }
3677}
3678
3679void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3680{
3681 mMute = muted;
3682}
3683
Mathias Agopian65ab4712010-07-14 17:59:35 -07003684status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3685{
3686 status_t status = DEAD_OBJECT;
3687 sp<ThreadBase> thread = mThread.promote();
3688 if (thread != 0) {
3689 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3690 status = playbackThread->attachAuxEffect(this, EffectId);
3691 }
3692 return status;
3693}
3694
3695void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3696{
3697 mAuxEffectId = EffectId;
3698 mAuxBuffer = buffer;
3699}
3700
John Grossman4ff14ba2012-02-08 16:37:41 -08003701// timed audio tracks
3702
3703sp<AudioFlinger::PlaybackThread::TimedTrack>
3704AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003705 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003706 const sp<Client>& client,
3707 audio_stream_type_t streamType,
3708 uint32_t sampleRate,
3709 audio_format_t format,
3710 uint32_t channelMask,
3711 int frameCount,
3712 const sp<IMemory>& sharedBuffer,
3713 int sessionId) {
3714 if (!client->reserveTimedTrack())
3715 return NULL;
3716
3717 sp<TimedTrack> track = new TimedTrack(
3718 thread, client, streamType, sampleRate, format, channelMask, frameCount,
3719 sharedBuffer, sessionId);
3720
3721 if (track == NULL) {
3722 client->releaseTimedTrack();
3723 return NULL;
3724 }
3725
3726 return track;
3727}
3728
3729AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003730 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003731 const sp<Client>& client,
3732 audio_stream_type_t streamType,
3733 uint32_t sampleRate,
3734 audio_format_t format,
3735 uint32_t channelMask,
3736 int frameCount,
3737 const sp<IMemory>& sharedBuffer,
3738 int sessionId)
3739 : Track(thread, client, streamType, sampleRate, format, channelMask,
3740 frameCount, sharedBuffer, sessionId),
3741 mTimedSilenceBuffer(NULL),
3742 mTimedSilenceBufferSize(0),
3743 mTimedAudioOutputOnTime(false),
3744 mMediaTimeTransformValid(false)
3745{
3746 LocalClock lc;
3747 mLocalTimeFreq = lc.getLocalFreq();
3748
3749 mLocalTimeToSampleTransform.a_zero = 0;
3750 mLocalTimeToSampleTransform.b_zero = 0;
3751 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3752 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3753 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3754 &mLocalTimeToSampleTransform.a_to_b_denom);
3755}
3756
3757AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3758 mClient->releaseTimedTrack();
3759 delete [] mTimedSilenceBuffer;
3760}
3761
3762status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3763 size_t size, sp<IMemory>* buffer) {
3764
3765 Mutex::Autolock _l(mTimedBufferQueueLock);
3766
3767 trimTimedBufferQueue_l();
3768
3769 // lazily initialize the shared memory heap for timed buffers
3770 if (mTimedMemoryDealer == NULL) {
3771 const int kTimedBufferHeapSize = 512 << 10;
3772
3773 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3774 "AudioFlingerTimed");
3775 if (mTimedMemoryDealer == NULL)
3776 return NO_MEMORY;
3777 }
3778
3779 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3780 if (newBuffer == NULL) {
3781 newBuffer = mTimedMemoryDealer->allocate(size);
3782 if (newBuffer == NULL)
3783 return NO_MEMORY;
3784 }
3785
3786 *buffer = newBuffer;
3787 return NO_ERROR;
3788}
3789
3790// caller must hold mTimedBufferQueueLock
3791void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
3792 int64_t mediaTimeNow;
3793 {
3794 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3795 if (!mMediaTimeTransformValid)
3796 return;
3797
3798 int64_t targetTimeNow;
3799 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
3800 ? mCCHelper.getCommonTime(&targetTimeNow)
3801 : mCCHelper.getLocalTime(&targetTimeNow);
3802
3803 if (OK != res)
3804 return;
3805
3806 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
3807 &mediaTimeNow)) {
3808 return;
3809 }
3810 }
3811
3812 size_t trimIndex;
3813 for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
3814 if (mTimedBufferQueue[trimIndex].pts() > mediaTimeNow)
3815 break;
3816 }
3817
3818 if (trimIndex) {
3819 mTimedBufferQueue.removeItemsAt(0, trimIndex);
3820 }
3821}
3822
3823status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
3824 const sp<IMemory>& buffer, int64_t pts) {
3825
3826 {
3827 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3828 if (!mMediaTimeTransformValid)
3829 return INVALID_OPERATION;
3830 }
3831
3832 Mutex::Autolock _l(mTimedBufferQueueLock);
3833
3834 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
3835
3836 return NO_ERROR;
3837}
3838
3839status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
3840 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
3841
3842 ALOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
3843 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
3844 target);
3845
3846 if (!(target == TimedAudioTrack::LOCAL_TIME ||
3847 target == TimedAudioTrack::COMMON_TIME)) {
3848 return BAD_VALUE;
3849 }
3850
3851 Mutex::Autolock lock(mMediaTimeTransformLock);
3852 mMediaTimeTransform = xform;
3853 mMediaTimeTransformTarget = target;
3854 mMediaTimeTransformValid = true;
3855
3856 return NO_ERROR;
3857}
3858
3859#define min(a, b) ((a) < (b) ? (a) : (b))
3860
3861// implementation of getNextBuffer for tracks whose buffers have timestamps
3862status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
3863 AudioBufferProvider::Buffer* buffer, int64_t pts)
3864{
3865 if (pts == AudioBufferProvider::kInvalidPTS) {
3866 buffer->raw = 0;
3867 buffer->frameCount = 0;
3868 return INVALID_OPERATION;
3869 }
3870
John Grossman4ff14ba2012-02-08 16:37:41 -08003871 Mutex::Autolock _l(mTimedBufferQueueLock);
3872
3873 while (true) {
3874
3875 // if we have no timed buffers, then fail
3876 if (mTimedBufferQueue.isEmpty()) {
3877 buffer->raw = 0;
3878 buffer->frameCount = 0;
3879 return NOT_ENOUGH_DATA;
3880 }
3881
3882 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
3883
3884 // calculate the PTS of the head of the timed buffer queue expressed in
3885 // local time
3886 int64_t headLocalPTS;
3887 {
3888 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3889
3890 assert(mMediaTimeTransformValid);
3891
3892 if (mMediaTimeTransform.a_to_b_denom == 0) {
3893 // the transform represents a pause, so yield silence
3894 timedYieldSilence(buffer->frameCount, buffer);
3895 return NO_ERROR;
3896 }
3897
3898 int64_t transformedPTS;
3899 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
3900 &transformedPTS)) {
3901 // the transform failed. this shouldn't happen, but if it does
3902 // then just drop this buffer
3903 ALOGW("timedGetNextBuffer transform failed");
3904 buffer->raw = 0;
3905 buffer->frameCount = 0;
3906 mTimedBufferQueue.removeAt(0);
3907 return NO_ERROR;
3908 }
3909
3910 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
3911 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
3912 &headLocalPTS)) {
3913 buffer->raw = 0;
3914 buffer->frameCount = 0;
3915 return INVALID_OPERATION;
3916 }
3917 } else {
3918 headLocalPTS = transformedPTS;
3919 }
3920 }
3921
3922 // adjust the head buffer's PTS to reflect the portion of the head buffer
3923 // that has already been consumed
3924 int64_t effectivePTS = headLocalPTS +
3925 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
3926
3927 // Calculate the delta in samples between the head of the input buffer
3928 // queue and the start of the next output buffer that will be written.
3929 // If the transformation fails because of over or underflow, it means
3930 // that the sample's position in the output stream is so far out of
3931 // whack that it should just be dropped.
3932 int64_t sampleDelta;
3933 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
3934 ALOGV("*** head buffer is too far from PTS: dropped buffer");
3935 mTimedBufferQueue.removeAt(0);
3936 continue;
3937 }
3938 if (!mLocalTimeToSampleTransform.doForwardTransform(
3939 (effectivePTS - pts) << 32, &sampleDelta)) {
3940 ALOGV("*** too late during sample rate transform: dropped buffer");
3941 mTimedBufferQueue.removeAt(0);
3942 continue;
3943 }
3944
3945 ALOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
3946 __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
3947 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
3948 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
3949
3950 // if the delta between the ideal placement for the next input sample and
3951 // the current output position is within this threshold, then we will
3952 // concatenate the next input samples to the previous output
3953 const int64_t kSampleContinuityThreshold =
3954 (static_cast<int64_t>(sampleRate()) << 32) / 10;
3955
3956 // if this is the first buffer of audio that we're emitting from this track
3957 // then it should be almost exactly on time.
3958 const int64_t kSampleStartupThreshold = 1LL << 32;
3959
3960 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
3961 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
3962 // the next input is close enough to being on time, so concatenate it
3963 // with the last output
3964 timedYieldSamples(buffer);
3965
3966 ALOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
3967 return NO_ERROR;
3968 } else if (sampleDelta > 0) {
3969 // the gap between the current output position and the proper start of
3970 // the next input sample is too big, so fill it with silence
3971 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
3972
3973 timedYieldSilence(framesUntilNextInput, buffer);
3974 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
3975 return NO_ERROR;
3976 } else {
3977 // the next input sample is late
3978 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
3979 size_t onTimeSamplePosition =
3980 head.position() + lateFrames * mCblk->frameSize;
3981
3982 if (onTimeSamplePosition > head.buffer()->size()) {
3983 // all the remaining samples in the head are too late, so
3984 // drop it and move on
3985 ALOGV("*** too late: dropped buffer");
3986 mTimedBufferQueue.removeAt(0);
3987 continue;
3988 } else {
3989 // skip over the late samples
3990 head.setPosition(onTimeSamplePosition);
3991
3992 // yield the available samples
3993 timedYieldSamples(buffer);
3994
3995 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
3996 return NO_ERROR;
3997 }
3998 }
3999 }
4000}
4001
4002// Yield samples from the timed buffer queue head up to the given output
4003// buffer's capacity.
4004//
4005// Caller must hold mTimedBufferQueueLock
4006void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples(
4007 AudioBufferProvider::Buffer* buffer) {
4008
4009 const TimedBuffer& head = mTimedBufferQueue[0];
4010
4011 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4012 head.position());
4013
4014 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4015 mCblk->frameSize);
4016 size_t framesRequested = buffer->frameCount;
4017 buffer->frameCount = min(framesLeftInHead, framesRequested);
4018
4019 mTimedAudioOutputOnTime = true;
4020}
4021
4022// Yield samples of silence up to the given output buffer's capacity
4023//
4024// Caller must hold mTimedBufferQueueLock
4025void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence(
4026 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4027
4028 // lazily allocate a buffer filled with silence
4029 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4030 delete [] mTimedSilenceBuffer;
4031 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4032 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4033 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4034 }
4035
4036 buffer->raw = mTimedSilenceBuffer;
4037 size_t framesRequested = buffer->frameCount;
4038 buffer->frameCount = min(numFrames, framesRequested);
4039
4040 mTimedAudioOutputOnTime = false;
4041}
4042
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004043// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004044void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4045 AudioBufferProvider::Buffer* buffer) {
4046
4047 Mutex::Autolock _l(mTimedBufferQueueLock);
4048
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004049 // If the buffer which was just released is part of the buffer at the head
4050 // of the queue, be sure to update the amt of the buffer which has been
4051 // consumed. If the buffer being returned is not part of the head of the
4052 // queue, its either because the buffer is part of the silence buffer, or
4053 // because the head of the timed queue was trimmed after the mixer called
4054 // getNextBuffer but before the mixer called releaseBuffer.
4055 if ((buffer->raw != mTimedSilenceBuffer) && mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004056 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004057
4058 void* start = head.buffer()->pointer();
Glenn Kastenf063b492012-02-17 16:24:10 -08004059 void* end = (char *) head.buffer()->pointer() + head.buffer()->size();
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004060
4061 if ((buffer->raw >= start) && (buffer->raw <= end)) {
4062 head.setPosition(head.position() +
4063 (buffer->frameCount * mCblk->frameSize));
4064 if (static_cast<size_t>(head.position()) >= head.buffer()->size()) {
4065 mTimedBufferQueue.removeAt(0);
4066 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004067 }
4068 }
4069
4070 buffer->raw = 0;
4071 buffer->frameCount = 0;
4072}
4073
4074uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4075 Mutex::Autolock _l(mTimedBufferQueueLock);
4076
4077 uint32_t frames = 0;
4078 for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4079 const TimedBuffer& tb = mTimedBufferQueue[i];
4080 frames += (tb.buffer()->size() - tb.position()) / mCblk->frameSize;
4081 }
4082
4083 return frames;
4084}
4085
4086AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4087 : mPTS(0), mPosition(0) {}
4088
4089AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4090 const sp<IMemory>& buffer, int64_t pts)
4091 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4092
Mathias Agopian65ab4712010-07-14 17:59:35 -07004093// ----------------------------------------------------------------------------
4094
4095// RecordTrack constructor must be called with AudioFlinger::mLock held
4096AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004097 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004098 const sp<Client>& client,
4099 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004100 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004101 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004102 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004103 int sessionId)
4104 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004105 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004106 mOverflow(false)
4107{
4108 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01004109 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07004110 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004111 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07004112 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004113 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004114 } else {
4115 mCblk->frameSize = sizeof(int8_t);
4116 }
4117 }
4118}
4119
4120AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4121{
4122 sp<ThreadBase> thread = mThread.promote();
4123 if (thread != 0) {
4124 AudioSystem::releaseInput(thread->id());
4125 }
4126}
4127
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004128// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004129status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004130{
4131 audio_track_cblk_t* cblk = this->cblk();
4132 uint32_t framesAvail;
4133 uint32_t framesReq = buffer->frameCount;
4134
4135 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004136 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004137 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004138 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004139 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004140 }
4141
4142 framesAvail = cblk->framesAvailable_l();
4143
Glenn Kastenf6b16782011-12-15 09:51:17 -08004144 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004145 uint32_t s = cblk->server;
4146 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4147
4148 if (framesReq > framesAvail) {
4149 framesReq = framesAvail;
4150 }
4151 if (s + framesReq > bufferEnd) {
4152 framesReq = bufferEnd - s;
4153 }
4154
4155 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004156 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004157
4158 buffer->frameCount = framesReq;
4159 return NO_ERROR;
4160 }
4161
4162getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004163 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004164 buffer->frameCount = 0;
4165 return NOT_ENOUGH_DATA;
4166}
4167
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004168status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004169{
4170 sp<ThreadBase> thread = mThread.promote();
4171 if (thread != 0) {
4172 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004173 return recordThread->start(this, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004174 } else {
4175 return BAD_VALUE;
4176 }
4177}
4178
4179void AudioFlinger::RecordThread::RecordTrack::stop()
4180{
4181 sp<ThreadBase> thread = mThread.promote();
4182 if (thread != 0) {
4183 RecordThread *recordThread = (RecordThread *)thread.get();
4184 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004185 TrackBase::reset();
4186 // Force overerrun condition to avoid false overrun callback until first data is
4187 // read from buffer
4188 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004189 }
4190}
4191
4192void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4193{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004194 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004195 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004196 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004197 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004198 mSessionId,
4199 mFrameCount,
4200 mState,
4201 mCblk->sampleRate,
4202 mCblk->server,
4203 mCblk->user);
4204}
4205
4206
4207// ----------------------------------------------------------------------------
4208
4209AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004210 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004211 DuplicatingThread *sourceThread,
4212 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004213 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004214 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004215 int frameCount)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004216 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004217 mActive(false), mSourceThread(sourceThread)
4218{
4219
Mathias Agopian65ab4712010-07-14 17:59:35 -07004220 if (mCblk != NULL) {
4221 mCblk->flags |= CBLK_DIRECTION_OUT;
4222 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004223 mOutBuffer.frameCount = 0;
4224 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01004225 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004226 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4227 mCblk, mBuffer, mCblk->buffers,
4228 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004229 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004230 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004231 }
4232}
4233
4234AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4235{
4236 clearBufferQueue();
4237}
4238
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004239status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004240{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004241 status_t status = Track::start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004242 if (status != NO_ERROR) {
4243 return status;
4244 }
4245
4246 mActive = true;
4247 mRetryCount = 127;
4248 return status;
4249}
4250
4251void AudioFlinger::PlaybackThread::OutputTrack::stop()
4252{
4253 Track::stop();
4254 clearBufferQueue();
4255 mOutBuffer.frameCount = 0;
4256 mActive = false;
4257}
4258
4259bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4260{
4261 Buffer *pInBuffer;
4262 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004263 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004264 bool outputBufferFull = false;
4265 inBuffer.frameCount = frames;
4266 inBuffer.i16 = data;
4267
4268 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4269
4270 if (!mActive && frames != 0) {
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004271 start(0);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004272 sp<ThreadBase> thread = mThread.promote();
4273 if (thread != 0) {
4274 MixerThread *mixerThread = (MixerThread *)thread.get();
4275 if (mCblk->frameCount > frames){
4276 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4277 uint32_t startFrames = (mCblk->frameCount - frames);
4278 pInBuffer = new Buffer;
4279 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4280 pInBuffer->frameCount = startFrames;
4281 pInBuffer->i16 = pInBuffer->mBuffer;
4282 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4283 mBufferQueue.add(pInBuffer);
4284 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004285 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004286 }
4287 }
4288 }
4289 }
4290
4291 while (waitTimeLeftMs) {
4292 // First write pending buffers, then new data
4293 if (mBufferQueue.size()) {
4294 pInBuffer = mBufferQueue.itemAt(0);
4295 } else {
4296 pInBuffer = &inBuffer;
4297 }
4298
4299 if (pInBuffer->frameCount == 0) {
4300 break;
4301 }
4302
4303 if (mOutBuffer.frameCount == 0) {
4304 mOutBuffer.frameCount = pInBuffer->frameCount;
4305 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08004306 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01004307 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004308 outputBufferFull = true;
4309 break;
4310 }
4311 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4312 if (waitTimeLeftMs >= waitTimeMs) {
4313 waitTimeLeftMs -= waitTimeMs;
4314 } else {
4315 waitTimeLeftMs = 0;
4316 }
4317 }
4318
4319 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4320 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4321 mCblk->stepUser(outFrames);
4322 pInBuffer->frameCount -= outFrames;
4323 pInBuffer->i16 += outFrames * channelCount;
4324 mOutBuffer.frameCount -= outFrames;
4325 mOutBuffer.i16 += outFrames * channelCount;
4326
4327 if (pInBuffer->frameCount == 0) {
4328 if (mBufferQueue.size()) {
4329 mBufferQueue.removeAt(0);
4330 delete [] pInBuffer->mBuffer;
4331 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01004332 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004333 } else {
4334 break;
4335 }
4336 }
4337 }
4338
4339 // If we could not write all frames, allocate a buffer and queue it for next time.
4340 if (inBuffer.frameCount) {
4341 sp<ThreadBase> thread = mThread.promote();
4342 if (thread != 0 && !thread->standby()) {
4343 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4344 pInBuffer = new Buffer;
4345 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4346 pInBuffer->frameCount = inBuffer.frameCount;
4347 pInBuffer->i16 = pInBuffer->mBuffer;
4348 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4349 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01004350 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004351 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004352 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004353 }
4354 }
4355 }
4356
4357 // Calling write() with a 0 length buffer, means that no more data will be written:
4358 // If no more buffers are pending, fill output track buffer to make sure it is started
4359 // by output mixer.
4360 if (frames == 0 && mBufferQueue.size() == 0) {
4361 if (mCblk->user < mCblk->frameCount) {
4362 frames = mCblk->frameCount - mCblk->user;
4363 pInBuffer = new Buffer;
4364 pInBuffer->mBuffer = new int16_t[frames * channelCount];
4365 pInBuffer->frameCount = frames;
4366 pInBuffer->i16 = pInBuffer->mBuffer;
4367 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4368 mBufferQueue.add(pInBuffer);
4369 } else if (mActive) {
4370 stop();
4371 }
4372 }
4373
4374 return outputBufferFull;
4375}
4376
4377status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4378{
4379 int active;
4380 status_t result;
4381 audio_track_cblk_t* cblk = mCblk;
4382 uint32_t framesReq = buffer->frameCount;
4383
Steve Block3856b092011-10-20 11:56:00 +01004384// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004385 buffer->frameCount = 0;
4386
4387 uint32_t framesAvail = cblk->framesAvailable();
4388
4389
4390 if (framesAvail == 0) {
4391 Mutex::Autolock _l(cblk->lock);
4392 goto start_loop_here;
4393 while (framesAvail == 0) {
4394 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004395 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004396 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004397 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004398 }
4399 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4400 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004401 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004402 }
4403 // read the server count again
4404 start_loop_here:
4405 framesAvail = cblk->framesAvailable_l();
4406 }
4407 }
4408
4409// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004410// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004411// }
4412
4413 if (framesReq > framesAvail) {
4414 framesReq = framesAvail;
4415 }
4416
4417 uint32_t u = cblk->user;
4418 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4419
4420 if (u + framesReq > bufferEnd) {
4421 framesReq = bufferEnd - u;
4422 }
4423
4424 buffer->frameCount = framesReq;
4425 buffer->raw = (void *)cblk->buffer(u);
4426 return NO_ERROR;
4427}
4428
4429
4430void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4431{
4432 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004433
4434 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004435 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004436 delete [] pBuffer->mBuffer;
4437 delete pBuffer;
4438 }
4439 mBufferQueue.clear();
4440}
4441
4442// ----------------------------------------------------------------------------
4443
4444AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4445 : RefBase(),
4446 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08004447 // 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 -07004448 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08004449 mPid(pid),
4450 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004451{
4452 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4453}
4454
4455// Client destructor must be called with AudioFlinger::mLock held
4456AudioFlinger::Client::~Client()
4457{
4458 mAudioFlinger->removeClient_l(mPid);
4459}
4460
Glenn Kasten435dbe62012-01-30 10:15:48 -08004461sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004462{
4463 return mMemoryDealer;
4464}
4465
John Grossman4ff14ba2012-02-08 16:37:41 -08004466// Reserve one of the limited slots for a timed audio track associated
4467// with this client
4468bool AudioFlinger::Client::reserveTimedTrack()
4469{
4470 const int kMaxTimedTracksPerClient = 4;
4471
4472 Mutex::Autolock _l(mTimedTrackLock);
4473
4474 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4475 ALOGW("can not create timed track - pid %d has exceeded the limit",
4476 mPid);
4477 return false;
4478 }
4479
4480 mTimedTrackCount++;
4481 return true;
4482}
4483
4484// Release a slot for a timed audio track
4485void AudioFlinger::Client::releaseTimedTrack()
4486{
4487 Mutex::Autolock _l(mTimedTrackLock);
4488 mTimedTrackCount--;
4489}
4490
Mathias Agopian65ab4712010-07-14 17:59:35 -07004491// ----------------------------------------------------------------------------
4492
4493AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4494 const sp<IAudioFlingerClient>& client,
4495 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004496 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004497{
4498}
4499
4500AudioFlinger::NotificationClient::~NotificationClient()
4501{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004502}
4503
4504void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4505{
4506 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08004507 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004508}
4509
4510// ----------------------------------------------------------------------------
4511
4512AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4513 : BnAudioTrack(),
4514 mTrack(track)
4515{
4516}
4517
4518AudioFlinger::TrackHandle::~TrackHandle() {
4519 // just stop the track on deletion, associated resources
4520 // will be freed from the main thread once all pending buffers have
4521 // been played. Unless it's not in the active track list, in which
4522 // case we free everything now...
4523 mTrack->destroy();
4524}
4525
Glenn Kasten90716c52012-01-26 13:40:12 -08004526sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4527 return mTrack->getCblk();
4528}
4529
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004530status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4531 return mTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004532}
4533
4534void AudioFlinger::TrackHandle::stop() {
4535 mTrack->stop();
4536}
4537
4538void AudioFlinger::TrackHandle::flush() {
4539 mTrack->flush();
4540}
4541
4542void AudioFlinger::TrackHandle::mute(bool e) {
4543 mTrack->mute(e);
4544}
4545
4546void AudioFlinger::TrackHandle::pause() {
4547 mTrack->pause();
4548}
4549
Mathias Agopian65ab4712010-07-14 17:59:35 -07004550status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4551{
4552 return mTrack->attachAuxEffect(EffectId);
4553}
4554
John Grossman4ff14ba2012-02-08 16:37:41 -08004555status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4556 sp<IMemory>* buffer) {
4557 if (!mTrack->isTimedTrack())
4558 return INVALID_OPERATION;
4559
4560 PlaybackThread::TimedTrack* tt =
4561 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4562 return tt->allocateTimedBuffer(size, buffer);
4563}
4564
4565status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4566 int64_t pts) {
4567 if (!mTrack->isTimedTrack())
4568 return INVALID_OPERATION;
4569
4570 PlaybackThread::TimedTrack* tt =
4571 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4572 return tt->queueTimedBuffer(buffer, pts);
4573}
4574
4575status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4576 const LinearTransform& xform, int target) {
4577
4578 if (!mTrack->isTimedTrack())
4579 return INVALID_OPERATION;
4580
4581 PlaybackThread::TimedTrack* tt =
4582 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4583 return tt->setMediaTimeTransform(
4584 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4585}
4586
Mathias Agopian65ab4712010-07-14 17:59:35 -07004587status_t AudioFlinger::TrackHandle::onTransact(
4588 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4589{
4590 return BnAudioTrack::onTransact(code, data, reply, flags);
4591}
4592
4593// ----------------------------------------------------------------------------
4594
4595sp<IAudioRecord> AudioFlinger::openRecord(
4596 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004597 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004598 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004599 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004600 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004601 int frameCount,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004602 // FIXME dead, remove from IAudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -07004603 uint32_t flags,
4604 int *sessionId,
4605 status_t *status)
4606{
4607 sp<RecordThread::RecordTrack> recordTrack;
4608 sp<RecordHandle> recordHandle;
4609 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004610 status_t lStatus;
4611 RecordThread *thread;
4612 size_t inFrameCount;
4613 int lSessionId;
4614
4615 // check calling permissions
4616 if (!recordingAllowed()) {
4617 lStatus = PERMISSION_DENIED;
4618 goto Exit;
4619 }
4620
4621 // add client to list
4622 { // scope for mLock
4623 Mutex::Autolock _l(mLock);
4624 thread = checkRecordThread_l(input);
4625 if (thread == NULL) {
4626 lStatus = BAD_VALUE;
4627 goto Exit;
4628 }
4629
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004630 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004631
4632 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004633 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004634 lSessionId = *sessionId;
4635 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004636 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004637 if (sessionId != NULL) {
4638 *sessionId = lSessionId;
4639 }
4640 }
4641 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004642 recordTrack = thread->createRecordTrack_l(client,
4643 sampleRate,
4644 format,
4645 channelMask,
4646 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004647 lSessionId,
4648 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004649 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004650 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004651 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4652 // destructor is called by the TrackBase destructor with mLock held
4653 client.clear();
4654 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004655 goto Exit;
4656 }
4657
4658 // return to handle to client
4659 recordHandle = new RecordHandle(recordTrack);
4660 lStatus = NO_ERROR;
4661
4662Exit:
4663 if (status) {
4664 *status = lStatus;
4665 }
4666 return recordHandle;
4667}
4668
4669// ----------------------------------------------------------------------------
4670
4671AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4672 : BnAudioRecord(),
4673 mRecordTrack(recordTrack)
4674{
4675}
4676
4677AudioFlinger::RecordHandle::~RecordHandle() {
4678 stop();
4679}
4680
Glenn Kasten90716c52012-01-26 13:40:12 -08004681sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4682 return mRecordTrack->getCblk();
4683}
4684
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004685status_t AudioFlinger::RecordHandle::start(pid_t tid) {
Steve Block3856b092011-10-20 11:56:00 +01004686 ALOGV("RecordHandle::start()");
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004687 return mRecordTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004688}
4689
4690void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004691 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004692 mRecordTrack->stop();
4693}
4694
Mathias Agopian65ab4712010-07-14 17:59:35 -07004695status_t AudioFlinger::RecordHandle::onTransact(
4696 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4697{
4698 return BnAudioRecord::onTransact(code, data, reply, flags);
4699}
4700
4701// ----------------------------------------------------------------------------
4702
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004703AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4704 AudioStreamIn *input,
4705 uint32_t sampleRate,
4706 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004707 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004708 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004709 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004710 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4711 // mRsmpInIndex and mInputBytes set by readInputParameters()
4712 mReqChannelCount(popcount(channels)),
4713 mReqSampleRate(sampleRate)
4714 // mBytesRead is only meaningful while active, and so is cleared in start()
4715 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004716{
Glenn Kasten480b4682012-02-28 12:30:08 -08004717 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07004718
Mathias Agopian65ab4712010-07-14 17:59:35 -07004719 readInputParameters();
4720}
4721
4722
4723AudioFlinger::RecordThread::~RecordThread()
4724{
4725 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004726 delete mResampler;
4727 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004728}
4729
4730void AudioFlinger::RecordThread::onFirstRef()
4731{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004732 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004733}
4734
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004735status_t AudioFlinger::RecordThread::readyToRun()
4736{
4737 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004738 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004739 return status;
4740}
4741
Mathias Agopian65ab4712010-07-14 17:59:35 -07004742bool AudioFlinger::RecordThread::threadLoop()
4743{
4744 AudioBufferProvider::Buffer buffer;
4745 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004746 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004747
Eric Laurent44d98482010-09-30 16:12:31 -07004748 nsecs_t lastWarning = 0;
4749
Eric Laurentfeb0db62011-07-22 09:04:31 -07004750 acquireWakeLock();
4751
Mathias Agopian65ab4712010-07-14 17:59:35 -07004752 // start recording
4753 while (!exitPending()) {
4754
4755 processConfigEvents();
4756
4757 { // scope for mLock
4758 Mutex::Autolock _l(mLock);
4759 checkForNewParameters_l();
4760 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4761 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004762 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004763 mStandby = true;
4764 }
4765
4766 if (exitPending()) break;
4767
Eric Laurentfeb0db62011-07-22 09:04:31 -07004768 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004769 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004770 // go to sleep
4771 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004772 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004773 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004774 continue;
4775 }
4776 if (mActiveTrack != 0) {
4777 if (mActiveTrack->mState == TrackBase::PAUSING) {
4778 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004779 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004780 mStandby = true;
4781 }
4782 mActiveTrack.clear();
4783 mStartStopCond.broadcast();
4784 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4785 if (mReqChannelCount != mActiveTrack->channelCount()) {
4786 mActiveTrack.clear();
4787 mStartStopCond.broadcast();
4788 } else if (mBytesRead != 0) {
4789 // record start succeeds only if first read from audio input
4790 // succeeds
4791 if (mBytesRead > 0) {
4792 mActiveTrack->mState = TrackBase::ACTIVE;
4793 } else {
4794 mActiveTrack.clear();
4795 }
4796 mStartStopCond.broadcast();
4797 }
4798 mStandby = false;
4799 }
4800 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004801 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004802 }
4803
4804 if (mActiveTrack != 0) {
4805 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4806 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004807 unlockEffectChains(effectChains);
4808 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004809 continue;
4810 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004811 for (size_t i = 0; i < effectChains.size(); i ++) {
4812 effectChains[i]->process_l();
4813 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004814
Mathias Agopian65ab4712010-07-14 17:59:35 -07004815 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004816 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004817 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004818 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004819 // no resampling
4820 while (framesOut) {
4821 size_t framesIn = mFrameCount - mRsmpInIndex;
4822 if (framesIn) {
4823 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4824 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4825 if (framesIn > framesOut)
4826 framesIn = framesOut;
4827 mRsmpInIndex += framesIn;
4828 framesOut -= framesIn;
4829 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004830 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004831 memcpy(dst, src, framesIn * mFrameSize);
4832 } else {
4833 int16_t *src16 = (int16_t *)src;
4834 int16_t *dst16 = (int16_t *)dst;
4835 if (mChannelCount == 1) {
4836 while (framesIn--) {
4837 *dst16++ = *src16;
4838 *dst16++ = *src16++;
4839 }
4840 } else {
4841 while (framesIn--) {
4842 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4843 src16 += 2;
4844 }
4845 }
4846 }
4847 }
4848 if (framesOut && mFrameCount == mRsmpInIndex) {
4849 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004850 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004851 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004852 framesOut = 0;
4853 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004854 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004855 mRsmpInIndex = 0;
4856 }
4857 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004858 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004859 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4860 // Force input into standby so that it tries to
4861 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004862 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004863 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004864 }
4865 mRsmpInIndex = mFrameCount;
4866 framesOut = 0;
4867 buffer.frameCount = 0;
4868 }
4869 }
4870 }
4871 } else {
4872 // resampling
4873
4874 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4875 // alter output frame count as if we were expecting stereo samples
4876 if (mChannelCount == 1 && mReqChannelCount == 1) {
4877 framesOut >>= 1;
4878 }
4879 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4880 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4881 // are 32 bit aligned which should be always true.
4882 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004883 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004884 // the resampler always outputs stereo samples: do post stereo to mono conversion
4885 int16_t *src = (int16_t *)mRsmpOutBuffer;
4886 int16_t *dst = buffer.i16;
4887 while (framesOut--) {
4888 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4889 src += 2;
4890 }
4891 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004892 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004893 }
4894
4895 }
4896 mActiveTrack->releaseBuffer(&buffer);
4897 mActiveTrack->overflow();
4898 }
4899 // client isn't retrieving buffers fast enough
4900 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004901 if (!mActiveTrack->setOverflow()) {
4902 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004903 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004904 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004905 lastWarning = now;
4906 }
4907 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004908 // Release the processor for a while before asking for a new buffer.
4909 // This will give the application more chance to read from the buffer and
4910 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004911 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004912 }
4913 }
Eric Laurentec437d82011-07-26 20:54:46 -07004914 // enable changes in effect chain
4915 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004916 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004917 }
4918
4919 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004920 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004921 }
4922 mActiveTrack.clear();
4923
4924 mStartStopCond.broadcast();
4925
Eric Laurentfeb0db62011-07-22 09:04:31 -07004926 releaseWakeLock();
4927
Steve Block3856b092011-10-20 11:56:00 +01004928 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004929 return false;
4930}
4931
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004932
4933sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4934 const sp<AudioFlinger::Client>& client,
4935 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004936 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004937 int channelMask,
4938 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004939 int sessionId,
4940 status_t *status)
4941{
4942 sp<RecordTrack> track;
4943 status_t lStatus;
4944
4945 lStatus = initCheck();
4946 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004947 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004948 goto Exit;
4949 }
4950
4951 { // scope for mLock
4952 Mutex::Autolock _l(mLock);
4953
4954 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004955 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004956
Glenn Kasten7378ca52012-01-20 13:44:40 -08004957 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004958 lStatus = NO_MEMORY;
4959 goto Exit;
4960 }
4961
4962 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004963 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4964 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004965 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004966 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4967 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004968 }
4969 lStatus = NO_ERROR;
4970
4971Exit:
4972 if (status) {
4973 *status = lStatus;
4974 }
4975 return track;
4976}
4977
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004978status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004979{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004980 ALOGV("RecordThread::start tid=%d", tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004981 sp <ThreadBase> strongMe = this;
4982 status_t status = NO_ERROR;
4983 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004984 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004985 if (mActiveTrack != 0) {
4986 if (recordTrack != mActiveTrack.get()) {
4987 status = -EBUSY;
4988 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4989 mActiveTrack->mState = TrackBase::ACTIVE;
4990 }
4991 return status;
4992 }
4993
4994 recordTrack->mState = TrackBase::IDLE;
4995 mActiveTrack = recordTrack;
4996 mLock.unlock();
4997 status_t status = AudioSystem::startInput(mId);
4998 mLock.lock();
4999 if (status != NO_ERROR) {
5000 mActiveTrack.clear();
5001 return status;
5002 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005003 mRsmpInIndex = mFrameCount;
5004 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005005 if (mResampler != NULL) {
5006 mResampler->reset();
5007 }
5008 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005009 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005010 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005011 mWaitWorkCV.signal();
5012 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005013 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005014 mActiveTrack.clear();
5015 status = INVALID_OPERATION;
5016 goto startError;
5017 }
5018 mStartStopCond.wait(mLock);
5019 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005020 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005021 status = BAD_VALUE;
5022 goto startError;
5023 }
Steve Block3856b092011-10-20 11:56:00 +01005024 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005025 return status;
5026 }
5027startError:
5028 AudioSystem::stopInput(mId);
5029 return status;
5030}
5031
5032void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005033 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005034 sp <ThreadBase> strongMe = this;
5035 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005036 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005037 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5038 mActiveTrack->mState = TrackBase::PAUSING;
5039 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005040 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005041 return;
5042 }
5043 mStartStopCond.wait(mLock);
5044 // if we have been restarted, recordTrack == mActiveTrack.get() here
5045 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5046 mLock.unlock();
5047 AudioSystem::stopInput(mId);
5048 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005049 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005050 }
5051 }
5052 }
5053}
5054
5055status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5056{
5057 const size_t SIZE = 256;
5058 char buffer[SIZE];
5059 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005060
5061 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5062 result.append(buffer);
5063
5064 if (mActiveTrack != 0) {
5065 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005066 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005067 mActiveTrack->dump(buffer, SIZE);
5068 result.append(buffer);
5069
5070 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5071 result.append(buffer);
5072 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5073 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005074 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005075 result.append(buffer);
5076 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5077 result.append(buffer);
5078 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5079 result.append(buffer);
5080
5081
5082 } else {
5083 result.append("No record client\n");
5084 }
5085 write(fd, result.string(), result.size());
5086
5087 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005088 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005089
5090 return NO_ERROR;
5091}
5092
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005093// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005094status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005095{
5096 size_t framesReq = buffer->frameCount;
5097 size_t framesReady = mFrameCount - mRsmpInIndex;
5098 int channelCount;
5099
5100 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005101 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005102 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005103 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005104 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5105 // Force input into standby so that it tries to
5106 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005107 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005108 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005109 }
Glenn Kastene0feee32011-12-13 11:53:26 -08005110 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005111 buffer->frameCount = 0;
5112 return NOT_ENOUGH_DATA;
5113 }
5114 mRsmpInIndex = 0;
5115 framesReady = mFrameCount;
5116 }
5117
5118 if (framesReq > framesReady) {
5119 framesReq = framesReady;
5120 }
5121
5122 if (mChannelCount == 1 && mReqChannelCount == 2) {
5123 channelCount = 1;
5124 } else {
5125 channelCount = 2;
5126 }
5127 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5128 buffer->frameCount = framesReq;
5129 return NO_ERROR;
5130}
5131
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005132// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07005133void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5134{
5135 mRsmpInIndex += buffer->frameCount;
5136 buffer->frameCount = 0;
5137}
5138
5139bool AudioFlinger::RecordThread::checkForNewParameters_l()
5140{
5141 bool reconfig = false;
5142
5143 while (!mNewParameters.isEmpty()) {
5144 status_t status = NO_ERROR;
5145 String8 keyValuePair = mNewParameters[0];
5146 AudioParameter param = AudioParameter(keyValuePair);
5147 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08005148 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005149 int reqSamplingRate = mReqSampleRate;
5150 int reqChannelCount = mReqChannelCount;
5151
5152 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5153 reqSamplingRate = value;
5154 reconfig = true;
5155 }
5156 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08005157 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005158 reconfig = true;
5159 }
5160 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005161 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005162 reconfig = true;
5163 }
5164 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5165 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08005166 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005167 // if frame count is changed after track creation
5168 if (mActiveTrack != 0) {
5169 status = INVALID_OPERATION;
5170 } else {
5171 reconfig = true;
5172 }
5173 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005174 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5175 // forward device change to effects that have requested to be
5176 // aware of attached audio device.
5177 for (size_t i = 0; i < mEffectChains.size(); i++) {
5178 mEffectChains[i]->setDevice_l(value);
5179 }
5180 // store input device and output device but do not forward output device to audio HAL.
5181 // Note that status is ignored by the caller for output device
5182 // (see AudioFlinger::setParameters()
5183 if (value & AUDIO_DEVICE_OUT_ALL) {
5184 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5185 status = BAD_VALUE;
5186 } else {
5187 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07005188 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5189 if (mTrack != NULL) {
5190 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005191 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005192 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5193 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5194 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005195 }
5196 mDevice |= (uint32_t)value;
5197 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005198 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005199 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005200 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005201 mInput->stream->common.standby(&mInput->stream->common);
5202 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005203 }
5204 if (reconfig) {
5205 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005206 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005207 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005208 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08005209 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
5210 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005211 status = NO_ERROR;
5212 }
5213 if (status == NO_ERROR) {
5214 readInputParameters();
5215 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5216 }
5217 }
5218 }
5219
5220 mNewParameters.removeAt(0);
5221
5222 mParamStatus = status;
5223 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07005224 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5225 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08005226 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005227 }
5228 return reconfig;
5229}
5230
5231String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5232{
Dima Zavinfce7a472011-04-19 22:30:36 -07005233 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005234 String8 out_s8 = String8();
5235
5236 Mutex::Autolock _l(mLock);
5237 if (initCheck() != NO_ERROR) {
5238 return out_s8;
5239 }
Dima Zavinfce7a472011-04-19 22:30:36 -07005240
Dima Zavin799a70e2011-04-18 16:57:27 -07005241 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07005242 out_s8 = String8(s);
5243 free(s);
5244 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005245}
5246
5247void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5248 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08005249 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005250
5251 switch (event) {
5252 case AudioSystem::INPUT_OPENED:
5253 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005254 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005255 desc.samplingRate = mSampleRate;
5256 desc.format = mFormat;
5257 desc.frameCount = mFrameCount;
5258 desc.latency = 0;
5259 param2 = &desc;
5260 break;
5261
5262 case AudioSystem::INPUT_CLOSED:
5263 default:
5264 break;
5265 }
5266 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5267}
5268
5269void AudioFlinger::RecordThread::readInputParameters()
5270{
Glenn Kastene9dd0172012-01-27 18:08:45 -08005271 delete mRsmpInBuffer;
5272 // mRsmpInBuffer is always assigned a new[] below
5273 delete mRsmpOutBuffer;
5274 mRsmpOutBuffer = NULL;
5275 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08005276 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005277
Dima Zavin799a70e2011-04-18 16:57:27 -07005278 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005279 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5280 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07005281 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08005282 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07005283 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005284 mFrameCount = mInputBytes / mFrameSize;
5285 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5286
Glenn Kasten53d76db2012-03-08 12:32:47 -08005287 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005288 {
5289 int channelCount;
5290 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5291 // stereo to mono post process as the resampler always outputs stereo.
5292 if (mChannelCount == 1 && mReqChannelCount == 2) {
5293 channelCount = 1;
5294 } else {
5295 channelCount = 2;
5296 }
5297 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5298 mResampler->setSampleRate(mSampleRate);
5299 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5300 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5301
5302 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5303 if (mChannelCount == 1 && mReqChannelCount == 1) {
5304 mFrameCount >>= 1;
5305 }
5306
5307 }
5308 mRsmpInIndex = mFrameCount;
5309}
5310
5311unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5312{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005313 Mutex::Autolock _l(mLock);
5314 if (initCheck() != NO_ERROR) {
5315 return 0;
5316 }
5317
Dima Zavin799a70e2011-04-18 16:57:27 -07005318 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005319}
5320
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005321uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5322{
5323 Mutex::Autolock _l(mLock);
5324 uint32_t result = 0;
5325 if (getEffectChain_l(sessionId) != 0) {
5326 result = EFFECT_SESSION;
5327 }
5328
5329 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5330 result |= TRACK_SESSION;
5331 }
5332
5333 return result;
5334}
5335
Eric Laurent59bd0da2011-08-01 09:52:20 -07005336AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5337{
5338 Mutex::Autolock _l(mLock);
5339 return mTrack;
5340}
5341
Glenn Kastenaed850d2012-01-26 09:46:34 -08005342AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005343{
5344 Mutex::Autolock _l(mLock);
5345 return mInput;
5346}
5347
5348AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5349{
5350 Mutex::Autolock _l(mLock);
5351 AudioStreamIn *input = mInput;
5352 mInput = NULL;
5353 return input;
5354}
5355
5356// this method must always be called either with ThreadBase mLock held or inside the thread loop
5357audio_stream_t* AudioFlinger::RecordThread::stream()
5358{
5359 if (mInput == NULL) {
5360 return NULL;
5361 }
5362 return &mInput->stream->common;
5363}
5364
5365
Mathias Agopian65ab4712010-07-14 17:59:35 -07005366// ----------------------------------------------------------------------------
5367
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005368audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005369 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005370 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005371 uint32_t *pChannels,
5372 uint32_t *pLatencyMs,
Glenn Kasten18868c52012-03-07 09:15:37 -08005373 audio_policy_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005374{
5375 status_t status;
5376 PlaybackThread *thread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005377 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005378 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005379 uint32_t channels = pChannels ? *pChannels : 0;
5380 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07005381 audio_stream_out_t *outStream;
5382 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005383
Steve Block3856b092011-10-20 11:56:00 +01005384 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07005385 pDevices ? *pDevices : 0,
5386 samplingRate,
5387 format,
5388 channels,
5389 flags);
5390
5391 if (pDevices == NULL || *pDevices == 0) {
5392 return 0;
5393 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005394
Mathias Agopian65ab4712010-07-14 17:59:35 -07005395 Mutex::Autolock _l(mLock);
5396
Dima Zavin799a70e2011-04-18 16:57:27 -07005397 outHwDev = findSuitableHwDev_l(*pDevices);
5398 if (outHwDev == NULL)
5399 return 0;
5400
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005401 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Glenn Kasten58f30212012-01-12 12:27:51 -08005402 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005403 &channels, &samplingRate, &outStream);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005404 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01005405 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005406 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005407 samplingRate,
5408 format,
5409 channels,
5410 status);
5411
Dima Zavin799a70e2011-04-18 16:57:27 -07005412 if (outStream != NULL) {
5413 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005414 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07005415
Dima Zavinfce7a472011-04-19 22:30:36 -07005416 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5417 (format != AUDIO_FORMAT_PCM_16_BIT) ||
5418 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005419 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005420 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005421 } else {
5422 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005423 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005424 }
5425 mPlaybackThreads.add(id, thread);
5426
Glenn Kastena0d68332012-01-27 16:47:15 -08005427 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5428 if (pFormat != NULL) *pFormat = format;
5429 if (pChannels != NULL) *pChannels = channels;
5430 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005431
5432 // notify client processes of the new output creation
5433 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5434 return id;
5435 }
5436
5437 return 0;
5438}
5439
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005440audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
5441 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005442{
5443 Mutex::Autolock _l(mLock);
5444 MixerThread *thread1 = checkMixerThread_l(output1);
5445 MixerThread *thread2 = checkMixerThread_l(output2);
5446
5447 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005448 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005449 return 0;
5450 }
5451
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005452 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005453 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5454 thread->addOutputTrack(thread2);
5455 mPlaybackThreads.add(id, thread);
5456 // notify client processes of the new output creation
5457 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5458 return id;
5459}
5460
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005461status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005462{
5463 // keep strong reference on the playback thread so that
5464 // it is not destroyed while exit() is executed
5465 sp <PlaybackThread> thread;
5466 {
5467 Mutex::Autolock _l(mLock);
5468 thread = checkPlaybackThread_l(output);
5469 if (thread == NULL) {
5470 return BAD_VALUE;
5471 }
5472
Steve Block3856b092011-10-20 11:56:00 +01005473 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005474
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005475 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005476 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005477 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005478 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5479 dupThread->removeOutputTrack((MixerThread *)thread.get());
5480 }
5481 }
5482 }
Glenn Kastena1117922012-01-26 10:53:32 -08005483 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005484 mPlaybackThreads.removeItem(output);
5485 }
5486 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005487 // The thread entity (active unit of execution) is no longer running here,
5488 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005489
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005490 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005491 AudioStreamOut *out = thread->clearOutput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005492 assert(out != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005493 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005494 out->hwDev->close_output_stream(out->hwDev, out->stream);
5495 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005496 }
5497 return NO_ERROR;
5498}
5499
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005500status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005501{
5502 Mutex::Autolock _l(mLock);
5503 PlaybackThread *thread = checkPlaybackThread_l(output);
5504
5505 if (thread == NULL) {
5506 return BAD_VALUE;
5507 }
5508
Steve Block3856b092011-10-20 11:56:00 +01005509 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005510 thread->suspend();
5511
5512 return NO_ERROR;
5513}
5514
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005515status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005516{
5517 Mutex::Autolock _l(mLock);
5518 PlaybackThread *thread = checkPlaybackThread_l(output);
5519
5520 if (thread == NULL) {
5521 return BAD_VALUE;
5522 }
5523
Steve Block3856b092011-10-20 11:56:00 +01005524 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005525
5526 thread->restore();
5527
5528 return NO_ERROR;
5529}
5530
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005531audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005532 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005533 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005534 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005535 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005536{
5537 status_t status;
5538 RecordThread *thread = NULL;
5539 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005540 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005541 uint32_t channels = pChannels ? *pChannels : 0;
5542 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005543 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005544 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005545 audio_stream_in_t *inStream;
5546 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005547
5548 if (pDevices == NULL || *pDevices == 0) {
5549 return 0;
5550 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005551
Mathias Agopian65ab4712010-07-14 17:59:35 -07005552 Mutex::Autolock _l(mLock);
5553
Dima Zavin799a70e2011-04-18 16:57:27 -07005554 inHwDev = findSuitableHwDev_l(*pDevices);
5555 if (inHwDev == NULL)
5556 return 0;
5557
Glenn Kasten58f30212012-01-12 12:27:51 -08005558 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005559 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005560 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005561 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005562 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005563 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005564 samplingRate,
5565 format,
5566 channels,
5567 acoustics,
5568 status);
5569
5570 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5571 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5572 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005573 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005574 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005575 (samplingRate <= 2 * reqSamplingRate) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08005576 (popcount(channels) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01005577 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005578 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005579 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005580 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005581 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005582 }
5583
Dima Zavin799a70e2011-04-18 16:57:27 -07005584 if (inStream != NULL) {
5585 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5586
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005587 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005588 // Start record thread
5589 // RecorThread require both input and output device indication to forward to audio
5590 // pre processing modules
5591 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5592 thread = new RecordThread(this,
5593 input,
5594 reqSamplingRate,
5595 reqChannels,
5596 id,
5597 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005598 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005599 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005600 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5601 if (pFormat != NULL) *pFormat = format;
5602 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005603
Dima Zavin799a70e2011-04-18 16:57:27 -07005604 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005605
5606 // notify client processes of the new input creation
5607 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5608 return id;
5609 }
5610
5611 return 0;
5612}
5613
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005614status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005615{
5616 // keep strong reference on the record thread so that
5617 // it is not destroyed while exit() is executed
5618 sp <RecordThread> thread;
5619 {
5620 Mutex::Autolock _l(mLock);
5621 thread = checkRecordThread_l(input);
5622 if (thread == NULL) {
5623 return BAD_VALUE;
5624 }
5625
Steve Block3856b092011-10-20 11:56:00 +01005626 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08005627 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005628 mRecordThreads.removeItem(input);
5629 }
5630 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005631 // The thread entity (active unit of execution) is no longer running here,
5632 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005633
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005634 AudioStreamIn *in = thread->clearInput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005635 assert(in != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005636 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005637 in->hwDev->close_input_stream(in->hwDev, in->stream);
5638 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005639
5640 return NO_ERROR;
5641}
5642
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005643status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005644{
5645 Mutex::Autolock _l(mLock);
5646 MixerThread *dstThread = checkMixerThread_l(output);
5647 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005648 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005649 return BAD_VALUE;
5650 }
5651
Steve Block3856b092011-10-20 11:56:00 +01005652 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005653 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5654
Eric Laurent9f6530f2011-08-30 10:18:54 -07005655 dstThread->setStreamValid(stream, true);
5656
Mathias Agopian65ab4712010-07-14 17:59:35 -07005657 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5658 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08005659 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005660 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005661 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005662 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005663 }
Eric Laurentde070132010-07-13 04:45:46 -07005664 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005665
5666 return NO_ERROR;
5667}
5668
5669
5670int AudioFlinger::newAudioSessionId()
5671{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005672 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005673}
5674
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005675void AudioFlinger::acquireAudioSessionId(int audioSession)
5676{
5677 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005678 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005679 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005680 size_t num = mAudioSessionRefs.size();
5681 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005682 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005683 if (ref->mSessionid == audioSession && ref->mPid == caller) {
5684 ref->mCnt++;
5685 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005686 return;
5687 }
5688 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005689 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5690 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005691}
5692
5693void AudioFlinger::releaseAudioSessionId(int audioSession)
5694{
5695 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005696 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005697 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005698 size_t num = mAudioSessionRefs.size();
5699 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005700 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005701 if (ref->mSessionid == audioSession && ref->mPid == caller) {
5702 ref->mCnt--;
5703 ALOGV(" decremented refcount to %d", ref->mCnt);
5704 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005705 mAudioSessionRefs.removeAt(i);
5706 delete ref;
5707 purgeStaleEffects_l();
5708 }
5709 return;
5710 }
5711 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005712 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005713}
5714
5715void AudioFlinger::purgeStaleEffects_l() {
5716
Steve Block3856b092011-10-20 11:56:00 +01005717 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005718
5719 Vector< sp<EffectChain> > chains;
5720
5721 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5722 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5723 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5724 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005725 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5726 chains.push(ec);
5727 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005728 }
5729 }
5730 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5731 sp<RecordThread> t = mRecordThreads.valueAt(i);
5732 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5733 sp<EffectChain> ec = t->mEffectChains[j];
5734 chains.push(ec);
5735 }
5736 }
5737
5738 for (size_t i = 0; i < chains.size(); i++) {
5739 sp<EffectChain> ec = chains[i];
5740 int sessionid = ec->sessionId();
5741 sp<ThreadBase> t = ec->mThread.promote();
5742 if (t == 0) {
5743 continue;
5744 }
5745 size_t numsessionrefs = mAudioSessionRefs.size();
5746 bool found = false;
5747 for (size_t k = 0; k < numsessionrefs; k++) {
5748 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005749 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005750 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005751 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005752 found = true;
5753 break;
5754 }
5755 }
5756 if (!found) {
5757 // remove all effects from the chain
5758 while (ec->mEffects.size()) {
5759 sp<EffectModule> effect = ec->mEffects[0];
5760 effect->unPin();
5761 Mutex::Autolock _l (t->mLock);
5762 t->removeEffect_l(effect);
5763 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5764 sp<EffectHandle> handle = effect->mHandles[j].promote();
5765 if (handle != 0) {
5766 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005767 if (handle->mHasControl && handle->mEnabled) {
5768 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5769 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005770 }
5771 }
5772 AudioSystem::unregisterEffect(effect->id());
5773 }
5774 }
5775 }
5776 return;
5777}
5778
Mathias Agopian65ab4712010-07-14 17:59:35 -07005779// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005780AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005781{
Glenn Kastena1117922012-01-26 10:53:32 -08005782 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005783}
5784
5785// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005786AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005787{
5788 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08005789 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005790}
5791
5792// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005793AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005794{
Glenn Kastena1117922012-01-26 10:53:32 -08005795 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005796}
5797
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005798uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005799{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005800 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005801}
5802
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08005803AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005804{
5805 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5806 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005807 AudioStreamOut *output = thread->getOutput();
5808 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005809 return thread;
5810 }
5811 }
5812 return NULL;
5813}
5814
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08005815uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005816{
5817 PlaybackThread *thread = primaryPlaybackThread_l();
5818
5819 if (thread == NULL) {
5820 return 0;
5821 }
5822
5823 return thread->device();
5824}
5825
5826
Mathias Agopian65ab4712010-07-14 17:59:35 -07005827// ----------------------------------------------------------------------------
5828// Effect management
5829// ----------------------------------------------------------------------------
5830
5831
Glenn Kastenf587ba52012-01-26 16:25:10 -08005832status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005833{
5834 Mutex::Autolock _l(mLock);
5835 return EffectQueryNumberEffects(numEffects);
5836}
5837
Glenn Kastenf587ba52012-01-26 16:25:10 -08005838status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005839{
5840 Mutex::Autolock _l(mLock);
5841 return EffectQueryEffect(index, descriptor);
5842}
5843
Glenn Kasten5e92a782012-01-30 07:40:52 -08005844status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08005845 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005846{
5847 Mutex::Autolock _l(mLock);
5848 return EffectGetDescriptor(pUuid, descriptor);
5849}
5850
5851
Mathias Agopian65ab4712010-07-14 17:59:35 -07005852sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5853 effect_descriptor_t *pDesc,
5854 const sp<IEffectClient>& effectClient,
5855 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005856 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005857 int sessionId,
5858 status_t *status,
5859 int *id,
5860 int *enabled)
5861{
5862 status_t lStatus = NO_ERROR;
5863 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005864 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005865
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005866 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005867 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005868
5869 if (pDesc == NULL) {
5870 lStatus = BAD_VALUE;
5871 goto Exit;
5872 }
5873
Eric Laurent84e9a102010-09-23 16:10:16 -07005874 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005875 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005876 lStatus = PERMISSION_DENIED;
5877 goto Exit;
5878 }
5879
Dima Zavinfce7a472011-04-19 22:30:36 -07005880 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005881 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08005882 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005883 lStatus = PERMISSION_DENIED;
5884 goto Exit;
5885 }
5886
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005887 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005888 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005889 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005890 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005891 lStatus = BAD_VALUE;
5892 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005893 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005894 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005895 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005896 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005897 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005898 }
5899 }
5900
Mathias Agopian65ab4712010-07-14 17:59:35 -07005901 {
5902 Mutex::Autolock _l(mLock);
5903
Mathias Agopian65ab4712010-07-14 17:59:35 -07005904
5905 if (!EffectIsNullUuid(&pDesc->uuid)) {
5906 // if uuid is specified, request effect descriptor
5907 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5908 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005909 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005910 goto Exit;
5911 }
5912 } else {
5913 // if uuid is not specified, look for an available implementation
5914 // of the required type in effect factory
5915 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005916 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005917 lStatus = BAD_VALUE;
5918 goto Exit;
5919 }
5920 uint32_t numEffects = 0;
5921 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005922 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005923 bool found = false;
5924
5925 lStatus = EffectQueryNumberEffects(&numEffects);
5926 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005927 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005928 goto Exit;
5929 }
5930 for (uint32_t i = 0; i < numEffects; i++) {
5931 lStatus = EffectQueryEffect(i, &desc);
5932 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005933 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005934 continue;
5935 }
5936 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5937 // If matching type found save effect descriptor. If the session is
5938 // 0 and the effect is not auxiliary, continue enumeration in case
5939 // an auxiliary version of this effect type is available
5940 found = true;
5941 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005942 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005943 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5944 break;
5945 }
5946 }
5947 }
5948 if (!found) {
5949 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00005950 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005951 goto Exit;
5952 }
5953 // For same effect type, chose auxiliary version over insert version if
5954 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005955 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005956 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5957 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5958 }
5959 }
5960
5961 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005962 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005963 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5964 lStatus = INVALID_OPERATION;
5965 goto Exit;
5966 }
5967
Eric Laurent59255e42011-07-27 19:49:51 -07005968 // check recording permission for visualizer
5969 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5970 !recordingAllowed()) {
5971 lStatus = PERMISSION_DENIED;
5972 goto Exit;
5973 }
5974
Mathias Agopian65ab4712010-07-14 17:59:35 -07005975 // return effect descriptor
5976 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5977
5978 // If output is not specified try to find a matching audio session ID in one of the
5979 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005980 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5981 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005982 // Note: io is never 0 when creating an effect on an input
5983 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005984 // look for the thread where the specified audio session is present
5985 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5986 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005987 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005988 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005989 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005990 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005991 if (io == 0) {
5992 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5993 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5994 io = mRecordThreads.keyAt(i);
5995 break;
5996 }
5997 }
5998 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005999 // If no output thread contains the requested session ID, default to
6000 // first output. The effect chain will be moved to the correct output
6001 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006002 if (io == 0 && mPlaybackThreads.size()) {
6003 io = mPlaybackThreads.keyAt(0);
6004 }
Steve Block3856b092011-10-20 11:56:00 +01006005 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006006 }
6007 ThreadBase *thread = checkRecordThread_l(io);
6008 if (thread == NULL) {
6009 thread = checkPlaybackThread_l(io);
6010 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00006011 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006012 lStatus = BAD_VALUE;
6013 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07006014 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006015 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006016
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006017 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006018
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006019 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07006020 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6021 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006022 if (handle != 0 && id != NULL) {
6023 *id = handle->id();
6024 }
6025 }
6026
6027Exit:
6028 if(status) {
6029 *status = lStatus;
6030 }
6031 return handle;
6032}
6033
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006034status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
6035 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07006036{
Steve Block3856b092011-10-20 11:56:00 +01006037 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07006038 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006039 Mutex::Autolock _l(mLock);
6040 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006041 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006042 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006043 }
Eric Laurentde070132010-07-13 04:45:46 -07006044 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6045 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006046 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006047 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006048 }
Eric Laurentde070132010-07-13 04:45:46 -07006049 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6050 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006051 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006052 return BAD_VALUE;
6053 }
6054
6055 Mutex::Autolock _dl(dstThread->mLock);
6056 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07006057 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07006058
Mathias Agopian65ab4712010-07-14 17:59:35 -07006059 return NO_ERROR;
6060}
6061
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006062// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07006063status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07006064 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07006065 AudioFlinger::PlaybackThread *dstThread,
6066 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07006067{
Steve Block3856b092011-10-20 11:56:00 +01006068 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006069 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07006070
Eric Laurent59255e42011-07-27 19:49:51 -07006071 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006072 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006073 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006074 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07006075 return INVALID_OPERATION;
6076 }
6077
Eric Laurent39e94f82010-07-28 01:32:47 -07006078 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07006079 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07006080 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07006081 // removed.
6082 srcThread->removeEffectChain_l(chain);
6083
6084 // transfer all effects one by one so that new effect chain is created on new thread with
6085 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006086 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07006087 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006088 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07006089 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6090 while (effect != 0) {
6091 srcThread->removeEffect_l(effect);
6092 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07006093 // removeEffect_l() has stopped the effect if it was active so it must be restarted
6094 if (effect->state() == EffectModule::ACTIVE ||
6095 effect->state() == EffectModule::STOPPING) {
6096 effect->start();
6097 }
Eric Laurent39e94f82010-07-28 01:32:47 -07006098 // if the move request is not received from audio policy manager, the effect must be
6099 // re-registered with the new strategy and output
6100 if (dstChain == 0) {
6101 dstChain = effect->chain().promote();
6102 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006103 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07006104 srcThread->addEffect_l(effect);
6105 return NO_INIT;
6106 }
6107 strategy = dstChain->strategy();
6108 }
6109 if (reRegister) {
6110 AudioSystem::unregisterEffect(effect->id());
6111 AudioSystem::registerEffect(&effect->desc(),
6112 dstOutput,
6113 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07006114 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07006115 effect->id());
6116 }
Eric Laurentde070132010-07-13 04:45:46 -07006117 effect = chain->getEffectFromId_l(0);
6118 }
6119
6120 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006121}
6122
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006123
Mathias Agopian65ab4712010-07-14 17:59:35 -07006124// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006125sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07006126 const sp<AudioFlinger::Client>& client,
6127 const sp<IEffectClient>& effectClient,
6128 int32_t priority,
6129 int sessionId,
6130 effect_descriptor_t *desc,
6131 int *enabled,
6132 status_t *status
6133 )
6134{
6135 sp<EffectModule> effect;
6136 sp<EffectHandle> handle;
6137 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006138 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07006139 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006140 bool effectCreated = false;
6141 bool effectRegistered = false;
6142
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006143 lStatus = initCheck();
6144 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006145 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006146 goto Exit;
6147 }
6148
6149 // Do not allow effects with session ID 0 on direct output or duplicating threads
6150 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07006151 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006152 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07006153 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006154 lStatus = BAD_VALUE;
6155 goto Exit;
6156 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006157 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08006158 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006159 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006160 desc->name, desc->flags, mType);
6161 lStatus = BAD_VALUE;
6162 goto Exit;
6163 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006164
Steve Block3856b092011-10-20 11:56:00 +01006165 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006166
6167 { // scope for mLock
6168 Mutex::Autolock _l(mLock);
6169
6170 // check for existing effect chain with the requested audio session
6171 chain = getEffectChain_l(sessionId);
6172 if (chain == 0) {
6173 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006174 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006175 chain = new EffectChain(this, sessionId);
6176 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07006177 chain->setStrategy(getStrategyForSession_l(sessionId));
6178 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006179 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07006180 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006181 }
6182
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08006183 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006184
6185 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006186 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006187 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07006188 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006189 if (lStatus != NO_ERROR) {
6190 goto Exit;
6191 }
6192 effectRegistered = true;
6193 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07006194 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006195 lStatus = effect->status();
6196 if (lStatus != NO_ERROR) {
6197 goto Exit;
6198 }
Eric Laurentcab11242010-07-15 12:50:15 -07006199 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006200 if (lStatus != NO_ERROR) {
6201 goto Exit;
6202 }
6203 effectCreated = true;
6204
6205 effect->setDevice(mDevice);
6206 effect->setMode(mAudioFlinger->getMode());
6207 }
6208 // create effect handle and connect it to effect module
6209 handle = new EffectHandle(effect, client, effectClient, priority);
6210 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08006211 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006212 *enabled = (int)effect->isEnabled();
6213 }
6214 }
6215
6216Exit:
6217 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07006218 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006219 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07006220 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006221 }
6222 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07006223 AudioSystem::unregisterEffect(effect->id());
6224 }
6225 if (chainCreated) {
6226 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006227 }
6228 handle.clear();
6229 }
6230
6231 if(status) {
6232 *status = lStatus;
6233 }
6234 return handle;
6235}
6236
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006237sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6238{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006239 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08006240 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006241}
6242
Eric Laurentde070132010-07-13 04:45:46 -07006243// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6244// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006245status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07006246{
6247 // check for existing effect chain with the requested audio session
6248 int sessionId = effect->sessionId();
6249 sp<EffectChain> chain = getEffectChain_l(sessionId);
6250 bool chainCreated = false;
6251
6252 if (chain == 0) {
6253 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006254 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006255 chain = new EffectChain(this, sessionId);
6256 addEffectChain_l(chain);
6257 chain->setStrategy(getStrategyForSession_l(sessionId));
6258 chainCreated = true;
6259 }
Steve Block3856b092011-10-20 11:56:00 +01006260 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006261
6262 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006263 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07006264 this, effect->desc().name, chain.get());
6265 return BAD_VALUE;
6266 }
6267
6268 status_t status = chain->addEffect_l(effect);
6269 if (status != NO_ERROR) {
6270 if (chainCreated) {
6271 removeEffectChain_l(chain);
6272 }
6273 return status;
6274 }
6275
6276 effect->setDevice(mDevice);
6277 effect->setMode(mAudioFlinger->getMode());
6278 return NO_ERROR;
6279}
6280
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006281void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07006282
Steve Block3856b092011-10-20 11:56:00 +01006283 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006284 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07006285 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6286 detachAuxEffect_l(effect->id());
6287 }
6288
6289 sp<EffectChain> chain = effect->chain().promote();
6290 if (chain != 0) {
6291 // remove effect chain if removing last effect
6292 if (chain->removeEffect_l(effect) == 0) {
6293 removeEffectChain_l(chain);
6294 }
6295 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00006296 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006297 }
6298}
6299
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006300void AudioFlinger::ThreadBase::lockEffectChains_l(
6301 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
6302{
6303 effectChains = mEffectChains;
6304 for (size_t i = 0; i < mEffectChains.size(); i++) {
6305 mEffectChains[i]->lock();
6306 }
6307}
6308
6309void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006310 const Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006311{
6312 for (size_t i = 0; i < effectChains.size(); i++) {
6313 effectChains[i]->unlock();
6314 }
6315}
6316
6317sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6318{
6319 Mutex::Autolock _l(mLock);
6320 return getEffectChain_l(sessionId);
6321}
6322
6323sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6324{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006325 size_t size = mEffectChains.size();
6326 for (size_t i = 0; i < size; i++) {
6327 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08006328 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006329 }
6330 }
Glenn Kasten090f0192012-01-30 13:00:02 -08006331 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006332}
6333
Glenn Kastenf78aee72012-01-04 11:00:47 -08006334void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006335{
6336 Mutex::Autolock _l(mLock);
6337 size_t size = mEffectChains.size();
6338 for (size_t i = 0; i < size; i++) {
6339 mEffectChains[i]->setMode_l(mode);
6340 }
6341}
6342
6343void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006344 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08006345 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07006346
Mathias Agopian65ab4712010-07-14 17:59:35 -07006347 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006348 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006349 // delete the effect module if removing last handle on it
6350 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006351 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006352 removeEffect_l(effect);
6353 AudioSystem::unregisterEffect(effect->id());
6354 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006355 }
6356}
6357
6358status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6359{
6360 int session = chain->sessionId();
6361 int16_t *buffer = mMixBuffer;
6362 bool ownsBuffer = false;
6363
Steve Block3856b092011-10-20 11:56:00 +01006364 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006365 if (session > 0) {
6366 // Only one effect chain can be present in direct output thread and it uses
6367 // the mix buffer as input
6368 if (mType != DIRECT) {
6369 size_t numSamples = mFrameCount * mChannelCount;
6370 buffer = new int16_t[numSamples];
6371 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01006372 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006373 ownsBuffer = true;
6374 }
6375
6376 // Attach all tracks with same session ID to this chain.
6377 for (size_t i = 0; i < mTracks.size(); ++i) {
6378 sp<Track> track = mTracks[i];
6379 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006380 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006381 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006382 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006383 }
6384 }
6385
6386 // indicate all active tracks in the chain
6387 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6388 sp<Track> track = mActiveTracks[i].promote();
6389 if (track == 0) continue;
6390 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006391 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07006392 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006393 }
6394 }
6395 }
6396
6397 chain->setInBuffer(buffer, ownsBuffer);
6398 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006399 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006400 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006401 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6402 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006403 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006404 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6405 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006406 // Effect chain for other sessions are inserted at beginning of effect
6407 // chains list to be processed before output mix effects. Relative order between other
6408 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006409 size_t size = mEffectChains.size();
6410 size_t i = 0;
6411 for (i = 0; i < size; i++) {
6412 if (mEffectChains[i]->sessionId() < session) break;
6413 }
6414 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006415 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006416
6417 return NO_ERROR;
6418}
6419
6420size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6421{
6422 int session = chain->sessionId();
6423
Steve Block3856b092011-10-20 11:56:00 +01006424 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006425
6426 for (size_t i = 0; i < mEffectChains.size(); i++) {
6427 if (chain == mEffectChains[i]) {
6428 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006429 // detach all active tracks from the chain
6430 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6431 sp<Track> track = mActiveTracks[i].promote();
6432 if (track == 0) continue;
6433 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006434 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006435 chain.get(), session);
6436 chain->decActiveTrackCnt();
6437 }
6438 }
6439
Mathias Agopian65ab4712010-07-14 17:59:35 -07006440 // detach all tracks with same session ID from this chain
6441 for (size_t i = 0; i < mTracks.size(); ++i) {
6442 sp<Track> track = mTracks[i];
6443 if (session == track->sessionId()) {
6444 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006445 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006446 }
6447 }
Eric Laurentde070132010-07-13 04:45:46 -07006448 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006449 }
6450 }
6451 return mEffectChains.size();
6452}
6453
Eric Laurentde070132010-07-13 04:45:46 -07006454status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6455 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006456{
6457 Mutex::Autolock _l(mLock);
6458 return attachAuxEffect_l(track, EffectId);
6459}
6460
Eric Laurentde070132010-07-13 04:45:46 -07006461status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6462 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006463{
6464 status_t status = NO_ERROR;
6465
6466 if (EffectId == 0) {
6467 track->setAuxBuffer(0, NULL);
6468 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006469 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6470 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006471 if (effect != 0) {
6472 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6473 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6474 } else {
6475 status = INVALID_OPERATION;
6476 }
6477 } else {
6478 status = BAD_VALUE;
6479 }
6480 }
6481 return status;
6482}
6483
6484void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6485{
6486 for (size_t i = 0; i < mTracks.size(); ++i) {
6487 sp<Track> track = mTracks[i];
6488 if (track->auxEffectId() == effectId) {
6489 attachAuxEffect_l(track, 0);
6490 }
6491 }
6492}
6493
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006494status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6495{
6496 // only one chain per input thread
6497 if (mEffectChains.size() != 0) {
6498 return INVALID_OPERATION;
6499 }
Steve Block3856b092011-10-20 11:56:00 +01006500 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006501
6502 chain->setInBuffer(NULL);
6503 chain->setOutBuffer(NULL);
6504
Eric Laurent59255e42011-07-27 19:49:51 -07006505 checkSuspendOnAddEffectChain_l(chain);
6506
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006507 mEffectChains.add(chain);
6508
6509 return NO_ERROR;
6510}
6511
6512size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6513{
Steve Block3856b092011-10-20 11:56:00 +01006514 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006515 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006516 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6517 chain.get(), mEffectChains.size(), this);
6518 if (mEffectChains.size() == 1) {
6519 mEffectChains.removeAt(0);
6520 }
6521 return 0;
6522}
6523
Mathias Agopian65ab4712010-07-14 17:59:35 -07006524// ----------------------------------------------------------------------------
6525// EffectModule implementation
6526// ----------------------------------------------------------------------------
6527
6528#undef LOG_TAG
6529#define LOG_TAG "AudioFlinger::EffectModule"
6530
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006531AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006532 const wp<AudioFlinger::EffectChain>& chain,
6533 effect_descriptor_t *desc,
6534 int id,
6535 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006536 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006537 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006538{
Steve Block3856b092011-10-20 11:56:00 +01006539 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006540 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006541 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006542 return;
6543 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006544
6545 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6546
6547 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006548 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006549
6550 if (mStatus != NO_ERROR) {
6551 return;
6552 }
6553 lStatus = init();
6554 if (lStatus < 0) {
6555 mStatus = lStatus;
6556 goto Error;
6557 }
6558
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006559 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6560 mPinned = true;
6561 }
Steve Block3856b092011-10-20 11:56:00 +01006562 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006563 return;
6564Error:
6565 EffectRelease(mEffectInterface);
6566 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006567 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006568}
6569
6570AudioFlinger::EffectModule::~EffectModule()
6571{
Steve Block3856b092011-10-20 11:56:00 +01006572 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006573 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006574 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6575 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6576 sp<ThreadBase> thread = mThread.promote();
6577 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006578 audio_stream_t *stream = thread->stream();
6579 if (stream != NULL) {
6580 stream->remove_audio_effect(stream, mEffectInterface);
6581 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006582 }
6583 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006584 // release effect engine
6585 EffectRelease(mEffectInterface);
6586 }
6587}
6588
Glenn Kasten435dbe62012-01-30 10:15:48 -08006589status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006590{
6591 status_t status;
6592
6593 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006594 int priority = handle->priority();
6595 size_t size = mHandles.size();
6596 sp<EffectHandle> h;
6597 size_t i;
6598 for (i = 0; i < size; i++) {
6599 h = mHandles[i].promote();
6600 if (h == 0) continue;
6601 if (h->priority() <= priority) break;
6602 }
6603 // if inserted in first place, move effect control from previous owner to this handle
6604 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006605 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006606 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006607 enabled = h->enabled();
6608 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006609 }
Eric Laurent59255e42011-07-27 19:49:51 -07006610 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006611 status = NO_ERROR;
6612 } else {
6613 status = ALREADY_EXISTS;
6614 }
Steve Block3856b092011-10-20 11:56:00 +01006615 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006616 mHandles.insertAt(handle, i);
6617 return status;
6618}
6619
6620size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6621{
6622 Mutex::Autolock _l(mLock);
6623 size_t size = mHandles.size();
6624 size_t i;
6625 for (i = 0; i < size; i++) {
6626 if (mHandles[i] == handle) break;
6627 }
6628 if (i == size) {
6629 return size;
6630 }
Steve Block3856b092011-10-20 11:56:00 +01006631 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006632
6633 bool enabled = false;
6634 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006635 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006636 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006637 enabled = hdl->enabled();
6638 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006639 mHandles.removeAt(i);
6640 size = mHandles.size();
6641 // if removed from first place, move effect control from this handle to next in line
6642 if (i == 0 && size != 0) {
6643 sp<EffectHandle> h = mHandles[0].promote();
6644 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006645 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006646 }
6647 }
6648
Eric Laurentec437d82011-07-26 20:54:46 -07006649 // Prevent calls to process() and other functions on effect interface from now on.
6650 // The effect engine will be released by the destructor when the last strong reference on
6651 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006652 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006653 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006654 }
6655
Mathias Agopian65ab4712010-07-14 17:59:35 -07006656 return size;
6657}
6658
Eric Laurent59255e42011-07-27 19:49:51 -07006659sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6660{
6661 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08006662 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07006663}
6664
Glenn Kasten58123c32012-02-03 10:32:24 -08006665void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006666{
Glenn Kasten90bebef2012-01-27 15:24:38 -08006667 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006668 // keep a strong reference on this EffectModule to avoid calling the
6669 // destructor before we exit
6670 sp<EffectModule> keep(this);
6671 {
6672 sp<ThreadBase> thread = mThread.promote();
6673 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006674 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006675 }
6676 }
6677}
6678
6679void AudioFlinger::EffectModule::updateState() {
6680 Mutex::Autolock _l(mLock);
6681
6682 switch (mState) {
6683 case RESTART:
6684 reset_l();
6685 // FALL THROUGH
6686
6687 case STARTING:
6688 // clear auxiliary effect input buffer for next accumulation
6689 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6690 memset(mConfig.inputCfg.buffer.raw,
6691 0,
6692 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6693 }
6694 start_l();
6695 mState = ACTIVE;
6696 break;
6697 case STOPPING:
6698 stop_l();
6699 mDisableWaitCnt = mMaxDisableWaitCnt;
6700 mState = STOPPED;
6701 break;
6702 case STOPPED:
6703 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6704 // turn off sequence.
6705 if (--mDisableWaitCnt == 0) {
6706 reset_l();
6707 mState = IDLE;
6708 }
6709 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006710 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006711 break;
6712 }
6713}
6714
6715void AudioFlinger::EffectModule::process()
6716{
6717 Mutex::Autolock _l(mLock);
6718
Eric Laurentec437d82011-07-26 20:54:46 -07006719 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006720 mConfig.inputCfg.buffer.raw == NULL ||
6721 mConfig.outputCfg.buffer.raw == NULL) {
6722 return;
6723 }
6724
Eric Laurent8f45bd72010-08-31 13:50:07 -07006725 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006726 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6727 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006728 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006729 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006730 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006731 }
6732
6733 // do the actual processing in the effect engine
6734 int ret = (*mEffectInterface)->process(mEffectInterface,
6735 &mConfig.inputCfg.buffer,
6736 &mConfig.outputCfg.buffer);
6737
6738 // force transition to IDLE state when engine is ready
6739 if (mState == STOPPED && ret == -ENODATA) {
6740 mDisableWaitCnt = 1;
6741 }
6742
6743 // clear auxiliary effect input buffer for next accumulation
6744 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006745 memset(mConfig.inputCfg.buffer.raw, 0,
6746 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006747 }
6748 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006749 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6750 // If an insert effect is idle and input buffer is different from output buffer,
6751 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006752 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006753 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006754 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6755 int16_t *in = mConfig.inputCfg.buffer.s16;
6756 int16_t *out = mConfig.outputCfg.buffer.s16;
6757 for (size_t i = 0; i < frameCnt; i++) {
6758 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006759 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006760 }
6761 }
6762}
6763
6764void AudioFlinger::EffectModule::reset_l()
6765{
6766 if (mEffectInterface == NULL) {
6767 return;
6768 }
6769 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6770}
6771
6772status_t AudioFlinger::EffectModule::configure()
6773{
6774 uint32_t channels;
6775 if (mEffectInterface == NULL) {
6776 return NO_INIT;
6777 }
6778
6779 sp<ThreadBase> thread = mThread.promote();
6780 if (thread == 0) {
6781 return DEAD_OBJECT;
6782 }
6783
6784 // TODO: handle configuration of effects replacing track process
6785 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006786 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006787 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006788 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006789 }
6790
6791 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006792 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006793 } else {
6794 mConfig.inputCfg.channels = channels;
6795 }
6796 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006797 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6798 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006799 mConfig.inputCfg.samplingRate = thread->sampleRate();
6800 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6801 mConfig.inputCfg.bufferProvider.cookie = NULL;
6802 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6803 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6804 mConfig.outputCfg.bufferProvider.cookie = NULL;
6805 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6806 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6807 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6808 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006809 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006810 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006811 // - in other sessions:
6812 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6813 // other effect: overwrites output buffer: input buffer == output buffer
6814 // Auxiliary effect:
6815 // accumulates in output buffer: input buffer != output buffer
6816 // Therefore: accumulate <=> input buffer != output buffer
6817 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6818 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6819 } else {
6820 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6821 }
6822 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6823 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6824 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6825 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6826
Steve Block3856b092011-10-20 11:56:00 +01006827 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006828 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6829
Mathias Agopian65ab4712010-07-14 17:59:35 -07006830 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006831 uint32_t size = sizeof(int);
6832 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006833 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006834 sizeof(effect_config_t),
6835 &mConfig,
6836 &size,
6837 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006838 if (status == 0) {
6839 status = cmdStatus;
6840 }
6841
6842 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6843 (1000 * mConfig.outputCfg.buffer.frameCount);
6844
6845 return status;
6846}
6847
6848status_t AudioFlinger::EffectModule::init()
6849{
6850 Mutex::Autolock _l(mLock);
6851 if (mEffectInterface == NULL) {
6852 return NO_INIT;
6853 }
6854 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006855 uint32_t size = sizeof(status_t);
6856 status_t status = (*mEffectInterface)->command(mEffectInterface,
6857 EFFECT_CMD_INIT,
6858 0,
6859 NULL,
6860 &size,
6861 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006862 if (status == 0) {
6863 status = cmdStatus;
6864 }
6865 return status;
6866}
6867
Eric Laurentec35a142011-10-05 17:42:25 -07006868status_t AudioFlinger::EffectModule::start()
6869{
6870 Mutex::Autolock _l(mLock);
6871 return start_l();
6872}
6873
Mathias Agopian65ab4712010-07-14 17:59:35 -07006874status_t AudioFlinger::EffectModule::start_l()
6875{
6876 if (mEffectInterface == NULL) {
6877 return NO_INIT;
6878 }
6879 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006880 uint32_t size = sizeof(status_t);
6881 status_t status = (*mEffectInterface)->command(mEffectInterface,
6882 EFFECT_CMD_ENABLE,
6883 0,
6884 NULL,
6885 &size,
6886 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006887 if (status == 0) {
6888 status = cmdStatus;
6889 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006890 if (status == 0 &&
6891 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6892 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6893 sp<ThreadBase> thread = mThread.promote();
6894 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006895 audio_stream_t *stream = thread->stream();
6896 if (stream != NULL) {
6897 stream->add_audio_effect(stream, mEffectInterface);
6898 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006899 }
6900 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006901 return status;
6902}
6903
Eric Laurentec437d82011-07-26 20:54:46 -07006904status_t AudioFlinger::EffectModule::stop()
6905{
6906 Mutex::Autolock _l(mLock);
6907 return stop_l();
6908}
6909
Mathias Agopian65ab4712010-07-14 17:59:35 -07006910status_t AudioFlinger::EffectModule::stop_l()
6911{
6912 if (mEffectInterface == NULL) {
6913 return NO_INIT;
6914 }
6915 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006916 uint32_t size = sizeof(status_t);
6917 status_t status = (*mEffectInterface)->command(mEffectInterface,
6918 EFFECT_CMD_DISABLE,
6919 0,
6920 NULL,
6921 &size,
6922 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006923 if (status == 0) {
6924 status = cmdStatus;
6925 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006926 if (status == 0 &&
6927 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6928 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6929 sp<ThreadBase> thread = mThread.promote();
6930 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006931 audio_stream_t *stream = thread->stream();
6932 if (stream != NULL) {
6933 stream->remove_audio_effect(stream, mEffectInterface);
6934 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006935 }
6936 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006937 return status;
6938}
6939
Eric Laurent25f43952010-07-28 05:40:18 -07006940status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6941 uint32_t cmdSize,
6942 void *pCmdData,
6943 uint32_t *replySize,
6944 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006945{
6946 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006947// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006948
Eric Laurentec437d82011-07-26 20:54:46 -07006949 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006950 return NO_INIT;
6951 }
Eric Laurent25f43952010-07-28 05:40:18 -07006952 status_t status = (*mEffectInterface)->command(mEffectInterface,
6953 cmdCode,
6954 cmdSize,
6955 pCmdData,
6956 replySize,
6957 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006958 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006959 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006960 for (size_t i = 1; i < mHandles.size(); i++) {
6961 sp<EffectHandle> h = mHandles[i].promote();
6962 if (h != 0) {
6963 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6964 }
6965 }
6966 }
6967 return status;
6968}
6969
6970status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6971{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006972
Mathias Agopian65ab4712010-07-14 17:59:35 -07006973 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006974 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006975
6976 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006977 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6978 if (enabled && status != NO_ERROR) {
6979 return status;
6980 }
6981
Mathias Agopian65ab4712010-07-14 17:59:35 -07006982 switch (mState) {
6983 // going from disabled to enabled
6984 case IDLE:
6985 mState = STARTING;
6986 break;
6987 case STOPPED:
6988 mState = RESTART;
6989 break;
6990 case STOPPING:
6991 mState = ACTIVE;
6992 break;
6993
6994 // going from enabled to disabled
6995 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006996 mState = STOPPED;
6997 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006998 case STARTING:
6999 mState = IDLE;
7000 break;
7001 case ACTIVE:
7002 mState = STOPPING;
7003 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007004 case DESTROYED:
7005 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007006 }
7007 for (size_t i = 1; i < mHandles.size(); i++) {
7008 sp<EffectHandle> h = mHandles[i].promote();
7009 if (h != 0) {
7010 h->setEnabled(enabled);
7011 }
7012 }
7013 }
7014 return NO_ERROR;
7015}
7016
Glenn Kastenc59c0042012-02-02 14:06:11 -08007017bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007018{
7019 switch (mState) {
7020 case RESTART:
7021 case STARTING:
7022 case ACTIVE:
7023 return true;
7024 case IDLE:
7025 case STOPPING:
7026 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07007027 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07007028 default:
7029 return false;
7030 }
7031}
7032
Glenn Kastenc59c0042012-02-02 14:06:11 -08007033bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07007034{
7035 switch (mState) {
7036 case RESTART:
7037 case ACTIVE:
7038 case STOPPING:
7039 case STOPPED:
7040 return true;
7041 case IDLE:
7042 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07007043 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007044 default:
7045 return false;
7046 }
7047}
7048
Mathias Agopian65ab4712010-07-14 17:59:35 -07007049status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7050{
7051 Mutex::Autolock _l(mLock);
7052 status_t status = NO_ERROR;
7053
7054 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7055 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07007056 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07007057 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7058 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007059 status_t cmdStatus;
7060 uint32_t volume[2];
7061 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07007062 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007063 volume[0] = *left;
7064 volume[1] = *right;
7065 if (controller) {
7066 pVolume = volume;
7067 }
Eric Laurent25f43952010-07-28 05:40:18 -07007068 status = (*mEffectInterface)->command(mEffectInterface,
7069 EFFECT_CMD_SET_VOLUME,
7070 size,
7071 volume,
7072 &size,
7073 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007074 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7075 *left = volume[0];
7076 *right = volume[1];
7077 }
7078 }
7079 return status;
7080}
7081
7082status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7083{
7084 Mutex::Autolock _l(mLock);
7085 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007086 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7087 // audio pre processing modules on RecordThread can receive both output and
7088 // input device indication in the same call
7089 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7090 if (dev) {
7091 status_t cmdStatus;
7092 uint32_t size = sizeof(status_t);
7093
7094 status = (*mEffectInterface)->command(mEffectInterface,
7095 EFFECT_CMD_SET_DEVICE,
7096 sizeof(uint32_t),
7097 &dev,
7098 &size,
7099 &cmdStatus);
7100 if (status == NO_ERROR) {
7101 status = cmdStatus;
7102 }
7103 }
7104 dev = device & AUDIO_DEVICE_IN_ALL;
7105 if (dev) {
7106 status_t cmdStatus;
7107 uint32_t size = sizeof(status_t);
7108
7109 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7110 EFFECT_CMD_SET_INPUT_DEVICE,
7111 sizeof(uint32_t),
7112 &dev,
7113 &size,
7114 &cmdStatus);
7115 if (status2 == NO_ERROR) {
7116 status2 = cmdStatus;
7117 }
7118 if (status == NO_ERROR) {
7119 status = status2;
7120 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007121 }
7122 }
7123 return status;
7124}
7125
Glenn Kastenf78aee72012-01-04 11:00:47 -08007126status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007127{
7128 Mutex::Autolock _l(mLock);
7129 status_t status = NO_ERROR;
7130 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007131 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007132 uint32_t size = sizeof(status_t);
7133 status = (*mEffectInterface)->command(mEffectInterface,
7134 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08007135 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07007136 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07007137 &size,
7138 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007139 if (status == NO_ERROR) {
7140 status = cmdStatus;
7141 }
7142 }
7143 return status;
7144}
7145
Eric Laurent59255e42011-07-27 19:49:51 -07007146void AudioFlinger::EffectModule::setSuspended(bool suspended)
7147{
7148 Mutex::Autolock _l(mLock);
7149 mSuspended = suspended;
7150}
Glenn Kastena3a85482012-01-04 11:01:11 -08007151
7152bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07007153{
7154 Mutex::Autolock _l(mLock);
7155 return mSuspended;
7156}
7157
Mathias Agopian65ab4712010-07-14 17:59:35 -07007158status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7159{
7160 const size_t SIZE = 256;
7161 char buffer[SIZE];
7162 String8 result;
7163
7164 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7165 result.append(buffer);
7166
7167 bool locked = tryLock(mLock);
7168 // failed to lock - AudioFlinger is probably deadlocked
7169 if (!locked) {
7170 result.append("\t\tCould not lock Fx mutex:\n");
7171 }
7172
7173 result.append("\t\tSession Status State Engine:\n");
7174 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7175 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7176 result.append(buffer);
7177
7178 result.append("\t\tDescriptor:\n");
7179 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7180 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7181 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7182 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7183 result.append(buffer);
7184 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7185 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7186 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7187 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7188 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07007189 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007190 mDescriptor.apiVersion,
7191 mDescriptor.flags);
7192 result.append(buffer);
7193 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7194 mDescriptor.name);
7195 result.append(buffer);
7196 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7197 mDescriptor.implementor);
7198 result.append(buffer);
7199
7200 result.append("\t\t- Input configuration:\n");
7201 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7202 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7203 (uint32_t)mConfig.inputCfg.buffer.raw,
7204 mConfig.inputCfg.buffer.frameCount,
7205 mConfig.inputCfg.samplingRate,
7206 mConfig.inputCfg.channels,
7207 mConfig.inputCfg.format);
7208 result.append(buffer);
7209
7210 result.append("\t\t- Output configuration:\n");
7211 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7212 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7213 (uint32_t)mConfig.outputCfg.buffer.raw,
7214 mConfig.outputCfg.buffer.frameCount,
7215 mConfig.outputCfg.samplingRate,
7216 mConfig.outputCfg.channels,
7217 mConfig.outputCfg.format);
7218 result.append(buffer);
7219
7220 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7221 result.append(buffer);
7222 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7223 for (size_t i = 0; i < mHandles.size(); ++i) {
7224 sp<EffectHandle> handle = mHandles[i].promote();
7225 if (handle != 0) {
7226 handle->dump(buffer, SIZE);
7227 result.append(buffer);
7228 }
7229 }
7230
7231 result.append("\n");
7232
7233 write(fd, result.string(), result.length());
7234
7235 if (locked) {
7236 mLock.unlock();
7237 }
7238
7239 return NO_ERROR;
7240}
7241
7242// ----------------------------------------------------------------------------
7243// EffectHandle implementation
7244// ----------------------------------------------------------------------------
7245
7246#undef LOG_TAG
7247#define LOG_TAG "AudioFlinger::EffectHandle"
7248
7249AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7250 const sp<AudioFlinger::Client>& client,
7251 const sp<IEffectClient>& effectClient,
7252 int32_t priority)
7253 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007254 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007255 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007256{
Steve Block3856b092011-10-20 11:56:00 +01007257 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007258
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007259 if (client == 0) {
7260 return;
7261 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007262 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7263 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7264 if (mCblkMemory != 0) {
7265 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7266
Glenn Kastena0d68332012-01-27 16:47:15 -08007267 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007268 new(mCblk) effect_param_cblk_t();
7269 mBuffer = (uint8_t *)mCblk + bufOffset;
7270 }
7271 } else {
Steve Block29357bc2012-01-06 19:20:56 +00007272 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007273 return;
7274 }
7275}
7276
7277AudioFlinger::EffectHandle::~EffectHandle()
7278{
Steve Block3856b092011-10-20 11:56:00 +01007279 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007280 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01007281 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007282}
7283
7284status_t AudioFlinger::EffectHandle::enable()
7285{
Steve Block3856b092011-10-20 11:56:00 +01007286 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007287 if (!mHasControl) return INVALID_OPERATION;
7288 if (mEffect == 0) return DEAD_OBJECT;
7289
Eric Laurentdb7c0792011-08-10 10:37:50 -07007290 if (mEnabled) {
7291 return NO_ERROR;
7292 }
7293
Eric Laurent59255e42011-07-27 19:49:51 -07007294 mEnabled = true;
7295
7296 sp<ThreadBase> thread = mEffect->thread().promote();
7297 if (thread != 0) {
7298 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7299 }
7300
7301 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7302 if (mEffect->suspended()) {
7303 return NO_ERROR;
7304 }
7305
Eric Laurentdb7c0792011-08-10 10:37:50 -07007306 status_t status = mEffect->setEnabled(true);
7307 if (status != NO_ERROR) {
7308 if (thread != 0) {
7309 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7310 }
7311 mEnabled = false;
7312 }
7313 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007314}
7315
7316status_t AudioFlinger::EffectHandle::disable()
7317{
Steve Block3856b092011-10-20 11:56:00 +01007318 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007319 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07007320 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007321
Eric Laurentdb7c0792011-08-10 10:37:50 -07007322 if (!mEnabled) {
7323 return NO_ERROR;
7324 }
Eric Laurent59255e42011-07-27 19:49:51 -07007325 mEnabled = false;
7326
7327 if (mEffect->suspended()) {
7328 return NO_ERROR;
7329 }
7330
7331 status_t status = mEffect->setEnabled(false);
7332
7333 sp<ThreadBase> thread = mEffect->thread().promote();
7334 if (thread != 0) {
7335 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7336 }
7337
7338 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007339}
7340
7341void AudioFlinger::EffectHandle::disconnect()
7342{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007343 disconnect(true);
7344}
7345
Glenn Kasten58123c32012-02-03 10:32:24 -08007346void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007347{
Glenn Kasten58123c32012-02-03 10:32:24 -08007348 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007349 if (mEffect == 0) {
7350 return;
7351 }
Glenn Kasten58123c32012-02-03 10:32:24 -08007352 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07007353
Eric Laurenta85a74a2011-10-19 11:44:54 -07007354 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007355 sp<ThreadBase> thread = mEffect->thread().promote();
7356 if (thread != 0) {
7357 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7358 }
Eric Laurent59255e42011-07-27 19:49:51 -07007359 }
7360
Mathias Agopian65ab4712010-07-14 17:59:35 -07007361 // release sp on module => module destructor can be called now
7362 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007363 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08007364 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08007365 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007366 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7367 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08007368 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007369 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07007370 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7371 mClient.clear();
7372 }
7373}
7374
Eric Laurent25f43952010-07-28 05:40:18 -07007375status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7376 uint32_t cmdSize,
7377 void *pCmdData,
7378 uint32_t *replySize,
7379 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007380{
Steve Block3856b092011-10-20 11:56:00 +01007381// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07007382// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007383
7384 // only get parameter command is permitted for applications not controlling the effect
7385 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7386 return INVALID_OPERATION;
7387 }
7388 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007389 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007390
7391 // handle commands that are not forwarded transparently to effect engine
7392 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7393 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7394 // no risk to block the whole media server process or mixer threads is we are stuck here
7395 Mutex::Autolock _l(mCblk->lock);
7396 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7397 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7398 mCblk->serverIndex = 0;
7399 mCblk->clientIndex = 0;
7400 return BAD_VALUE;
7401 }
7402 status_t status = NO_ERROR;
7403 while (mCblk->serverIndex < mCblk->clientIndex) {
7404 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007405 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007406 int *p = (int *)(mBuffer + mCblk->serverIndex);
7407 int size = *p++;
7408 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007409 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007410 break;
7411 }
7412 effect_param_t *param = (effect_param_t *)p;
7413 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007414 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007415 mCblk->serverIndex += size;
7416 continue;
7417 }
Eric Laurent25f43952010-07-28 05:40:18 -07007418 uint32_t psize = sizeof(effect_param_t) +
7419 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7420 param->vsize;
7421 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7422 psize,
7423 p,
7424 &rsize,
7425 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007426 // stop at first error encountered
7427 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007428 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007429 *(int *)pReplyData = reply;
7430 break;
7431 } else if (reply != NO_ERROR) {
7432 *(int *)pReplyData = reply;
7433 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007434 }
7435 mCblk->serverIndex += size;
7436 }
7437 mCblk->serverIndex = 0;
7438 mCblk->clientIndex = 0;
7439 return status;
7440 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007441 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007442 return enable();
7443 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007444 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007445 return disable();
7446 }
7447
7448 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7449}
7450
Eric Laurent59255e42011-07-27 19:49:51 -07007451void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007452{
Steve Block3856b092011-10-20 11:56:00 +01007453 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007454
7455 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007456 mEnabled = enabled;
7457
Mathias Agopian65ab4712010-07-14 17:59:35 -07007458 if (signal && mEffectClient != 0) {
7459 mEffectClient->controlStatusChanged(hasControl);
7460 }
7461}
7462
Eric Laurent25f43952010-07-28 05:40:18 -07007463void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7464 uint32_t cmdSize,
7465 void *pCmdData,
7466 uint32_t replySize,
7467 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007468{
7469 if (mEffectClient != 0) {
7470 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7471 }
7472}
7473
7474
7475
7476void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7477{
7478 if (mEffectClient != 0) {
7479 mEffectClient->enableStatusChanged(enabled);
7480 }
7481}
7482
7483status_t AudioFlinger::EffectHandle::onTransact(
7484 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7485{
7486 return BnEffect::onTransact(code, data, reply, flags);
7487}
7488
7489
7490void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7491{
Glenn Kastena0d68332012-01-27 16:47:15 -08007492 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007493
7494 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08007495 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007496 mPriority,
7497 mHasControl,
7498 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007499 mCblk ? mCblk->clientIndex : 0,
7500 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007501 );
7502
7503 if (locked) {
7504 mCblk->lock.unlock();
7505 }
7506}
7507
7508#undef LOG_TAG
7509#define LOG_TAG "AudioFlinger::EffectChain"
7510
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007511AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007512 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007513 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007514 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7515 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007516{
Dima Zavinfce7a472011-04-19 22:30:36 -07007517 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007518 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007519 return;
7520 }
7521 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7522 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007523}
7524
7525AudioFlinger::EffectChain::~EffectChain()
7526{
7527 if (mOwnInBuffer) {
7528 delete mInBuffer;
7529 }
7530
7531}
7532
Eric Laurent59255e42011-07-27 19:49:51 -07007533// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007534sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007535{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007536 size_t size = mEffects.size();
7537
7538 for (size_t i = 0; i < size; i++) {
7539 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007540 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007541 }
7542 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007543 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007544}
7545
Eric Laurent59255e42011-07-27 19:49:51 -07007546// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007547sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007548{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007549 size_t size = mEffects.size();
7550
7551 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007552 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7553 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007554 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007555 }
7556 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007557 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007558}
7559
Eric Laurent59255e42011-07-27 19:49:51 -07007560// getEffectFromType_l() must be called with ThreadBase::mLock held
7561sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7562 const effect_uuid_t *type)
7563{
Eric Laurent59255e42011-07-27 19:49:51 -07007564 size_t size = mEffects.size();
7565
7566 for (size_t i = 0; i < size; i++) {
7567 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007568 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007569 }
7570 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007571 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007572}
7573
Mathias Agopian65ab4712010-07-14 17:59:35 -07007574// Must be called with EffectChain::mLock locked
7575void AudioFlinger::EffectChain::process_l()
7576{
Eric Laurentdac69112010-09-28 14:09:57 -07007577 sp<ThreadBase> thread = mThread.promote();
7578 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007579 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007580 return;
7581 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007582 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7583 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007584 // always process effects unless no more tracks are on the session and the effect tail
7585 // has been rendered
7586 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007587 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007588 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007589
Eric Laurent544fe9b2011-11-11 15:42:52 -08007590 if (!tracksOnSession && mTailBufferCount == 0) {
7591 doProcess = false;
7592 }
7593
7594 if (activeTrackCnt() == 0) {
7595 // if no track is active and the effect tail has not been rendered,
7596 // the input buffer must be cleared here as the mixer process will not do it
7597 if (tracksOnSession || mTailBufferCount > 0) {
7598 size_t numSamples = thread->frameCount() * thread->channelCount();
7599 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7600 if (mTailBufferCount > 0) {
7601 mTailBufferCount--;
7602 }
7603 }
7604 }
Eric Laurentdac69112010-09-28 14:09:57 -07007605 }
7606
Mathias Agopian65ab4712010-07-14 17:59:35 -07007607 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007608 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007609 for (size_t i = 0; i < size; i++) {
7610 mEffects[i]->process();
7611 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007612 }
7613 for (size_t i = 0; i < size; i++) {
7614 mEffects[i]->updateState();
7615 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007616}
7617
Eric Laurentcab11242010-07-15 12:50:15 -07007618// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007619status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007620{
7621 effect_descriptor_t desc = effect->desc();
7622 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7623
7624 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007625 effect->setChain(this);
7626 sp<ThreadBase> thread = mThread.promote();
7627 if (thread == 0) {
7628 return NO_INIT;
7629 }
7630 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007631
7632 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7633 // Auxiliary effects are inserted at the beginning of mEffects vector as
7634 // they are processed first and accumulated in chain input buffer
7635 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007636
Mathias Agopian65ab4712010-07-14 17:59:35 -07007637 // the input buffer for auxiliary effect contains mono samples in
7638 // 32 bit format. This is to avoid saturation in AudoMixer
7639 // accumulation stage. Saturation is done in EffectModule::process() before
7640 // calling the process in effect engine
7641 size_t numSamples = thread->frameCount();
7642 int32_t *buffer = new int32_t[numSamples];
7643 memset(buffer, 0, numSamples * sizeof(int32_t));
7644 effect->setInBuffer((int16_t *)buffer);
7645 // auxiliary effects output samples to chain input buffer for further processing
7646 // by insert effects
7647 effect->setOutBuffer(mInBuffer);
7648 } else {
7649 // Insert effects are inserted at the end of mEffects vector as they are processed
7650 // after track and auxiliary effects.
7651 // Insert effect order as a function of indicated preference:
7652 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7653 // another effect is present
7654 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7655 // last effect claiming first position
7656 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7657 // first effect claiming last position
7658 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7659 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7660 // already present
7661
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007662 size_t size = mEffects.size();
7663 size_t idx_insert = size;
7664 ssize_t idx_insert_first = -1;
7665 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007666
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007667 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007668 effect_descriptor_t d = mEffects[i]->desc();
7669 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7670 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7671 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7672 // check invalid effect chaining combinations
7673 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7674 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007675 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007676 return INVALID_OPERATION;
7677 }
7678 // remember position of first insert effect and by default
7679 // select this as insert position for new effect
7680 if (idx_insert == size) {
7681 idx_insert = i;
7682 }
7683 // remember position of last insert effect claiming
7684 // first position
7685 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7686 idx_insert_first = i;
7687 }
7688 // remember position of first insert effect claiming
7689 // last position
7690 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7691 idx_insert_last == -1) {
7692 idx_insert_last = i;
7693 }
7694 }
7695 }
7696
7697 // modify idx_insert from first position if needed
7698 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7699 if (idx_insert_last != -1) {
7700 idx_insert = idx_insert_last;
7701 } else {
7702 idx_insert = size;
7703 }
7704 } else {
7705 if (idx_insert_first != -1) {
7706 idx_insert = idx_insert_first + 1;
7707 }
7708 }
7709
7710 // always read samples from chain input buffer
7711 effect->setInBuffer(mInBuffer);
7712
7713 // if last effect in the chain, output samples to chain
7714 // output buffer, otherwise to chain input buffer
7715 if (idx_insert == size) {
7716 if (idx_insert != 0) {
7717 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7718 mEffects[idx_insert-1]->configure();
7719 }
7720 effect->setOutBuffer(mOutBuffer);
7721 } else {
7722 effect->setOutBuffer(mInBuffer);
7723 }
7724 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007725
Steve Block3856b092011-10-20 11:56:00 +01007726 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007727 }
7728 effect->configure();
7729 return NO_ERROR;
7730}
7731
Eric Laurentcab11242010-07-15 12:50:15 -07007732// removeEffect_l() must be called with PlaybackThread::mLock held
7733size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007734{
7735 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007736 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007737 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7738
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007739 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007740 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007741 // calling stop here will remove pre-processing effect from the audio HAL.
7742 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7743 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007744 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7745 mEffects[i]->state() == EffectModule::STOPPING) {
7746 mEffects[i]->stop();
7747 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007748 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7749 delete[] effect->inBuffer();
7750 } else {
7751 if (i == size - 1 && i != 0) {
7752 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7753 mEffects[i - 1]->configure();
7754 }
7755 }
7756 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007757 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007758 break;
7759 }
7760 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007761
7762 return mEffects.size();
7763}
7764
Eric Laurentcab11242010-07-15 12:50:15 -07007765// setDevice_l() must be called with PlaybackThread::mLock held
7766void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007767{
7768 size_t size = mEffects.size();
7769 for (size_t i = 0; i < size; i++) {
7770 mEffects[i]->setDevice(device);
7771 }
7772}
7773
Eric Laurentcab11242010-07-15 12:50:15 -07007774// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007775void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007776{
7777 size_t size = mEffects.size();
7778 for (size_t i = 0; i < size; i++) {
7779 mEffects[i]->setMode(mode);
7780 }
7781}
7782
Eric Laurentcab11242010-07-15 12:50:15 -07007783// setVolume_l() must be called with PlaybackThread::mLock held
7784bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007785{
7786 uint32_t newLeft = *left;
7787 uint32_t newRight = *right;
7788 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007789 int ctrlIdx = -1;
7790 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007791
Eric Laurentcab11242010-07-15 12:50:15 -07007792 // first update volume controller
7793 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007794 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007795 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7796 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007797 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007798 break;
7799 }
7800 }
7801
7802 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007803 if (hasControl) {
7804 *left = mNewLeftVolume;
7805 *right = mNewRightVolume;
7806 }
7807 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007808 }
7809
7810 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007811 mLeftVolume = newLeft;
7812 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007813
7814 // second get volume update from volume controller
7815 if (ctrlIdx >= 0) {
7816 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007817 mNewLeftVolume = newLeft;
7818 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007819 }
7820 // then indicate volume to all other effects in chain.
7821 // Pass altered volume to effects before volume controller
7822 // and requested volume to effects after controller
7823 uint32_t lVol = newLeft;
7824 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007825
Mathias Agopian65ab4712010-07-14 17:59:35 -07007826 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007827 if ((int)i == ctrlIdx) continue;
7828 // this also works for ctrlIdx == -1 when there is no volume controller
7829 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007830 lVol = *left;
7831 rVol = *right;
7832 }
7833 mEffects[i]->setVolume(&lVol, &rVol, false);
7834 }
7835 *left = newLeft;
7836 *right = newRight;
7837
7838 return hasControl;
7839}
7840
Mathias Agopian65ab4712010-07-14 17:59:35 -07007841status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7842{
7843 const size_t SIZE = 256;
7844 char buffer[SIZE];
7845 String8 result;
7846
7847 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7848 result.append(buffer);
7849
7850 bool locked = tryLock(mLock);
7851 // failed to lock - AudioFlinger is probably deadlocked
7852 if (!locked) {
7853 result.append("\tCould not lock mutex:\n");
7854 }
7855
Eric Laurentcab11242010-07-15 12:50:15 -07007856 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7857 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007858 mEffects.size(),
7859 (uint32_t)mInBuffer,
7860 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007861 mActiveTrackCnt);
7862 result.append(buffer);
7863 write(fd, result.string(), result.size());
7864
7865 for (size_t i = 0; i < mEffects.size(); ++i) {
7866 sp<EffectModule> effect = mEffects[i];
7867 if (effect != 0) {
7868 effect->dump(fd, args);
7869 }
7870 }
7871
7872 if (locked) {
7873 mLock.unlock();
7874 }
7875
7876 return NO_ERROR;
7877}
7878
Eric Laurent59255e42011-07-27 19:49:51 -07007879// must be called with ThreadBase::mLock held
7880void AudioFlinger::EffectChain::setEffectSuspended_l(
7881 const effect_uuid_t *type, bool suspend)
7882{
7883 sp<SuspendedEffectDesc> desc;
7884 // use effect type UUID timelow as key as there is no real risk of identical
7885 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007886 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007887 if (suspend) {
7888 if (index >= 0) {
7889 desc = mSuspendedEffects.valueAt(index);
7890 } else {
7891 desc = new SuspendedEffectDesc();
7892 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7893 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007894 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007895 }
7896 if (desc->mRefCount++ == 0) {
7897 sp<EffectModule> effect = getEffectIfEnabled(type);
7898 if (effect != 0) {
7899 desc->mEffect = effect;
7900 effect->setSuspended(true);
7901 effect->setEnabled(false);
7902 }
7903 }
7904 } else {
7905 if (index < 0) {
7906 return;
7907 }
7908 desc = mSuspendedEffects.valueAt(index);
7909 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007910 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007911 desc->mRefCount = 1;
7912 }
7913 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007914 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007915 if (desc->mEffect != 0) {
7916 sp<EffectModule> effect = desc->mEffect.promote();
7917 if (effect != 0) {
7918 effect->setSuspended(false);
7919 sp<EffectHandle> handle = effect->controlHandle();
7920 if (handle != 0) {
7921 effect->setEnabled(handle->enabled());
7922 }
7923 }
7924 desc->mEffect.clear();
7925 }
7926 mSuspendedEffects.removeItemsAt(index);
7927 }
7928 }
7929}
7930
7931// must be called with ThreadBase::mLock held
7932void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7933{
7934 sp<SuspendedEffectDesc> desc;
7935
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007936 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07007937 if (suspend) {
7938 if (index >= 0) {
7939 desc = mSuspendedEffects.valueAt(index);
7940 } else {
7941 desc = new SuspendedEffectDesc();
7942 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007943 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007944 }
7945 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08007946 Vector< sp<EffectModule> > effects;
7947 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07007948 for (size_t i = 0; i < effects.size(); i++) {
7949 setEffectSuspended_l(&effects[i]->desc().type, true);
7950 }
7951 }
7952 } else {
7953 if (index < 0) {
7954 return;
7955 }
7956 desc = mSuspendedEffects.valueAt(index);
7957 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007958 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007959 desc->mRefCount = 1;
7960 }
7961 if (--desc->mRefCount == 0) {
7962 Vector<const effect_uuid_t *> types;
7963 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7964 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7965 continue;
7966 }
7967 types.add(&mSuspendedEffects.valueAt(i)->mType);
7968 }
7969 for (size_t i = 0; i < types.size(); i++) {
7970 setEffectSuspended_l(types[i], false);
7971 }
Steve Block3856b092011-10-20 11:56:00 +01007972 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007973 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7974 }
7975 }
7976}
7977
Eric Laurent6bffdb82011-09-23 08:40:41 -07007978
7979// The volume effect is used for automated tests only
7980#ifndef OPENSL_ES_H_
7981static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7982 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7983const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7984#endif //OPENSL_ES_H_
7985
Eric Laurentdb7c0792011-08-10 10:37:50 -07007986bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7987{
7988 // auxiliary effects and visualizer are never suspended on output mix
7989 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7990 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007991 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7992 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007993 return false;
7994 }
7995 return true;
7996}
7997
Glenn Kastend0539712012-01-30 12:56:03 -08007998void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07007999{
Glenn Kastend0539712012-01-30 12:56:03 -08008000 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07008001 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08008002 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8003 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07008004 }
Eric Laurent59255e42011-07-27 19:49:51 -07008005 }
Eric Laurent59255e42011-07-27 19:49:51 -07008006}
8007
8008sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8009 const effect_uuid_t *type)
8010{
Glenn Kasten090f0192012-01-30 13:00:02 -08008011 sp<EffectModule> effect = getEffectFromType_l(type);
8012 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008013}
8014
8015void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8016 bool enabled)
8017{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008018 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008019 if (enabled) {
8020 if (index < 0) {
8021 // if the effect is not suspend check if all effects are suspended
8022 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8023 if (index < 0) {
8024 return;
8025 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07008026 if (!isEffectEligibleForSuspend(effect->desc())) {
8027 return;
8028 }
Eric Laurent59255e42011-07-27 19:49:51 -07008029 setEffectSuspended_l(&effect->desc().type, enabled);
8030 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07008031 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008032 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07008033 return;
8034 }
Eric Laurent59255e42011-07-27 19:49:51 -07008035 }
Steve Block3856b092011-10-20 11:56:00 +01008036 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07008037 effect->desc().type.timeLow);
8038 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8039 // if effect is requested to suspended but was not yet enabled, supend it now.
8040 if (desc->mEffect == 0) {
8041 desc->mEffect = effect;
8042 effect->setEnabled(false);
8043 effect->setSuspended(true);
8044 }
8045 } else {
8046 if (index < 0) {
8047 return;
8048 }
Steve Block3856b092011-10-20 11:56:00 +01008049 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07008050 effect->desc().type.timeLow);
8051 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8052 desc->mEffect.clear();
8053 effect->setSuspended(false);
8054 }
8055}
8056
Mathias Agopian65ab4712010-07-14 17:59:35 -07008057#undef LOG_TAG
8058#define LOG_TAG "AudioFlinger"
8059
8060// ----------------------------------------------------------------------------
8061
8062status_t AudioFlinger::onTransact(
8063 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8064{
8065 return BnAudioFlinger::onTransact(code, data, reply, flags);
8066}
8067
Mathias Agopian65ab4712010-07-14 17:59:35 -07008068}; // namespace android