blob: 3fe55000d3fe6840d114ac8afbdc0e8b330f825a [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070034#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035
Dima Zavinfce7a472011-04-19 22:30:36 -070036#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080038#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039
Gloria Wang9ee159b2011-02-24 14:51:45 -080040#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080041#include <media/IMediaDeathNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042
43#include <private/media/AudioTrackShared.h>
44#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070045
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070047#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080051#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
Mathias Agopian65ab4712010-07-14 17:59:35 -070053#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070054#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070055#include <audio_effects/effect_ns.h>
56#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Glenn Kasten3b21c502011-12-15 09:52:39 -080058#include <audio_utils/primitives.h>
59
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070060#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070061#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070062// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
63
John Grossman4ff14ba2012-02-08 16:37:41 -080064#include <common_time/cc_helper.h>
65#include <common_time/local_clock.h>
66
Mathias Agopian65ab4712010-07-14 17:59:35 -070067// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070068
Eric Laurentde070132010-07-13 04:45:46 -070069
Mathias Agopian65ab4712010-07-14 17:59:35 -070070namespace android {
71
Glenn Kastenec1d6b52011-12-12 09:04:45 -080072static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
73static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070074
Mathias Agopian65ab4712010-07-14 17:59:35 -070075static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -080076static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070077
78// retry counts for buffer fill timeout
79// 50 * ~20msecs = 1 second
80static const int8_t kMaxTrackRetries = 50;
81static const int8_t kMaxTrackStartupRetries = 50;
82// allow less retry attempts on direct output thread.
83// direct outputs can be a scarce resource in audio hardware and should
84// be released as quickly as possible.
85static const int8_t kMaxTrackRetriesDirect = 2;
86
87static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -080088static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
Glenn Kasten7dede872011-12-13 11:04:14 -080090// don't warn about blocked writes or record buffer overflows more often than this
91static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -070092
Eric Laurent7c7f10b2011-06-17 21:29:58 -070093// RecordThread loop sleep time upon application overrun or audio HAL read error
94static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070095
Glenn Kasten7dede872011-12-13 11:04:14 -080096// maximum time to wait for setParameters to complete
97static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -070098
Eric Laurent7cafbb32011-11-22 18:50:29 -080099// minimum sleep time for the mixer thread loop when tracks are active but in underrun
100static const uint32_t kMinThreadSleepTimeUs = 5000;
101// maximum divider applied to the active sleep time in the mixer thread loop
102static const uint32_t kMaxThreadSleepTimeShift = 2;
103
John Grossman4ff14ba2012-02-08 16:37:41 -0800104nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800105
Mathias Agopian65ab4712010-07-14 17:59:35 -0700106// ----------------------------------------------------------------------------
107
Gloria Wang9ee159b2011-02-24 14:51:45 -0800108// To collect the amplifier usage
109static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800110 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
111 if (service == NULL) {
112 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800113 return;
114 }
115
116 service->addBatteryData(params);
117}
118
Dima Zavin799a70e2011-04-18 16:57:27 -0700119static int load_audio_interface(const char *if_name, const hw_module_t **mod,
120 audio_hw_device_t **dev)
121{
122 int rc;
123
124 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
125 if (rc)
126 goto out;
127
128 rc = audio_hw_device_open(*mod, dev);
Steve Block29357bc2012-01-06 19:20:56 +0000129 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin799a70e2011-04-18 16:57:27 -0700130 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
131 if (rc)
132 goto out;
133
134 return 0;
135
136out:
137 *mod = NULL;
138 *dev = NULL;
139 return rc;
140}
141
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800142static const char * const audio_interfaces[] = {
Dima Zavin799a70e2011-04-18 16:57:27 -0700143 "primary",
144 "a2dp",
145 "usb",
146};
147#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
148
Mathias Agopian65ab4712010-07-14 17:59:35 -0700149// ----------------------------------------------------------------------------
150
151AudioFlinger::AudioFlinger()
152 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800153 mPrimaryHardwareDev(NULL),
154 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
155 mMasterVolume(1.0f),
156 mMasterVolumeSupportLvl(MVS_NONE),
157 mMasterMute(false),
158 mNextUniqueId(1),
159 mMode(AUDIO_MODE_INVALID),
160 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700161{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700162}
163
164void AudioFlinger::onFirstRef()
165{
Dima Zavin799a70e2011-04-18 16:57:27 -0700166 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700167
Eric Laurent93575202011-01-18 18:39:02 -0800168 Mutex::Autolock _l(mLock);
169
Dima Zavin799a70e2011-04-18 16:57:27 -0700170 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800171 char val_str[PROPERTY_VALUE_MAX] = { 0 };
172 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
173 uint32_t int_val;
174 if (1 == sscanf(val_str, "%u", &int_val)) {
175 mStandbyTimeInNsecs = milliseconds(int_val);
176 ALOGI("Using %u mSec as standby time.", int_val);
177 } else {
178 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
179 ALOGI("Using default %u mSec as standby time.",
180 (uint32_t)(mStandbyTimeInNsecs / 1000000));
181 }
182 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700183
Dima Zavin799a70e2011-04-18 16:57:27 -0700184 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
185 const hw_module_t *mod;
186 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700187
Dima Zavin799a70e2011-04-18 16:57:27 -0700188 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
189 if (rc)
190 continue;
191
Steve Blockdf64d152012-01-04 20:05:49 +0000192 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Dima Zavin799a70e2011-04-18 16:57:27 -0700193 mod->name, mod->id);
194 mAudioHwDevs.push(dev);
195
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800196 if (mPrimaryHardwareDev == NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700197 mPrimaryHardwareDev = dev;
Steve Blockdf64d152012-01-04 20:05:49 +0000198 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700199 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700200 }
201 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700202
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800203 if (mPrimaryHardwareDev == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000204 ALOGE("Primary audio interface not found");
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800205 // proceed, all later accesses to mPrimaryHardwareDev verify it's safe with initCheck()
Dima Zavin799a70e2011-04-18 16:57:27 -0700206 }
207
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800208 // Currently (mPrimaryHardwareDev == NULL) == (mAudioHwDevs.size() == 0), but the way the
209 // primary HW dev is selected can change so these conditions might not always be equivalent.
210 // When that happens, re-visit all the code that assumes this.
211
212 AutoMutex lock(mHardwareLock);
213
John Grossman4ff14ba2012-02-08 16:37:41 -0800214 // Determine the level of master volume support the primary audio HAL has,
215 // and set the initial master volume at the same time.
216 float initialVolume = 1.0;
217 mMasterVolumeSupportLvl = MVS_NONE;
218 if (0 == mPrimaryHardwareDev->init_check(mPrimaryHardwareDev)) {
219 audio_hw_device_t *dev = mPrimaryHardwareDev;
220
221 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
222 if ((NULL != dev->get_master_volume) &&
223 (NO_ERROR == dev->get_master_volume(dev, &initialVolume))) {
224 mMasterVolumeSupportLvl = MVS_FULL;
225 } else {
226 mMasterVolumeSupportLvl = MVS_SETONLY;
227 initialVolume = 1.0;
228 }
229
230 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
231 if ((NULL == dev->set_master_volume) ||
232 (NO_ERROR != dev->set_master_volume(dev, initialVolume))) {
233 mMasterVolumeSupportLvl = MVS_NONE;
234 }
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800235 mHardwareStatus = AUDIO_HW_IDLE;
John Grossman4ff14ba2012-02-08 16:37:41 -0800236 }
237
238 // Set the mode for each audio HAL, and try to set the initial volume (if
239 // supported) for all of the non-primary audio HALs.
Dima Zavin799a70e2011-04-18 16:57:27 -0700240 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
241 audio_hw_device_t *dev = mAudioHwDevs[i];
242
243 mHardwareStatus = AUDIO_HW_INIT;
244 rc = dev->init_check(dev);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800245 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700246 if (rc == 0) {
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800247 mMode = AUDIO_MODE_NORMAL; // assigned multiple times with same value
Dima Zavin799a70e2011-04-18 16:57:27 -0700248 mHardwareStatus = AUDIO_HW_SET_MODE;
249 dev->set_mode(dev, mMode);
John Grossman4ff14ba2012-02-08 16:37:41 -0800250
251 if ((dev != mPrimaryHardwareDev) &&
252 (NULL != dev->set_master_volume)) {
253 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
254 dev->set_master_volume(dev, initialVolume);
255 }
256
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800257 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700258 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700259 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800260
261 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
262 ? initialVolume
263 : 1.0;
264 mMasterVolume = initialVolume;
265 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700266}
267
268AudioFlinger::~AudioFlinger()
269{
Dima Zavin799a70e2011-04-18 16:57:27 -0700270
Mathias Agopian65ab4712010-07-14 17:59:35 -0700271 while (!mRecordThreads.isEmpty()) {
272 // closeInput() will remove first entry from mRecordThreads
273 closeInput(mRecordThreads.keyAt(0));
274 }
275 while (!mPlaybackThreads.isEmpty()) {
276 // closeOutput() will remove first entry from mPlaybackThreads
277 closeOutput(mPlaybackThreads.keyAt(0));
278 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700279
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800280 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
281 // no mHardwareLock needed, as there are no other references to this
282 audio_hw_device_close(mAudioHwDevs[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700283 }
284}
285
Dima Zavin799a70e2011-04-18 16:57:27 -0700286audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
287{
288 /* first matching HW device is returned */
289 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
290 audio_hw_device_t *dev = mAudioHwDevs[i];
291 if ((dev->get_supported_devices(dev) & devices) == devices)
292 return dev;
293 }
294 return NULL;
295}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700296
297status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
298{
299 const size_t SIZE = 256;
300 char buffer[SIZE];
301 String8 result;
302
303 result.append("Clients:\n");
304 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800305 sp<Client> client = mClients.valueAt(i).promote();
306 if (client != 0) {
307 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
308 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700309 }
310 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700311
312 result.append("Global session refs:\n");
313 result.append(" session pid cnt\n");
314 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
315 AudioSessionRef *r = mAudioSessionRefs[i];
316 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
317 result.append(buffer);
318 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700319 write(fd, result.string(), result.size());
320 return NO_ERROR;
321}
322
323
324status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
325{
326 const size_t SIZE = 256;
327 char buffer[SIZE];
328 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800329 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700330
John Grossman4ff14ba2012-02-08 16:37:41 -0800331 snprintf(buffer, SIZE, "Hardware status: %d\n"
332 "Standby Time mSec: %u\n",
333 hardwareStatus,
334 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700335 result.append(buffer);
336 write(fd, result.string(), result.size());
337 return NO_ERROR;
338}
339
340status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
341{
342 const size_t SIZE = 256;
343 char buffer[SIZE];
344 String8 result;
345 snprintf(buffer, SIZE, "Permission Denial: "
346 "can't dump AudioFlinger from pid=%d, uid=%d\n",
347 IPCThreadState::self()->getCallingPid(),
348 IPCThreadState::self()->getCallingUid());
349 result.append(buffer);
350 write(fd, result.string(), result.size());
351 return NO_ERROR;
352}
353
354static bool tryLock(Mutex& mutex)
355{
356 bool locked = false;
357 for (int i = 0; i < kDumpLockRetries; ++i) {
358 if (mutex.tryLock() == NO_ERROR) {
359 locked = true;
360 break;
361 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800362 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700363 }
364 return locked;
365}
366
367status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
368{
Glenn Kasten44deb052012-02-05 18:09:08 -0800369 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700370 dumpPermissionDenial(fd, args);
371 } else {
372 // get state of hardware lock
373 bool hardwareLocked = tryLock(mHardwareLock);
374 if (!hardwareLocked) {
375 String8 result(kHardwareLockedString);
376 write(fd, result.string(), result.size());
377 } else {
378 mHardwareLock.unlock();
379 }
380
381 bool locked = tryLock(mLock);
382
383 // failed to lock - AudioFlinger is probably deadlocked
384 if (!locked) {
385 String8 result(kDeadlockedString);
386 write(fd, result.string(), result.size());
387 }
388
389 dumpClients(fd, args);
390 dumpInternals(fd, args);
391
392 // dump playback threads
393 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
394 mPlaybackThreads.valueAt(i)->dump(fd, args);
395 }
396
397 // dump record threads
398 for (size_t i = 0; i < mRecordThreads.size(); i++) {
399 mRecordThreads.valueAt(i)->dump(fd, args);
400 }
401
Dima Zavin799a70e2011-04-18 16:57:27 -0700402 // dump all hardware devs
403 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
404 audio_hw_device_t *dev = mAudioHwDevs[i];
405 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700406 }
407 if (locked) mLock.unlock();
408 }
409 return NO_ERROR;
410}
411
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800412sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
413{
414 // If pid is already in the mClients wp<> map, then use that entry
415 // (for which promote() is always != 0), otherwise create a new entry and Client.
416 sp<Client> client = mClients.valueFor(pid).promote();
417 if (client == 0) {
418 client = new Client(this, pid);
419 mClients.add(pid, client);
420 }
421
422 return client;
423}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700424
425// IAudioFlinger interface
426
427
428sp<IAudioTrack> AudioFlinger::createTrack(
429 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800430 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700431 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800432 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700433 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700434 int frameCount,
Glenn Kasten5cf034d2012-02-21 10:35:56 -0800435 // FIXME dead, remove from IAudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700436 uint32_t flags,
437 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800438 audio_io_handle_t output,
John Grossman4ff14ba2012-02-08 16:37:41 -0800439 bool isTimed,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700440 int *sessionId,
441 status_t *status)
442{
443 sp<PlaybackThread::Track> track;
444 sp<TrackHandle> trackHandle;
445 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700446 status_t lStatus;
447 int lSessionId;
448
Glenn Kasten263709e2012-01-06 08:40:01 -0800449 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
450 // but if someone uses binder directly they could bypass that and cause us to crash
451 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000452 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700453 lStatus = BAD_VALUE;
454 goto Exit;
455 }
456
457 {
458 Mutex::Autolock _l(mLock);
459 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700460 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700461 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000462 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700463 lStatus = BAD_VALUE;
464 goto Exit;
465 }
466
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800467 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700468
Steve Block3856b092011-10-20 11:56:00 +0100469 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700470 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700471 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700472 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
473 if (mPlaybackThreads.keyAt(i) != output) {
474 // prevent same audio session on different output threads
475 uint32_t sessions = t->hasAudioSession(*sessionId);
476 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000477 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700478 lStatus = BAD_VALUE;
479 goto Exit;
480 }
481 // check if an effect with same session ID is waiting for a track to be created
482 if (sessions & PlaybackThread::EFFECT_SESSION) {
483 effectThread = t.get();
484 }
Eric Laurentde070132010-07-13 04:45:46 -0700485 }
486 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700487 lSessionId = *sessionId;
488 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700489 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700490 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700491 if (sessionId != NULL) {
492 *sessionId = lSessionId;
493 }
494 }
Steve Block3856b092011-10-20 11:56:00 +0100495 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700496
497 track = thread->createTrack_l(client, streamType, sampleRate, format,
John Grossman4ff14ba2012-02-08 16:37:41 -0800498 channelMask, frameCount, sharedBuffer, lSessionId, isTimed, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700499
500 // move effect chain to this output thread if an effect on same session was waiting
501 // for a track to be created
502 if (lStatus == NO_ERROR && effectThread != NULL) {
503 Mutex::Autolock _dl(thread->mLock);
504 Mutex::Autolock _sl(effectThread->mLock);
505 moveEffectChain_l(lSessionId, effectThread, thread, true);
506 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700507 }
508 if (lStatus == NO_ERROR) {
509 trackHandle = new TrackHandle(track);
510 } else {
511 // remove local strong reference to Client before deleting the Track so that the Client
512 // destructor is called by the TrackBase destructor with mLock held
513 client.clear();
514 track.clear();
515 }
516
517Exit:
518 if(status) {
519 *status = lStatus;
520 }
521 return trackHandle;
522}
523
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800524uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700525{
526 Mutex::Autolock _l(mLock);
527 PlaybackThread *thread = checkPlaybackThread_l(output);
528 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000529 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700530 return 0;
531 }
532 return thread->sampleRate();
533}
534
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800535int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700536{
537 Mutex::Autolock _l(mLock);
538 PlaybackThread *thread = checkPlaybackThread_l(output);
539 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000540 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700541 return 0;
542 }
543 return thread->channelCount();
544}
545
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800546audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700547{
548 Mutex::Autolock _l(mLock);
549 PlaybackThread *thread = checkPlaybackThread_l(output);
550 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000551 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800552 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700553 }
554 return thread->format();
555}
556
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800557size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700558{
559 Mutex::Autolock _l(mLock);
560 PlaybackThread *thread = checkPlaybackThread_l(output);
561 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000562 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700563 return 0;
564 }
565 return thread->frameCount();
566}
567
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800568uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700569{
570 Mutex::Autolock _l(mLock);
571 PlaybackThread *thread = checkPlaybackThread_l(output);
572 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000573 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700574 return 0;
575 }
576 return thread->latency();
577}
578
579status_t AudioFlinger::setMasterVolume(float value)
580{
Eric Laurenta1884f92011-08-23 08:25:03 -0700581 status_t ret = initCheck();
582 if (ret != NO_ERROR) {
583 return ret;
584 }
585
Mathias Agopian65ab4712010-07-14 17:59:35 -0700586 // check calling permissions
587 if (!settingsAllowed()) {
588 return PERMISSION_DENIED;
589 }
590
John Grossman4ff14ba2012-02-08 16:37:41 -0800591 float swmv = value;
592
Mathias Agopian65ab4712010-07-14 17:59:35 -0700593 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800594 if (MVS_NONE != mMasterVolumeSupportLvl) {
595 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
596 AutoMutex lock(mHardwareLock);
597 audio_hw_device_t *dev = mAudioHwDevs[i];
598
599 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
600 if (NULL != dev->set_master_volume) {
601 dev->set_master_volume(dev, value);
602 }
603 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800604 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800605
606 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700607 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700608
Eric Laurent93575202011-01-18 18:39:02 -0800609 Mutex::Autolock _l(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -0800610 mMasterVolume = value;
611 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800612 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossman4ff14ba2012-02-08 16:37:41 -0800613 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700614
615 return NO_ERROR;
616}
617
Glenn Kastenf78aee72012-01-04 11:00:47 -0800618status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700619{
Eric Laurenta1884f92011-08-23 08:25:03 -0700620 status_t ret = initCheck();
621 if (ret != NO_ERROR) {
622 return ret;
623 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700624
625 // check calling permissions
626 if (!settingsAllowed()) {
627 return PERMISSION_DENIED;
628 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800629 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000630 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700631 return BAD_VALUE;
632 }
633
634 { // scope for the lock
635 AutoMutex lock(mHardwareLock);
636 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700637 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700638 mHardwareStatus = AUDIO_HW_IDLE;
639 }
640
641 if (NO_ERROR == ret) {
642 Mutex::Autolock _l(mLock);
643 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800644 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700645 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700646 }
647
648 return ret;
649}
650
651status_t AudioFlinger::setMicMute(bool state)
652{
Eric Laurenta1884f92011-08-23 08:25:03 -0700653 status_t ret = initCheck();
654 if (ret != NO_ERROR) {
655 return ret;
656 }
657
Mathias Agopian65ab4712010-07-14 17:59:35 -0700658 // check calling permissions
659 if (!settingsAllowed()) {
660 return PERMISSION_DENIED;
661 }
662
663 AutoMutex lock(mHardwareLock);
664 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700665 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700666 mHardwareStatus = AUDIO_HW_IDLE;
667 return ret;
668}
669
670bool AudioFlinger::getMicMute() const
671{
Eric Laurenta1884f92011-08-23 08:25:03 -0700672 status_t ret = initCheck();
673 if (ret != NO_ERROR) {
674 return false;
675 }
676
Dima Zavinfce7a472011-04-19 22:30:36 -0700677 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800678 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700679 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700680 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700681 mHardwareStatus = AUDIO_HW_IDLE;
682 return state;
683}
684
685status_t AudioFlinger::setMasterMute(bool muted)
686{
687 // check calling permissions
688 if (!settingsAllowed()) {
689 return PERMISSION_DENIED;
690 }
691
Eric Laurent93575202011-01-18 18:39:02 -0800692 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800693 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700694 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800695 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700696 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
697
698 return NO_ERROR;
699}
700
701float AudioFlinger::masterVolume() const
702{
Glenn Kasten98067102011-12-13 11:47:54 -0800703 Mutex::Autolock _l(mLock);
704 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700705}
706
John Grossman4ff14ba2012-02-08 16:37:41 -0800707float AudioFlinger::masterVolumeSW() const
708{
709 Mutex::Autolock _l(mLock);
710 return masterVolumeSW_l();
711}
712
Mathias Agopian65ab4712010-07-14 17:59:35 -0700713bool AudioFlinger::masterMute() const
714{
Glenn Kasten98067102011-12-13 11:47:54 -0800715 Mutex::Autolock _l(mLock);
716 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700717}
718
John Grossman4ff14ba2012-02-08 16:37:41 -0800719float AudioFlinger::masterVolume_l() const
720{
721 if (MVS_FULL == mMasterVolumeSupportLvl) {
722 float ret_val;
723 AutoMutex lock(mHardwareLock);
724
725 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
726 assert(NULL != mPrimaryHardwareDev);
727 assert(NULL != mPrimaryHardwareDev->get_master_volume);
728
729 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
730 mHardwareStatus = AUDIO_HW_IDLE;
731 return ret_val;
732 }
733
734 return mMasterVolume;
735}
736
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800737status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
738 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700739{
740 // check calling permissions
741 if (!settingsAllowed()) {
742 return PERMISSION_DENIED;
743 }
744
Glenn Kasten263709e2012-01-06 08:40:01 -0800745 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000746 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700747 return BAD_VALUE;
748 }
749
750 AutoMutex lock(mLock);
751 PlaybackThread *thread = NULL;
752 if (output) {
753 thread = checkPlaybackThread_l(output);
754 if (thread == NULL) {
755 return BAD_VALUE;
756 }
757 }
758
759 mStreamTypes[stream].volume = value;
760
761 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800762 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700763 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
764 }
765 } else {
766 thread->setStreamVolume(stream, value);
767 }
768
769 return NO_ERROR;
770}
771
Glenn Kastenfff6d712012-01-12 16:38:12 -0800772status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700773{
774 // check calling permissions
775 if (!settingsAllowed()) {
776 return PERMISSION_DENIED;
777 }
778
Glenn Kasten263709e2012-01-06 08:40:01 -0800779 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700780 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000781 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700782 return BAD_VALUE;
783 }
784
Eric Laurent93575202011-01-18 18:39:02 -0800785 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700786 mStreamTypes[stream].mute = muted;
787 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
788 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
789
790 return NO_ERROR;
791}
792
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800793float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700794{
Glenn Kasten263709e2012-01-06 08:40:01 -0800795 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796 return 0.0f;
797 }
798
799 AutoMutex lock(mLock);
800 float volume;
801 if (output) {
802 PlaybackThread *thread = checkPlaybackThread_l(output);
803 if (thread == NULL) {
804 return 0.0f;
805 }
806 volume = thread->streamVolume(stream);
807 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800808 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700809 }
810
811 return volume;
812}
813
Glenn Kastenfff6d712012-01-12 16:38:12 -0800814bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700815{
Glenn Kasten263709e2012-01-06 08:40:01 -0800816 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700817 return true;
818 }
819
Glenn Kasten6637baa2012-01-09 09:40:36 -0800820 AutoMutex lock(mLock);
821 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700822}
823
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800824status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700825{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800826 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700827 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
828 // check calling permissions
829 if (!settingsAllowed()) {
830 return PERMISSION_DENIED;
831 }
832
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833 // ioHandle == 0 means the parameters are global to the audio hardware interface
834 if (ioHandle == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700835 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800836 {
837 AutoMutex lock(mHardwareLock);
838 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700839 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
840 audio_hw_device_t *dev = mAudioHwDevs[i];
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800841 status_t result = dev->set_parameters(dev, keyValuePairs.string());
Dima Zavin799a70e2011-04-18 16:57:27 -0700842 final_result = result ?: final_result;
843 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700844 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800845 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700846 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
847 AudioParameter param = AudioParameter(keyValuePairs);
848 String8 value;
849 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
850 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700851 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
852 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700853 for (size_t i = 0; i < mRecordThreads.size(); i++) {
854 sp<RecordThread> thread = mRecordThreads.valueAt(i);
855 RecordThread::RecordTrack *track = thread->track();
856 if (track != NULL) {
857 audio_devices_t device = (audio_devices_t)(
858 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700859 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700860 thread->setEffectSuspended(FX_IID_AEC,
861 suspend,
862 track->sessionId());
863 thread->setEffectSuspended(FX_IID_NS,
864 suspend,
865 track->sessionId());
866 }
867 }
Eric Laurentbee53372011-08-29 12:42:48 -0700868 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700869 }
870 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700871 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700872 }
873
874 // hold a strong ref on thread in case closeOutput() or closeInput() is called
875 // and the thread is exited once the lock is released
876 sp<ThreadBase> thread;
877 {
878 Mutex::Autolock _l(mLock);
879 thread = checkPlaybackThread_l(ioHandle);
880 if (thread == NULL) {
881 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800882 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700883 // indicate output device change to all input threads for pre processing
884 AudioParameter param = AudioParameter(keyValuePairs);
885 int value;
886 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
887 for (size_t i = 0; i < mRecordThreads.size(); i++) {
888 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
889 }
890 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700891 }
892 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800893 if (thread != 0) {
894 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700895 }
896 return BAD_VALUE;
897}
898
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800899String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700900{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800901// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700902// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
903
904 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700905 String8 out_s8;
906
Dima Zavin799a70e2011-04-18 16:57:27 -0700907 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800908 char *s;
909 {
910 AutoMutex lock(mHardwareLock);
911 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700912 audio_hw_device_t *dev = mAudioHwDevs[i];
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800913 s = dev->get_parameters(dev, keys.string());
914 mHardwareStatus = AUDIO_HW_IDLE;
915 }
John Grossmanef7740b2012-02-09 11:28:36 -0800916 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700917 free(s);
918 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700919 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700920 }
921
922 Mutex::Autolock _l(mLock);
923
924 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
925 if (playbackThread != NULL) {
926 return playbackThread->getParameters(keys);
927 }
928 RecordThread *recordThread = checkRecordThread_l(ioHandle);
929 if (recordThread != NULL) {
930 return recordThread->getParameters(keys);
931 }
932 return String8("");
933}
934
Glenn Kastenf587ba52012-01-26 16:25:10 -0800935size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700936{
Eric Laurenta1884f92011-08-23 08:25:03 -0700937 status_t ret = initCheck();
938 if (ret != NO_ERROR) {
939 return 0;
940 }
941
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800942 AutoMutex lock(mHardwareLock);
943 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
944 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
945 mHardwareStatus = AUDIO_HW_IDLE;
946 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700947}
948
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800949unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700950{
951 if (ioHandle == 0) {
952 return 0;
953 }
954
955 Mutex::Autolock _l(mLock);
956
957 RecordThread *recordThread = checkRecordThread_l(ioHandle);
958 if (recordThread != NULL) {
959 return recordThread->getInputFramesLost();
960 }
961 return 0;
962}
963
964status_t AudioFlinger::setVoiceVolume(float value)
965{
Eric Laurenta1884f92011-08-23 08:25:03 -0700966 status_t ret = initCheck();
967 if (ret != NO_ERROR) {
968 return ret;
969 }
970
Mathias Agopian65ab4712010-07-14 17:59:35 -0700971 // check calling permissions
972 if (!settingsAllowed()) {
973 return PERMISSION_DENIED;
974 }
975
976 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800977 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700978 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700979 mHardwareStatus = AUDIO_HW_IDLE;
980
981 return ret;
982}
983
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800984status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
985 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700986{
987 status_t status;
988
989 Mutex::Autolock _l(mLock);
990
991 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
992 if (playbackThread != NULL) {
993 return playbackThread->getRenderPosition(halFrames, dspFrames);
994 }
995
996 return BAD_VALUE;
997}
998
999void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1000{
1001
1002 Mutex::Autolock _l(mLock);
1003
Glenn Kastenbb001922012-02-03 11:10:26 -08001004 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001005 if (mNotificationClients.indexOfKey(pid) < 0) {
1006 sp<NotificationClient> notificationClient = new NotificationClient(this,
1007 client,
1008 pid);
Steve Block3856b092011-10-20 11:56:00 +01001009 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001010
1011 mNotificationClients.add(pid, notificationClient);
1012
1013 sp<IBinder> binder = client->asBinder();
1014 binder->linkToDeath(notificationClient);
1015
1016 // the config change is always sent from playback or record threads to avoid deadlock
1017 // with AudioSystem::gLock
1018 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1019 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1020 }
1021
1022 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1023 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1024 }
1025 }
1026}
1027
1028void AudioFlinger::removeNotificationClient(pid_t pid)
1029{
1030 Mutex::Autolock _l(mLock);
1031
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001032 ssize_t index = mNotificationClients.indexOfKey(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001033 if (index >= 0) {
1034 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block3856b092011-10-20 11:56:00 +01001035 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001036 mNotificationClients.removeItem(pid);
1037 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001038
Steve Block3856b092011-10-20 11:56:00 +01001039 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001040 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001041 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001042 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001043 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +01001044 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001045 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +01001046 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001047 mAudioSessionRefs.removeAt(i);
1048 delete ref;
1049 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001050 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001051 } else {
1052 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001053 }
1054 }
1055 if (removed) {
1056 purgeStaleEffects_l();
1057 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001058}
1059
1060// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001061void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001062{
1063 size_t size = mNotificationClients.size();
1064 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001065 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1066 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001067 }
1068}
1069
1070// removeClient_l() must be called with AudioFlinger::mLock held
1071void AudioFlinger::removeClient_l(pid_t pid)
1072{
Steve Block3856b092011-10-20 11:56:00 +01001073 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001074 mClients.removeItem(pid);
1075}
1076
1077
1078// ----------------------------------------------------------------------------
1079
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001080AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1081 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001082 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001083 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001084 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
1085 // mChannelMask
1086 mChannelCount(0),
1087 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1088 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001089 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001090 mDevice(device),
1091 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001092{
1093}
1094
1095AudioFlinger::ThreadBase::~ThreadBase()
1096{
1097 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001098 // do not lock the mutex in destructor
1099 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001100 if (mPowerManager != 0) {
1101 sp<IBinder> binder = mPowerManager->asBinder();
1102 binder->unlinkToDeath(mDeathRecipient);
1103 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001104}
1105
1106void AudioFlinger::ThreadBase::exit()
1107{
Steve Block3856b092011-10-20 11:56:00 +01001108 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001109 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001110 // This lock prevents the following race in thread (uniprocessor for illustration):
1111 // if (!exitPending()) {
1112 // // context switch from here to exit()
1113 // // exit() calls requestExit(), what exitPending() observes
1114 // // exit() calls signal(), which is dropped since no waiters
1115 // // context switch back from exit() to here
1116 // mWaitWorkCV.wait(...);
1117 // // now thread is hung
1118 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001119 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001120 requestExit();
1121 mWaitWorkCV.signal();
1122 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001123 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1124 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001125 requestExitAndWait();
1126}
1127
Mathias Agopian65ab4712010-07-14 17:59:35 -07001128status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1129{
1130 status_t status;
1131
Steve Block3856b092011-10-20 11:56:00 +01001132 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001133 Mutex::Autolock _l(mLock);
1134
1135 mNewParameters.add(keyValuePairs);
1136 mWaitWorkCV.signal();
1137 // wait condition with timeout in case the thread loop has exited
1138 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001139 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001140 status = mParamStatus;
1141 mWaitWorkCV.signal();
1142 } else {
1143 status = TIMED_OUT;
1144 }
1145 return status;
1146}
1147
1148void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1149{
1150 Mutex::Autolock _l(mLock);
1151 sendConfigEvent_l(event, param);
1152}
1153
1154// sendConfigEvent_l() must be called with ThreadBase::mLock held
1155void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1156{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001157 ConfigEvent configEvent;
1158 configEvent.mEvent = event;
1159 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001160 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001161 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001162 mWaitWorkCV.signal();
1163}
1164
1165void AudioFlinger::ThreadBase::processConfigEvents()
1166{
1167 mLock.lock();
1168 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001169 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001170 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001171 mConfigEvents.removeAt(0);
1172 // release mLock before locking AudioFlinger mLock: lock order is always
1173 // AudioFlinger then ThreadBase to avoid cross deadlock
1174 mLock.unlock();
1175 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001176 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001177 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001178 mLock.lock();
1179 }
1180 mLock.unlock();
1181}
1182
1183status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1184{
1185 const size_t SIZE = 256;
1186 char buffer[SIZE];
1187 String8 result;
1188
1189 bool locked = tryLock(mLock);
1190 if (!locked) {
1191 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1192 write(fd, buffer, strlen(buffer));
1193 }
1194
1195 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1196 result.append(buffer);
1197 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1198 result.append(buffer);
1199 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1200 result.append(buffer);
1201 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1202 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001203 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1204 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001205 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1206 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001207 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001208 result.append(buffer);
1209
1210 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1211 result.append(buffer);
1212 result.append(" Index Command");
1213 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1214 snprintf(buffer, SIZE, "\n %02d ", i);
1215 result.append(buffer);
1216 result.append(mNewParameters[i]);
1217 }
1218
1219 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1220 result.append(buffer);
1221 snprintf(buffer, SIZE, " Index event param\n");
1222 result.append(buffer);
1223 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001224 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001225 result.append(buffer);
1226 }
1227 result.append("\n");
1228
1229 write(fd, result.string(), result.size());
1230
1231 if (locked) {
1232 mLock.unlock();
1233 }
1234 return NO_ERROR;
1235}
1236
Eric Laurent1d2bff02011-07-24 17:49:51 -07001237status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1238{
1239 const size_t SIZE = 256;
1240 char buffer[SIZE];
1241 String8 result;
1242
1243 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1244 write(fd, buffer, strlen(buffer));
1245
1246 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1247 sp<EffectChain> chain = mEffectChains[i];
1248 if (chain != 0) {
1249 chain->dump(fd, args);
1250 }
1251 }
1252 return NO_ERROR;
1253}
1254
Eric Laurentfeb0db62011-07-22 09:04:31 -07001255void AudioFlinger::ThreadBase::acquireWakeLock()
1256{
1257 Mutex::Autolock _l(mLock);
1258 acquireWakeLock_l();
1259}
1260
1261void AudioFlinger::ThreadBase::acquireWakeLock_l()
1262{
1263 if (mPowerManager == 0) {
1264 // use checkService() to avoid blocking if power service is not up yet
1265 sp<IBinder> binder =
1266 defaultServiceManager()->checkService(String16("power"));
1267 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001268 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001269 } else {
1270 mPowerManager = interface_cast<IPowerManager>(binder);
1271 binder->linkToDeath(mDeathRecipient);
1272 }
1273 }
1274 if (mPowerManager != 0) {
1275 sp<IBinder> binder = new BBinder();
1276 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1277 binder,
1278 String16(mName));
1279 if (status == NO_ERROR) {
1280 mWakeLockToken = binder;
1281 }
Steve Block3856b092011-10-20 11:56:00 +01001282 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001283 }
1284}
1285
1286void AudioFlinger::ThreadBase::releaseWakeLock()
1287{
1288 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001289 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001290}
1291
1292void AudioFlinger::ThreadBase::releaseWakeLock_l()
1293{
1294 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001295 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001296 if (mPowerManager != 0) {
1297 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1298 }
1299 mWakeLockToken.clear();
1300 }
1301}
1302
1303void AudioFlinger::ThreadBase::clearPowerManager()
1304{
1305 Mutex::Autolock _l(mLock);
1306 releaseWakeLock_l();
1307 mPowerManager.clear();
1308}
1309
1310void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1311{
1312 sp<ThreadBase> thread = mThread.promote();
1313 if (thread != 0) {
1314 thread->clearPowerManager();
1315 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001316 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001317}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001318
Eric Laurent59255e42011-07-27 19:49:51 -07001319void AudioFlinger::ThreadBase::setEffectSuspended(
1320 const effect_uuid_t *type, bool suspend, int sessionId)
1321{
1322 Mutex::Autolock _l(mLock);
1323 setEffectSuspended_l(type, suspend, sessionId);
1324}
1325
1326void AudioFlinger::ThreadBase::setEffectSuspended_l(
1327 const effect_uuid_t *type, bool suspend, int sessionId)
1328{
Glenn Kasten090f0192012-01-30 13:00:02 -08001329 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001330 if (chain != 0) {
1331 if (type != NULL) {
1332 chain->setEffectSuspended_l(type, suspend);
1333 } else {
1334 chain->setEffectSuspendedAll_l(suspend);
1335 }
1336 }
1337
1338 updateSuspendedSessions_l(type, suspend, sessionId);
1339}
1340
1341void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1342{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001343 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001344 if (index < 0) {
1345 return;
1346 }
1347
1348 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1349 mSuspendedSessions.editValueAt(index);
1350
1351 for (size_t i = 0; i < sessionEffects.size(); i++) {
1352 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1353 for (int j = 0; j < desc->mRefCount; j++) {
1354 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1355 chain->setEffectSuspendedAll_l(true);
1356 } else {
Steve Block3856b092011-10-20 11:56:00 +01001357 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001358 desc->mType.timeLow);
1359 chain->setEffectSuspended_l(&desc->mType, true);
1360 }
1361 }
1362 }
1363}
1364
Eric Laurent59255e42011-07-27 19:49:51 -07001365void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1366 bool suspend,
1367 int sessionId)
1368{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001369 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001370
1371 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1372
1373 if (suspend) {
1374 if (index >= 0) {
1375 sessionEffects = mSuspendedSessions.editValueAt(index);
1376 } else {
1377 mSuspendedSessions.add(sessionId, sessionEffects);
1378 }
1379 } else {
1380 if (index < 0) {
1381 return;
1382 }
1383 sessionEffects = mSuspendedSessions.editValueAt(index);
1384 }
1385
1386
1387 int key = EffectChain::kKeyForSuspendAll;
1388 if (type != NULL) {
1389 key = type->timeLow;
1390 }
1391 index = sessionEffects.indexOfKey(key);
1392
1393 sp <SuspendedSessionDesc> desc;
1394 if (suspend) {
1395 if (index >= 0) {
1396 desc = sessionEffects.valueAt(index);
1397 } else {
1398 desc = new SuspendedSessionDesc();
1399 if (type != NULL) {
1400 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1401 }
1402 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001403 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001404 }
1405 desc->mRefCount++;
1406 } else {
1407 if (index < 0) {
1408 return;
1409 }
1410 desc = sessionEffects.valueAt(index);
1411 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001412 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001413 sessionEffects.removeItemsAt(index);
1414 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001415 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001416 sessionId);
1417 mSuspendedSessions.removeItem(sessionId);
1418 }
1419 }
1420 }
1421 if (!sessionEffects.isEmpty()) {
1422 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1423 }
1424}
1425
1426void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1427 bool enabled,
1428 int sessionId)
1429{
1430 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001431 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1432}
Eric Laurent59255e42011-07-27 19:49:51 -07001433
Eric Laurenta85a74a2011-10-19 11:44:54 -07001434void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1435 bool enabled,
1436 int sessionId)
1437{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001438 if (mType != RECORD) {
1439 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1440 // another session. This gives the priority to well behaved effect control panels
1441 // and applications not using global effects.
1442 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1443 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1444 }
1445 }
Eric Laurent59255e42011-07-27 19:49:51 -07001446
1447 sp<EffectChain> chain = getEffectChain_l(sessionId);
1448 if (chain != 0) {
1449 chain->checkSuspendOnEffectEnabled(effect, enabled);
1450 }
1451}
1452
Mathias Agopian65ab4712010-07-14 17:59:35 -07001453// ----------------------------------------------------------------------------
1454
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001455AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1456 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001457 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001458 uint32_t device,
1459 type_t type)
1460 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001461 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1462 // Assumes constructor is called by AudioFlinger with it's mLock held,
1463 // but it would be safer to explicitly pass initial masterMute as parameter
1464 mMasterMute(audioFlinger->masterMute_l()),
1465 // mStreamTypes[] initialized in constructor body
1466 mOutput(output),
1467 // Assumes constructor is called by AudioFlinger with it's mLock held,
1468 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001469 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001470 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001471{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001472 snprintf(mName, kNameLength, "AudioOut_%d", id);
1473
Mathias Agopian65ab4712010-07-14 17:59:35 -07001474 readOutputParameters();
1475
Glenn Kasten263709e2012-01-06 08:40:01 -08001476 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001477 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1478 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1479 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001480 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1481 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001482 // initialized by stream_type_t default constructor
1483 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001484 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001485 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1486 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001487}
1488
1489AudioFlinger::PlaybackThread::~PlaybackThread()
1490{
1491 delete [] mMixBuffer;
1492}
1493
1494status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1495{
1496 dumpInternals(fd, args);
1497 dumpTracks(fd, args);
1498 dumpEffectChains(fd, args);
1499 return NO_ERROR;
1500}
1501
1502status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1503{
1504 const size_t SIZE = 256;
1505 char buffer[SIZE];
1506 String8 result;
1507
1508 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1509 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001510 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001511 for (size_t i = 0; i < mTracks.size(); ++i) {
1512 sp<Track> track = mTracks[i];
1513 if (track != 0) {
1514 track->dump(buffer, SIZE);
1515 result.append(buffer);
1516 }
1517 }
1518
1519 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1520 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001521 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 -07001522 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001523 sp<Track> track = mActiveTracks[i].promote();
1524 if (track != 0) {
1525 track->dump(buffer, SIZE);
1526 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001527 }
1528 }
1529 write(fd, result.string(), result.size());
1530 return NO_ERROR;
1531}
1532
Mathias Agopian65ab4712010-07-14 17:59:35 -07001533status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1534{
1535 const size_t SIZE = 256;
1536 char buffer[SIZE];
1537 String8 result;
1538
1539 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1540 result.append(buffer);
1541 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1542 result.append(buffer);
1543 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1544 result.append(buffer);
1545 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1546 result.append(buffer);
1547 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1548 result.append(buffer);
1549 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1550 result.append(buffer);
1551 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1552 result.append(buffer);
1553 write(fd, result.string(), result.size());
1554
1555 dumpBase(fd, args);
1556
1557 return NO_ERROR;
1558}
1559
1560// Thread virtuals
1561status_t AudioFlinger::PlaybackThread::readyToRun()
1562{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001563 status_t status = initCheck();
1564 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001565 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001566 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001567 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001569 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001570}
1571
1572void AudioFlinger::PlaybackThread::onFirstRef()
1573{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001574 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001575}
1576
1577// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1578sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1579 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001580 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001581 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001582 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001583 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001584 int frameCount,
1585 const sp<IMemory>& sharedBuffer,
1586 int sessionId,
John Grossman4ff14ba2012-02-08 16:37:41 -08001587 bool isTimed,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001588 status_t *status)
1589{
1590 sp<Track> track;
1591 status_t lStatus;
1592
1593 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001594 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1595 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001596 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001597 "for output %p with format %d",
1598 sampleRate, format, channelMask, mOutput, mFormat);
1599 lStatus = BAD_VALUE;
1600 goto Exit;
1601 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001602 }
1603 } else {
1604 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1605 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001606 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001607 lStatus = BAD_VALUE;
1608 goto Exit;
1609 }
1610 }
1611
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001612 lStatus = initCheck();
1613 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001614 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001615 goto Exit;
1616 }
1617
1618 { // scope for mLock
1619 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001620
1621 // all tracks in same audio session must share the same routing strategy otherwise
1622 // conflicts will happen when tracks are moved from one output to another by audio policy
1623 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001624 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001625 for (size_t i = 0; i < mTracks.size(); ++i) {
1626 sp<Track> t = mTracks[i];
1627 if (t != 0) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001628 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001629 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001630 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001631 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001632 lStatus = BAD_VALUE;
1633 goto Exit;
1634 }
1635 }
1636 }
1637
John Grossman4ff14ba2012-02-08 16:37:41 -08001638 if (!isTimed) {
1639 track = new Track(this, client, streamType, sampleRate, format,
1640 channelMask, frameCount, sharedBuffer, sessionId);
1641 } else {
1642 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1643 channelMask, frameCount, sharedBuffer, sessionId);
1644 }
1645 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001646 lStatus = NO_MEMORY;
1647 goto Exit;
1648 }
1649 mTracks.add(track);
1650
1651 sp<EffectChain> chain = getEffectChain_l(sessionId);
1652 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001653 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001654 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001655 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001656 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001657 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001658
1659 // invalidate track immediately if the stream type was moved to another thread since
1660 // createTrack() was called by the client process.
1661 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001662 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001663 this, streamType);
1664 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1665 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001666 }
1667 lStatus = NO_ERROR;
1668
1669Exit:
1670 if(status) {
1671 *status = lStatus;
1672 }
1673 return track;
1674}
1675
1676uint32_t AudioFlinger::PlaybackThread::latency() const
1677{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001678 Mutex::Autolock _l(mLock);
1679 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001680 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001681 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001682 return 0;
1683 }
1684}
1685
Glenn Kasten6637baa2012-01-09 09:40:36 -08001686void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001687{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001688 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001689 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001690}
1691
Glenn Kasten6637baa2012-01-09 09:40:36 -08001692void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001693{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001694 Mutex::Autolock _l(mLock);
1695 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001696}
1697
Glenn Kasten6637baa2012-01-09 09:40:36 -08001698void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001699{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001700 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001701 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001702}
1703
Glenn Kasten6637baa2012-01-09 09:40:36 -08001704void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001705{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001706 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001707 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001708}
1709
Glenn Kastenfff6d712012-01-12 16:38:12 -08001710float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001711{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001712 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001713 return mStreamTypes[stream].volume;
1714}
1715
Mathias Agopian65ab4712010-07-14 17:59:35 -07001716// addTrack_l() must be called with ThreadBase::mLock held
1717status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1718{
1719 status_t status = ALREADY_EXISTS;
1720
1721 // set retry count for buffer fill
1722 track->mRetryCount = kMaxTrackStartupRetries;
1723 if (mActiveTracks.indexOf(track) < 0) {
1724 // the track is newly added, make sure it fills up all its
1725 // buffers before playing. This is to ensure the client will
1726 // effectively get the latency it requested.
1727 track->mFillingUpStatus = Track::FS_FILLING;
1728 track->mResetDone = false;
1729 mActiveTracks.add(track);
1730 if (track->mainBuffer() != mMixBuffer) {
1731 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1732 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001733 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001734 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001735 }
1736 }
1737
1738 status = NO_ERROR;
1739 }
1740
Steve Block3856b092011-10-20 11:56:00 +01001741 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742 mWaitWorkCV.broadcast();
1743
1744 return status;
1745}
1746
1747// destroyTrack_l() must be called with ThreadBase::mLock held
1748void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1749{
1750 track->mState = TrackBase::TERMINATED;
1751 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001752 removeTrack_l(track);
1753 }
1754}
1755
1756void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1757{
1758 mTracks.remove(track);
1759 deleteTrackName_l(track->name());
1760 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1761 if (chain != 0) {
1762 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001763 }
1764}
1765
1766String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1767{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001768 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001769 char *s;
1770
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001771 Mutex::Autolock _l(mLock);
1772 if (initCheck() != NO_ERROR) {
1773 return out_s8;
1774 }
1775
Dima Zavin799a70e2011-04-18 16:57:27 -07001776 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001777 out_s8 = String8(s);
1778 free(s);
1779 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001780}
1781
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001782// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001783void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1784 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001785 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001786
Steve Block3856b092011-10-20 11:56:00 +01001787 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001788
1789 switch (event) {
1790 case AudioSystem::OUTPUT_OPENED:
1791 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001792 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001793 desc.samplingRate = mSampleRate;
1794 desc.format = mFormat;
1795 desc.frameCount = mFrameCount;
1796 desc.latency = latency();
1797 param2 = &desc;
1798 break;
1799
1800 case AudioSystem::STREAM_CONFIG_CHANGED:
1801 param2 = &param;
1802 case AudioSystem::OUTPUT_CLOSED:
1803 default:
1804 break;
1805 }
1806 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1807}
1808
1809void AudioFlinger::PlaybackThread::readOutputParameters()
1810{
Dima Zavin799a70e2011-04-18 16:57:27 -07001811 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001812 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1813 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001814 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001815 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001816 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001817
1818 // FIXME - Current mixer implementation only supports stereo output: Always
1819 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001820 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001821 mMixBuffer = new int16_t[mFrameCount * 2];
1822 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1823
Eric Laurentde070132010-07-13 04:45:46 -07001824 // force reconfiguration of effect chains and engines to take new buffer size and audio
1825 // parameters into account
1826 // Note that mLock is not held when readOutputParameters() is called from the constructor
1827 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1828 // matter.
1829 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1830 Vector< sp<EffectChain> > effectChains = mEffectChains;
1831 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001832 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001833 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001834}
1835
1836status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1837{
Glenn Kastena0d68332012-01-27 16:47:15 -08001838 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001839 return BAD_VALUE;
1840 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001841 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001842 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001843 return INVALID_OPERATION;
1844 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001845 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001846
Dima Zavin799a70e2011-04-18 16:57:27 -07001847 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001848}
1849
Eric Laurent39e94f82010-07-28 01:32:47 -07001850uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001851{
1852 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001853 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001854 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001855 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856 }
1857
1858 for (size_t i = 0; i < mTracks.size(); ++i) {
1859 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001860 if (sessionId == track->sessionId() &&
1861 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001862 result |= TRACK_SESSION;
1863 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001864 }
1865 }
1866
Eric Laurent39e94f82010-07-28 01:32:47 -07001867 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001868}
1869
Eric Laurentde070132010-07-13 04:45:46 -07001870uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1871{
Dima Zavinfce7a472011-04-19 22:30:36 -07001872 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001873 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001874 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1875 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001876 }
1877 for (size_t i = 0; i < mTracks.size(); i++) {
1878 sp<Track> track = mTracks[i];
1879 if (sessionId == track->sessionId() &&
1880 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001881 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07001882 }
1883 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001884 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001885}
1886
Mathias Agopian65ab4712010-07-14 17:59:35 -07001887
Glenn Kastenaed850d2012-01-26 09:46:34 -08001888AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001889{
1890 Mutex::Autolock _l(mLock);
1891 return mOutput;
1892}
1893
1894AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1895{
1896 Mutex::Autolock _l(mLock);
1897 AudioStreamOut *output = mOutput;
1898 mOutput = NULL;
1899 return output;
1900}
1901
1902// this method must always be called either with ThreadBase mLock held or inside the thread loop
1903audio_stream_t* AudioFlinger::PlaybackThread::stream()
1904{
1905 if (mOutput == NULL) {
1906 return NULL;
1907 }
1908 return &mOutput->stream->common;
1909}
1910
Eric Laurent162b40b2011-12-05 09:47:19 -08001911uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1912{
1913 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1914 // decoding and transfer time. So sleeping for half of the latency would likely cause
1915 // underruns
1916 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1917 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1918 } else {
1919 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1920 }
1921}
1922
Mathias Agopian65ab4712010-07-14 17:59:35 -07001923// ----------------------------------------------------------------------------
1924
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001925AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001926 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001927 : PlaybackThread(audioFlinger, output, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001928 mAudioMixer(new AudioMixer(mFrameCount, mSampleRate)),
1929 mPrevMixerStatus(MIXER_IDLE)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001930{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001931 // FIXME - Current mixer implementation only supports stereo output
1932 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001933 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001934 }
1935}
1936
1937AudioFlinger::MixerThread::~MixerThread()
1938{
1939 delete mAudioMixer;
1940}
1941
Glenn Kasten83efdd02012-02-24 07:21:32 -08001942class CpuStats {
1943public:
1944 void sample();
1945#ifdef DEBUG_CPU_USAGE
1946private:
1947 ThreadCpuUsage mCpu;
1948#endif
1949};
1950
1951void CpuStats::sample() {
1952#ifdef DEBUG_CPU_USAGE
1953 const CentralTendencyStatistics& stats = mCpu.statistics();
1954 mCpu.sampleAndEnable();
1955 unsigned n = stats.n();
1956 // mCpu.elapsed() is expensive, so don't call it every loop
1957 if ((n & 127) == 1) {
1958 long long elapsed = mCpu.elapsed();
1959 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1960 double perLoop = elapsed / (double) n;
1961 double perLoop100 = perLoop * 0.01;
1962 double mean = stats.mean();
1963 double stddev = stats.stddev();
1964 double minimum = stats.minimum();
1965 double maximum = stats.maximum();
1966 mCpu.resetStatistics();
1967 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",
1968 elapsed * .000000001, n, perLoop * .000001,
1969 mean * .001,
1970 stddev * .001,
1971 minimum * .001,
1972 maximum * .001,
1973 mean / perLoop100,
1974 stddev / perLoop100,
1975 minimum / perLoop100,
1976 maximum / perLoop100);
1977 }
1978 }
1979#endif
1980};
1981
Glenn Kasten37d825e2012-02-24 07:21:48 -08001982void AudioFlinger::PlaybackThread::checkSilentMode_l()
1983{
1984 if (!mMasterMute) {
1985 char value[PROPERTY_VALUE_MAX];
1986 if (property_get("ro.audio.silent", value, "0") > 0) {
1987 char *endptr;
1988 unsigned long ul = strtoul(value, &endptr, 0);
1989 if (*endptr == '\0' && ul != 0) {
1990 ALOGD("Silence is golden");
1991 // The setprop command will not allow a property to be changed after
1992 // the first time it is set, so we don't have to worry about un-muting.
1993 setMasterMute_l(true);
1994 }
1995 }
1996 }
1997}
1998
Mathias Agopian65ab4712010-07-14 17:59:35 -07001999bool AudioFlinger::MixerThread::threadLoop()
2000{
2001 Vector< sp<Track> > tracksToRemove;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002002 nsecs_t standbyTime = systemTime();
2003 size_t mixBufferSize = mFrameCount * mFrameSize;
2004 // FIXME: Relaxed timing because of a certain device that can't meet latency
2005 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07002006 // increase threshold again due to low power audio mode. The way this warning threshold is
2007 // calculated and its usefulness should be reconsidered anyway.
2008 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002009 nsecs_t lastWarning = 0;
2010 bool longStandbyExit = false;
2011 uint32_t activeSleepTime = activeSleepTimeUs();
2012 uint32_t idleSleepTime = idleSleepTimeUs();
2013 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08002014 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002015 Vector< sp<EffectChain> > effectChains;
Glenn Kasten83efdd02012-02-24 07:21:32 -08002016 CpuStats cpuStats;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002017
Eric Laurentfeb0db62011-07-22 09:04:31 -07002018 acquireWakeLock();
2019
Mathias Agopian65ab4712010-07-14 17:59:35 -07002020 while (!exitPending())
2021 {
Glenn Kasten83efdd02012-02-24 07:21:32 -08002022 cpuStats.sample();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002023 processConfigEvents();
2024
Glenn Kasten5d4eeea2012-02-24 07:25:40 -08002025 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002026 { // scope for mLock
2027
2028 Mutex::Autolock _l(mLock);
2029
2030 if (checkForNewParameters_l()) {
2031 mixBufferSize = mFrameCount * mFrameSize;
2032 // FIXME: Relaxed timing because of a certain device that can't meet latency
2033 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07002034 // increase threshold again due to low power audio mode. The way this warning
2035 // threshold is calculated and its usefulness should be reconsidered anyway.
2036 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002037 activeSleepTime = activeSleepTimeUs();
2038 idleSleepTime = idleSleepTimeUs();
2039 }
2040
2041 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2042
2043 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002044 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2045 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002046 if (!mStandby) {
Glenn Kasten90bebef2012-01-27 15:24:38 -08002047 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07002048 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002049 mStandby = true;
2050 mBytesWritten = 0;
2051 }
2052
2053 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2054 // we're about to wait, flush the binder command buffer
2055 IPCThreadState::self()->flushCommands();
2056
2057 if (exitPending()) break;
2058
Eric Laurentfeb0db62011-07-22 09:04:31 -07002059 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002060 // wait until we have something to do...
Glenn Kastenc0b52832012-02-24 11:18:09 -08002061 ALOGV("Thread %p type %d TID %d going to sleep", this, mType, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002062 mWaitWorkCV.wait(mLock);
Glenn Kastenc0b52832012-02-24 11:18:09 -08002063 ALOGV("Thread %p type %d TID %d waking up", this, mType, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002064 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002065
Eric Laurent27741442012-01-17 19:20:12 -08002066 mPrevMixerStatus = MIXER_IDLE;
Glenn Kasten37d825e2012-02-24 07:21:48 -08002067 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002068
John Grossman4ff14ba2012-02-08 16:37:41 -08002069 standbyTime = systemTime() + mStandbyTimeInNsecs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002070 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08002071 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002072 continue;
2073 }
2074 }
2075
2076 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
2077
2078 // prevent any changes in effect chain list and in each effect chain
2079 // during mixing and effect process as the audio buffers could be deleted
2080 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002081 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002082 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002083
Glenn Kastenf6b16782011-12-15 09:51:17 -08002084 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08002085 // obtain the presentation timestamp of the next output buffer
2086 int64_t pts;
2087 status_t status = INVALID_OPERATION;
2088
2089 if (NULL != mOutput->stream->get_next_write_timestamp) {
2090 status = mOutput->stream->get_next_write_timestamp(
2091 mOutput->stream, &pts);
2092 }
2093
2094 if (status != NO_ERROR) {
2095 pts = AudioBufferProvider::kInvalidPTS;
2096 }
2097
Mathias Agopian65ab4712010-07-14 17:59:35 -07002098 // mix buffers...
John Grossman4ff14ba2012-02-08 16:37:41 -08002099 mAudioMixer->process(pts);
Eric Laurent21e4b6e2012-01-23 18:56:59 -08002100 // increase sleep time progressively when application underrun condition clears.
2101 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2102 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2103 // such that we would underrun the audio HAL.
2104 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08002105 sleepTimeShift--;
2106 }
Eric Laurent21e4b6e2012-01-23 18:56:59 -08002107 sleepTime = 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08002108 standbyTime = systemTime() + mStandbyTimeInNsecs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002109 //TODO: delay standby when effects have a tail
2110 } else {
2111 // If no tracks are ready, sleep once for the duration of an output
2112 // buffer size, then write 0s to the output
2113 if (sleepTime == 0) {
2114 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08002115 sleepTime = activeSleepTime >> sleepTimeShift;
2116 if (sleepTime < kMinThreadSleepTimeUs) {
2117 sleepTime = kMinThreadSleepTimeUs;
2118 }
2119 // reduce sleep time in case of consecutive application underruns to avoid
2120 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2121 // duration we would end up writing less data than needed by the audio HAL if
2122 // the condition persists.
2123 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2124 sleepTimeShift++;
2125 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002126 } else {
2127 sleepTime = idleSleepTime;
2128 }
2129 } else if (mBytesWritten != 0 ||
2130 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2131 memset (mMixBuffer, 0, mixBufferSize);
2132 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01002133 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002134 }
2135 // TODO add standby time extension fct of effect tail
2136 }
2137
2138 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002139 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002140 }
2141 // sleepTime == 0 means we must write to audio hardware
2142 if (sleepTime == 0) {
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002143 for (size_t i = 0; i < effectChains.size(); i ++) {
2144 effectChains[i]->process_l();
2145 }
2146 // enable changes in effect chain
2147 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002148 mLastWriteTime = systemTime();
2149 mInWrite = true;
2150 mBytesWritten += mixBufferSize;
2151
Dima Zavin799a70e2011-04-18 16:57:27 -07002152 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002153 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2154 mNumWrites++;
2155 mInWrite = false;
2156 nsecs_t now = systemTime();
2157 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002158 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002159 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002160 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002161 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002162 ns2ms(delta), mNumDelayedWrites, this);
2163 lastWarning = now;
2164 }
2165 if (mStandby) {
2166 longStandbyExit = true;
2167 }
2168 }
2169 mStandby = false;
2170 } else {
2171 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002172 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002173 usleep(sleepTime);
2174 }
2175
2176 // finally let go of all our tracks, without the lock held
2177 // since we can't guarantee the destructors won't acquire that
2178 // same lock.
2179 tracksToRemove.clear();
2180
2181 // Effect chains will be actually deleted here if they were removed from
2182 // mEffectChains list during mixing or effects processing
2183 effectChains.clear();
2184 }
2185
2186 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002187 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002188 }
2189
Eric Laurentfeb0db62011-07-22 09:04:31 -07002190 releaseWakeLock();
2191
Glenn Kastenc0b52832012-02-24 11:18:09 -08002192 ALOGV("Thread %p type %d exiting", this, mType);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002193 return false;
2194}
2195
2196// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002197AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2198 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002199{
2200
Glenn Kasten29c23c32012-01-26 13:37:52 -08002201 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002202 // find out which tracks need to be processed
2203 size_t count = activeTracks.size();
2204 size_t mixedTracks = 0;
2205 size_t tracksWithEffect = 0;
2206
2207 float masterVolume = mMasterVolume;
2208 bool masterMute = mMasterMute;
2209
Eric Laurent571d49c2010-08-11 05:20:11 -07002210 if (masterMute) {
2211 masterVolume = 0;
2212 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002213 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002214 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002215 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002216 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002217 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002218 masterVolume = (float)((v + (1 << 23)) >> 24);
2219 chain.clear();
2220 }
2221
2222 for (size_t i=0 ; i<count ; i++) {
2223 sp<Track> t = activeTracks[i].promote();
2224 if (t == 0) continue;
2225
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002226 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002227 Track* const track = t.get();
2228 audio_track_cblk_t* cblk = track->cblk();
2229
2230 // The first time a track is added we wait
2231 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002232 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002233 // make sure that we have enough frames to mix one full buffer.
2234 // enforce this condition only once to enable draining the buffer in case the client
2235 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002236 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002237 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002238 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002239 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002240 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002241 if (t->sampleRate() == (int)mSampleRate) {
2242 minFrames = mFrameCount;
2243 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002244 // +1 for rounding and +1 for additional sample needed for interpolation
2245 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2246 // add frames already consumed but not yet released by the resampler
2247 // because cblk->framesReady() will include these frames
2248 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2249 // the minimum track buffer size is normally twice the number of frames necessary
2250 // to fill one buffer and the resampler should not leave more than one buffer worth
2251 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002252 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002253 }
2254 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002255 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002256 !track->isPaused() && !track->isTerminated())
2257 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002258 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002259
2260 mixedTracks++;
2261
2262 // track->mainBuffer() != mMixBuffer means there is an effect chain
2263 // connected to the track
2264 chain.clear();
2265 if (track->mainBuffer() != mMixBuffer) {
2266 chain = getEffectChain_l(track->sessionId());
2267 // Delegate volume control to effect in track effect chain if needed
2268 if (chain != 0) {
2269 tracksWithEffect++;
2270 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002271 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002272 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002273 }
2274 }
2275
2276
2277 int param = AudioMixer::VOLUME;
2278 if (track->mFillingUpStatus == Track::FS_FILLED) {
2279 // no ramp for the first volume setting
2280 track->mFillingUpStatus = Track::FS_ACTIVE;
2281 if (track->mState == TrackBase::RESUMING) {
2282 track->mState = TrackBase::ACTIVE;
2283 param = AudioMixer::RAMP_VOLUME;
2284 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002285 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002286 } else if (cblk->server != 0) {
2287 // If the track is stopped before the first frame was mixed,
2288 // do not apply ramp
2289 param = AudioMixer::RAMP_VOLUME;
2290 }
2291
2292 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002293 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002294 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002295 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002296 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002297 if (track->isPausing()) {
2298 track->setPaused();
2299 }
2300 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002301
Mathias Agopian65ab4712010-07-14 17:59:35 -07002302 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002303 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002304 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002305 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002306 vl = vlr & 0xFFFF;
2307 vr = vlr >> 16;
2308 // track volumes come from shared memory, so can't be trusted and must be clamped
2309 if (vl > MAX_GAIN_INT) {
2310 ALOGV("Track left volume out of range: %04X", vl);
2311 vl = MAX_GAIN_INT;
2312 }
2313 if (vr > MAX_GAIN_INT) {
2314 ALOGV("Track right volume out of range: %04X", vr);
2315 vr = MAX_GAIN_INT;
2316 }
2317 // now apply the master volume and stream type volume
2318 vl = (uint32_t)(v * vl) << 12;
2319 vr = (uint32_t)(v * vr) << 12;
2320 // assuming master volume and stream type volume each go up to 1.0,
2321 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002322
Glenn Kasten05632a52012-01-03 14:22:33 -08002323 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2324 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002325 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002326 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002327 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002328 }
2329 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002330 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002331 // Delegate volume control to effect in track effect chain if needed
2332 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2333 // Do not ramp volume if volume is controlled by effect
2334 param = AudioMixer::VOLUME;
2335 track->mHasVolumeController = true;
2336 } else {
2337 // force no volume ramp when volume controller was just disabled or removed
2338 // from effect chain to avoid volume spike
2339 if (track->mHasVolumeController) {
2340 param = AudioMixer::VOLUME;
2341 }
2342 track->mHasVolumeController = false;
2343 }
2344
2345 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002346 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002347 vl = (vl + (1 << 11)) >> 12;
2348 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2349 vr = (vr + (1 << 11)) >> 12;
2350 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002351
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002352 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 -07002353
Mathias Agopian65ab4712010-07-14 17:59:35 -07002354 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002355 mAudioMixer->setBufferProvider(name, track);
2356 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002357
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002358 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2359 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2360 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002361 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002362 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002363 AudioMixer::TRACK,
2364 AudioMixer::FORMAT, (void *)track->format());
2365 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002366 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002367 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002368 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002369 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002370 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002371 AudioMixer::RESAMPLE,
2372 AudioMixer::SAMPLE_RATE,
2373 (void *)(cblk->sampleRate));
2374 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002375 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002376 AudioMixer::TRACK,
2377 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2378 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002379 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002380 AudioMixer::TRACK,
2381 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2382
2383 // reset retry count
2384 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002385 // If one track is ready, set the mixer ready if:
2386 // - the mixer was not ready during previous round OR
2387 // - no other track is not ready
2388 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2389 mixerStatus != MIXER_TRACKS_ENABLED) {
2390 mixerStatus = MIXER_TRACKS_READY;
2391 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002392 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002393 //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 -07002394 if (track->isStopped()) {
2395 track->reset();
2396 }
2397 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2398 // We have consumed all the buffers of this track.
2399 // Remove it from the list of active tracks.
2400 tracksToRemove->add(track);
2401 } else {
2402 // No buffers for this track. Give it a few chances to
2403 // fill a buffer, then remove it from active list.
2404 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002405 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002406 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002407 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002408 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002409 // If one track is not ready, mark the mixer also not ready if:
2410 // - the mixer was ready during previous round OR
2411 // - no other track is ready
2412 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2413 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002414 mixerStatus = MIXER_TRACKS_ENABLED;
2415 }
2416 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002417 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002418 }
2419 }
2420
2421 // remove all the tracks that need to be...
2422 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002423 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002424 for (size_t i=0 ; i<count ; i++) {
2425 const sp<Track>& track = tracksToRemove->itemAt(i);
2426 mActiveTracks.remove(track);
2427 if (track->mainBuffer() != mMixBuffer) {
2428 chain = getEffectChain_l(track->sessionId());
2429 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002430 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002431 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002432 }
2433 }
2434 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002435 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002436 }
2437 }
2438 }
2439
2440 // mix buffer must be cleared if all tracks are connected to an
2441 // effect chain as in this case the mixer will not write to
2442 // mix buffer and track effects will accumulate into it
2443 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2444 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2445 }
2446
Eric Laurent27741442012-01-17 19:20:12 -08002447 mPrevMixerStatus = mixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002448 return mixerStatus;
2449}
2450
Glenn Kastenfff6d712012-01-12 16:38:12 -08002451void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002452{
Steve Block3856b092011-10-20 11:56:00 +01002453 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002454 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002455 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002456
Mathias Agopian65ab4712010-07-14 17:59:35 -07002457 size_t size = mTracks.size();
2458 for (size_t i = 0; i < size; i++) {
2459 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08002460 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002461 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002462 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002463 }
2464 }
2465}
2466
Glenn Kastenfff6d712012-01-12 16:38:12 -08002467void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002468{
Steve Block3856b092011-10-20 11:56:00 +01002469 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002470 this, streamType, valid);
2471 Mutex::Autolock _l(mLock);
2472
2473 mStreamTypes[streamType].valid = valid;
2474}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002475
2476// getTrackName_l() must be called with ThreadBase::mLock held
2477int AudioFlinger::MixerThread::getTrackName_l()
2478{
2479 return mAudioMixer->getTrackName();
2480}
2481
2482// deleteTrackName_l() must be called with ThreadBase::mLock held
2483void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2484{
Steve Block3856b092011-10-20 11:56:00 +01002485 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002486 mAudioMixer->deleteTrackName(name);
2487}
2488
2489// checkForNewParameters_l() must be called with ThreadBase::mLock held
2490bool AudioFlinger::MixerThread::checkForNewParameters_l()
2491{
2492 bool reconfig = false;
2493
2494 while (!mNewParameters.isEmpty()) {
2495 status_t status = NO_ERROR;
2496 String8 keyValuePair = mNewParameters[0];
2497 AudioParameter param = AudioParameter(keyValuePair);
2498 int value;
2499
2500 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2501 reconfig = true;
2502 }
2503 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002504 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002505 status = BAD_VALUE;
2506 } else {
2507 reconfig = true;
2508 }
2509 }
2510 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002511 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002512 status = BAD_VALUE;
2513 } else {
2514 reconfig = true;
2515 }
2516 }
2517 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2518 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002519 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002520 // if frame count is changed after track creation
2521 if (!mTracks.isEmpty()) {
2522 status = INVALID_OPERATION;
2523 } else {
2524 reconfig = true;
2525 }
2526 }
2527 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002528 // when changing the audio output device, call addBatteryData to notify
2529 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002530 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002531 uint32_t params = 0;
2532 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002533 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002534 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2535 }
2536
2537 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002538 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002539 // check if any other device (except speaker) is on
2540 if (value & deviceWithoutSpeaker ) {
2541 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2542 }
2543
2544 if (params != 0) {
2545 addBatteryData(params);
2546 }
2547 }
2548
Mathias Agopian65ab4712010-07-14 17:59:35 -07002549 // forward device change to effects that have requested to be
2550 // aware of attached audio device.
2551 mDevice = (uint32_t)value;
2552 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002553 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002554 }
2555 }
2556
2557 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002558 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002559 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002560 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002561 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002562 mStandby = true;
2563 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002564 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002565 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002566 }
2567 if (status == NO_ERROR && reconfig) {
2568 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002569 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2570 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002571 readOutputParameters();
2572 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2573 for (size_t i = 0; i < mTracks.size() ; i++) {
2574 int name = getTrackName_l();
2575 if (name < 0) break;
2576 mTracks[i]->mName = name;
2577 // limit track sample rate to 2 x new output sample rate
2578 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2579 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2580 }
2581 }
2582 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2583 }
2584 }
2585
2586 mNewParameters.removeAt(0);
2587
2588 mParamStatus = status;
2589 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002590 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2591 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002592 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002593 }
2594 return reconfig;
2595}
2596
2597status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2598{
2599 const size_t SIZE = 256;
2600 char buffer[SIZE];
2601 String8 result;
2602
2603 PlaybackThread::dumpInternals(fd, args);
2604
2605 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2606 result.append(buffer);
2607 write(fd, result.string(), result.size());
2608 return NO_ERROR;
2609}
2610
Mathias Agopian65ab4712010-07-14 17:59:35 -07002611uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2612{
Eric Laurent60e18242010-07-29 06:50:24 -07002613 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002614}
2615
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002616uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2617{
2618 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2619}
2620
Mathias Agopian65ab4712010-07-14 17:59:35 -07002621// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002622AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2623 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002624 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002625 // mLeftVolFloat, mRightVolFloat
2626 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002627{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002628}
2629
2630AudioFlinger::DirectOutputThread::~DirectOutputThread()
2631{
2632}
2633
Mathias Agopian65ab4712010-07-14 17:59:35 -07002634void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2635{
2636 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002637 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002638 return;
2639 }
2640
2641 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002642 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002643 size_t count = mFrameCount * mChannelCount;
2644 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2645 int16_t *dst = mMixBuffer + count-1;
2646 while(count--) {
2647 *dst-- = (int16_t)(*src--^0x80) << 8;
2648 }
2649 }
2650
2651 size_t frameCount = mFrameCount;
2652 int16_t *out = mMixBuffer;
2653 if (ramp) {
2654 if (mChannelCount == 1) {
2655 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2656 int32_t vlInc = d / (int32_t)frameCount;
2657 int32_t vl = ((int32_t)mLeftVolShort << 16);
2658 do {
2659 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2660 out++;
2661 vl += vlInc;
2662 } while (--frameCount);
2663
2664 } else {
2665 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2666 int32_t vlInc = d / (int32_t)frameCount;
2667 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2668 int32_t vrInc = d / (int32_t)frameCount;
2669 int32_t vl = ((int32_t)mLeftVolShort << 16);
2670 int32_t vr = ((int32_t)mRightVolShort << 16);
2671 do {
2672 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2673 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2674 out += 2;
2675 vl += vlInc;
2676 vr += vrInc;
2677 } while (--frameCount);
2678 }
2679 } else {
2680 if (mChannelCount == 1) {
2681 do {
2682 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2683 out++;
2684 } while (--frameCount);
2685 } else {
2686 do {
2687 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2688 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2689 out += 2;
2690 } while (--frameCount);
2691 }
2692 }
2693
2694 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002695 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002696 size_t count = mFrameCount * mChannelCount;
2697 int16_t *src = mMixBuffer;
2698 uint8_t *dst = (uint8_t *)mMixBuffer;
2699 while(count--) {
2700 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2701 }
2702 }
2703
2704 mLeftVolShort = leftVol;
2705 mRightVolShort = rightVol;
2706}
2707
2708bool AudioFlinger::DirectOutputThread::threadLoop()
2709{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002710 sp<Track> trackToRemove;
2711 sp<Track> activeTrack;
2712 nsecs_t standbyTime = systemTime();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002713 size_t mixBufferSize = mFrameCount*mFrameSize;
2714 uint32_t activeSleepTime = activeSleepTimeUs();
2715 uint32_t idleSleepTime = idleSleepTimeUs();
2716 uint32_t sleepTime = idleSleepTime;
2717 // use shorter standby delay as on normal output to release
2718 // hardware resources as soon as possible
2719 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2720
Eric Laurentfeb0db62011-07-22 09:04:31 -07002721 acquireWakeLock();
2722
Mathias Agopian65ab4712010-07-14 17:59:35 -07002723 while (!exitPending())
2724 {
2725 bool rampVolume;
2726 uint16_t leftVol;
2727 uint16_t rightVol;
2728 Vector< sp<EffectChain> > effectChains;
2729
2730 processConfigEvents();
2731
Glenn Kasten5d4eeea2012-02-24 07:25:40 -08002732 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002733 { // scope for the mLock
2734
2735 Mutex::Autolock _l(mLock);
2736
2737 if (checkForNewParameters_l()) {
2738 mixBufferSize = mFrameCount*mFrameSize;
2739 activeSleepTime = activeSleepTimeUs();
2740 idleSleepTime = idleSleepTimeUs();
2741 standbyDelay = microseconds(activeSleepTime*2);
2742 }
2743
2744 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002745 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2746 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002747 // wait until we have something to do...
2748 if (!mStandby) {
Glenn Kastenc0b52832012-02-24 11:18:09 -08002749 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07002750 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002751 mStandby = true;
2752 mBytesWritten = 0;
2753 }
2754
2755 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2756 // we're about to wait, flush the binder command buffer
2757 IPCThreadState::self()->flushCommands();
2758
2759 if (exitPending()) break;
2760
Eric Laurentfeb0db62011-07-22 09:04:31 -07002761 releaseWakeLock_l();
Glenn Kastenc0b52832012-02-24 11:18:09 -08002762 ALOGV("Thread %p type %d TID %d going to sleep", this, mType, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002763 mWaitWorkCV.wait(mLock);
Glenn Kastenc0b52832012-02-24 11:18:09 -08002764 ALOGV("Thread %p type %d TID %d waking up", this, mType, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002765 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002766
Glenn Kasten37d825e2012-02-24 07:21:48 -08002767 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002768
2769 standbyTime = systemTime() + standbyDelay;
2770 sleepTime = idleSleepTime;
2771 continue;
2772 }
2773 }
2774
2775 effectChains = mEffectChains;
2776
2777 // find out which tracks need to be processed
2778 if (mActiveTracks.size() != 0) {
2779 sp<Track> t = mActiveTracks[0].promote();
2780 if (t == 0) continue;
2781
2782 Track* const track = t.get();
2783 audio_track_cblk_t* cblk = track->cblk();
2784
2785 // The first time a track is added we wait
2786 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002787 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002788 !track->isPaused() && !track->isTerminated())
2789 {
Steve Block3856b092011-10-20 11:56:00 +01002790 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002791
2792 if (track->mFillingUpStatus == Track::FS_FILLED) {
2793 track->mFillingUpStatus = Track::FS_ACTIVE;
2794 mLeftVolFloat = mRightVolFloat = 0;
2795 mLeftVolShort = mRightVolShort = 0;
2796 if (track->mState == TrackBase::RESUMING) {
2797 track->mState = TrackBase::ACTIVE;
2798 rampVolume = true;
2799 }
2800 } else if (cblk->server != 0) {
2801 // If the track is stopped before the first frame was mixed,
2802 // do not apply ramp
2803 rampVolume = true;
2804 }
2805 // compute volume for this track
2806 float left, right;
2807 if (track->isMuted() || mMasterMute || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002808 mStreamTypes[track->streamType()].mute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002809 left = right = 0;
2810 if (track->isPausing()) {
2811 track->setPaused();
2812 }
2813 } else {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002814 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002815 float v = mMasterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002816 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002817 float v_clamped = v * (vlr & 0xFFFF);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002818 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2819 left = v_clamped/MAX_GAIN;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002820 v_clamped = v * (vlr >> 16);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002821 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2822 right = v_clamped/MAX_GAIN;
2823 }
2824
2825 if (left != mLeftVolFloat || right != mRightVolFloat) {
2826 mLeftVolFloat = left;
2827 mRightVolFloat = right;
2828
2829 // If audio HAL implements volume control,
2830 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002831 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002832 left = 1.0f;
2833 right = 1.0f;
2834 }
2835
2836 // Convert volumes from float to 8.24
2837 uint32_t vl = (uint32_t)(left * (1 << 24));
2838 uint32_t vr = (uint32_t)(right * (1 << 24));
2839
2840 // Delegate volume control to effect in track effect chain if needed
2841 // only one effect chain can be present on DirectOutputThread, so if
2842 // there is one, the track is connected to it
2843 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002844 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002845 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002846 rampVolume = false;
2847 }
2848 }
2849
2850 // Convert volumes from 8.24 to 4.12 format
2851 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2852 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2853 leftVol = (uint16_t)v_clamped;
2854 v_clamped = (vr + (1 << 11)) >> 12;
2855 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2856 rightVol = (uint16_t)v_clamped;
2857 } else {
2858 leftVol = mLeftVolShort;
2859 rightVol = mRightVolShort;
2860 rampVolume = false;
2861 }
2862
2863 // reset retry count
2864 track->mRetryCount = kMaxTrackRetriesDirect;
2865 activeTrack = t;
2866 mixerStatus = MIXER_TRACKS_READY;
2867 } else {
Steve Block3856b092011-10-20 11:56:00 +01002868 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002869 if (track->isStopped()) {
2870 track->reset();
2871 }
2872 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2873 // We have consumed all the buffers of this track.
2874 // Remove it from the list of active tracks.
2875 trackToRemove = track;
2876 } else {
2877 // No buffers for this track. Give it a few chances to
2878 // fill a buffer, then remove it from active list.
2879 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002880 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002881 trackToRemove = track;
2882 } else {
2883 mixerStatus = MIXER_TRACKS_ENABLED;
2884 }
2885 }
2886 }
2887 }
2888
2889 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002890 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002891 mActiveTracks.remove(trackToRemove);
2892 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002893 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002894 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002895 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002896 }
2897 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002898 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002899 }
2900 }
2901
Eric Laurentde070132010-07-13 04:45:46 -07002902 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002903 }
2904
Glenn Kastenf6b16782011-12-15 09:51:17 -08002905 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002906 AudioBufferProvider::Buffer buffer;
2907 size_t frameCount = mFrameCount;
Glenn Kastena1117922012-01-26 10:53:32 -08002908 int8_t *curBuf = (int8_t *)mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002909 // output audio to hardware
2910 while (frameCount) {
2911 buffer.frameCount = frameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08002912 activeTrack->getNextBuffer(&buffer);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002913 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002914 memset(curBuf, 0, frameCount * mFrameSize);
2915 break;
2916 }
2917 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2918 frameCount -= buffer.frameCount;
2919 curBuf += buffer.frameCount * mFrameSize;
2920 activeTrack->releaseBuffer(&buffer);
2921 }
2922 sleepTime = 0;
2923 standbyTime = systemTime() + standbyDelay;
2924 } else {
2925 if (sleepTime == 0) {
2926 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2927 sleepTime = activeSleepTime;
2928 } else {
2929 sleepTime = idleSleepTime;
2930 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002931 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002932 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2933 sleepTime = 0;
2934 }
2935 }
2936
2937 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002938 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002939 }
2940 // sleepTime == 0 means we must write to audio hardware
2941 if (sleepTime == 0) {
2942 if (mixerStatus == MIXER_TRACKS_READY) {
2943 applyVolume(leftVol, rightVol, rampVolume);
2944 }
2945 for (size_t i = 0; i < effectChains.size(); i ++) {
2946 effectChains[i]->process_l();
2947 }
Eric Laurentde070132010-07-13 04:45:46 -07002948 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002949
2950 mLastWriteTime = systemTime();
2951 mInWrite = true;
2952 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002953 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002954 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2955 mNumWrites++;
2956 mInWrite = false;
2957 mStandby = false;
2958 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002959 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002960 usleep(sleepTime);
2961 }
2962
2963 // finally let go of removed track, without the lock held
2964 // since we can't guarantee the destructors won't acquire that
2965 // same lock.
2966 trackToRemove.clear();
2967 activeTrack.clear();
2968
2969 // Effect chains will be actually deleted here if they were removed from
2970 // mEffectChains list during mixing or effects processing
2971 effectChains.clear();
2972 }
2973
2974 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002975 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002976 }
2977
Eric Laurentfeb0db62011-07-22 09:04:31 -07002978 releaseWakeLock();
2979
Glenn Kastenc0b52832012-02-24 11:18:09 -08002980 ALOGV("Thread %p type %d exiting", this, mType);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002981 return false;
2982}
2983
2984// getTrackName_l() must be called with ThreadBase::mLock held
2985int AudioFlinger::DirectOutputThread::getTrackName_l()
2986{
2987 return 0;
2988}
2989
2990// deleteTrackName_l() must be called with ThreadBase::mLock held
2991void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2992{
2993}
2994
2995// checkForNewParameters_l() must be called with ThreadBase::mLock held
2996bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2997{
2998 bool reconfig = false;
2999
3000 while (!mNewParameters.isEmpty()) {
3001 status_t status = NO_ERROR;
3002 String8 keyValuePair = mNewParameters[0];
3003 AudioParameter param = AudioParameter(keyValuePair);
3004 int value;
3005
3006 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3007 // do not accept frame count changes if tracks are open as the track buffer
3008 // size depends on frame count and correct behavior would not be garantied
3009 // if frame count is changed after track creation
3010 if (!mTracks.isEmpty()) {
3011 status = INVALID_OPERATION;
3012 } else {
3013 reconfig = true;
3014 }
3015 }
3016 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003017 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003018 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003019 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003020 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003021 mStandby = true;
3022 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07003023 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003024 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003025 }
3026 if (status == NO_ERROR && reconfig) {
3027 readOutputParameters();
3028 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3029 }
3030 }
3031
3032 mNewParameters.removeAt(0);
3033
3034 mParamStatus = status;
3035 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003036 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3037 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003038 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003039 }
3040 return reconfig;
3041}
3042
3043uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
3044{
3045 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003046 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003047 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003048 } else {
3049 time = 10000;
3050 }
3051 return time;
3052}
3053
3054uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
3055{
3056 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003057 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003058 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003059 } else {
3060 time = 10000;
3061 }
3062 return time;
3063}
3064
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003065uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
3066{
3067 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003068 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003069 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3070 } else {
3071 time = 10000;
3072 }
3073 return time;
3074}
3075
3076
Mathias Agopian65ab4712010-07-14 17:59:35 -07003077// ----------------------------------------------------------------------------
3078
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003079AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003080 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003081 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3082 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003083{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003084 addOutputTrack(mainThread);
3085}
3086
3087AudioFlinger::DuplicatingThread::~DuplicatingThread()
3088{
3089 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3090 mOutputTracks[i]->destroy();
3091 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003092}
3093
3094bool AudioFlinger::DuplicatingThread::threadLoop()
3095{
3096 Vector< sp<Track> > tracksToRemove;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003097 nsecs_t standbyTime = systemTime();
3098 size_t mixBufferSize = mFrameCount*mFrameSize;
3099 SortedVector< sp<OutputTrack> > outputTracks;
3100 uint32_t writeFrames = 0;
3101 uint32_t activeSleepTime = activeSleepTimeUs();
3102 uint32_t idleSleepTime = idleSleepTimeUs();
3103 uint32_t sleepTime = idleSleepTime;
3104 Vector< sp<EffectChain> > effectChains;
3105
Eric Laurentfeb0db62011-07-22 09:04:31 -07003106 acquireWakeLock();
3107
Mathias Agopian65ab4712010-07-14 17:59:35 -07003108 while (!exitPending())
3109 {
3110 processConfigEvents();
3111
Glenn Kasten5d4eeea2012-02-24 07:25:40 -08003112 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003113 { // scope for the mLock
3114
3115 Mutex::Autolock _l(mLock);
3116
3117 if (checkForNewParameters_l()) {
3118 mixBufferSize = mFrameCount*mFrameSize;
3119 updateWaitTime();
3120 activeSleepTime = activeSleepTimeUs();
3121 idleSleepTime = idleSleepTimeUs();
3122 }
3123
3124 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3125
3126 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3127 outputTracks.add(mOutputTracks[i]);
3128 }
3129
3130 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08003131 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3132 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003133 if (!mStandby) {
3134 for (size_t i = 0; i < outputTracks.size(); i++) {
3135 outputTracks[i]->stop();
3136 }
3137 mStandby = true;
3138 mBytesWritten = 0;
3139 }
3140
3141 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3142 // we're about to wait, flush the binder command buffer
3143 IPCThreadState::self()->flushCommands();
3144 outputTracks.clear();
3145
3146 if (exitPending()) break;
3147
Eric Laurentfeb0db62011-07-22 09:04:31 -07003148 releaseWakeLock_l();
Glenn Kastenc0b52832012-02-24 11:18:09 -08003149 // wait until we have something to do...
3150 ALOGV("Thread %p type %d TID %d going to sleep", this, mType, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003151 mWaitWorkCV.wait(mLock);
Glenn Kastenc0b52832012-02-24 11:18:09 -08003152 ALOGV("Thread %p type %d TID %d waking up", this, mType, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003153 acquireWakeLock_l();
3154
Glenn Kasten37d825e2012-02-24 07:21:48 -08003155 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003156
John Grossman4ff14ba2012-02-08 16:37:41 -08003157 standbyTime = systemTime() + mStandbyTimeInNsecs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003158 sleepTime = idleSleepTime;
3159 continue;
3160 }
3161 }
3162
3163 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3164
3165 // prevent any changes in effect chain list and in each effect chain
3166 // during mixing and effect process as the audio buffers could be deleted
3167 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003168 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003169 }
3170
Glenn Kastenf6b16782011-12-15 09:51:17 -08003171 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003172 // mix buffers...
3173 if (outputsReady(outputTracks)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08003174 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003175 } else {
3176 memset(mMixBuffer, 0, mixBufferSize);
3177 }
3178 sleepTime = 0;
3179 writeFrames = mFrameCount;
3180 } else {
3181 if (sleepTime == 0) {
3182 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3183 sleepTime = activeSleepTime;
3184 } else {
3185 sleepTime = idleSleepTime;
3186 }
3187 } else if (mBytesWritten != 0) {
3188 // flush remaining overflow buffers in output tracks
3189 for (size_t i = 0; i < outputTracks.size(); i++) {
3190 if (outputTracks[i]->isActive()) {
3191 sleepTime = 0;
3192 writeFrames = 0;
3193 memset(mMixBuffer, 0, mixBufferSize);
3194 break;
3195 }
3196 }
3197 }
3198 }
3199
3200 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003201 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003202 }
3203 // sleepTime == 0 means we must write to audio hardware
3204 if (sleepTime == 0) {
3205 for (size_t i = 0; i < effectChains.size(); i ++) {
3206 effectChains[i]->process_l();
3207 }
3208 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003209 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003210
John Grossman4ff14ba2012-02-08 16:37:41 -08003211 standbyTime = systemTime() + mStandbyTimeInNsecs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003212 for (size_t i = 0; i < outputTracks.size(); i++) {
3213 outputTracks[i]->write(mMixBuffer, writeFrames);
3214 }
3215 mStandby = false;
3216 mBytesWritten += mixBufferSize;
3217 } else {
3218 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003219 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220 usleep(sleepTime);
3221 }
3222
3223 // finally let go of all our tracks, without the lock held
3224 // since we can't guarantee the destructors won't acquire that
3225 // same lock.
3226 tracksToRemove.clear();
3227 outputTracks.clear();
3228
3229 // Effect chains will be actually deleted here if they were removed from
3230 // mEffectChains list during mixing or effects processing
3231 effectChains.clear();
3232 }
3233
Eric Laurentfeb0db62011-07-22 09:04:31 -07003234 releaseWakeLock();
3235
Glenn Kastenc0b52832012-02-24 11:18:09 -08003236 ALOGV("Thread %p type %d exiting", this, mType);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003237 return false;
3238}
3239
3240void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3241{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003242 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003243 // FIXME explain this formula
Mathias Agopian65ab4712010-07-14 17:59:35 -07003244 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003245 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003246 this,
3247 mSampleRate,
3248 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003249 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003250 frameCount);
3251 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003252 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003253 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003254 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003255 updateWaitTime();
3256 }
3257}
3258
3259void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3260{
3261 Mutex::Autolock _l(mLock);
3262 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003263 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003264 mOutputTracks[i]->destroy();
3265 mOutputTracks.removeAt(i);
3266 updateWaitTime();
3267 return;
3268 }
3269 }
Steve Block3856b092011-10-20 11:56:00 +01003270 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003271}
3272
3273void AudioFlinger::DuplicatingThread::updateWaitTime()
3274{
3275 mWaitTimeMs = UINT_MAX;
3276 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3277 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003278 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003279 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3280 if (waitTimeMs < mWaitTimeMs) {
3281 mWaitTimeMs = waitTimeMs;
3282 }
3283 }
3284 }
3285}
3286
3287
3288bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3289{
3290 for (size_t i = 0; i < outputTracks.size(); i++) {
3291 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3292 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003293 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003294 return false;
3295 }
3296 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3297 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003298 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003299 return false;
3300 }
3301 }
3302 return true;
3303}
3304
3305uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3306{
3307 return (mWaitTimeMs * 1000) / 2;
3308}
3309
3310// ----------------------------------------------------------------------------
3311
3312// TrackBase constructor must be called with AudioFlinger::mLock held
3313AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003314 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003315 const sp<Client>& client,
3316 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003317 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003318 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003319 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003320 const sp<IMemory>& sharedBuffer,
3321 int sessionId)
3322 : RefBase(),
3323 mThread(thread),
3324 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003325 mCblk(NULL),
3326 // mBuffer
3327 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003328 mFrameCount(0),
3329 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003330 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003331 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003332 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003333 // mChannelCount
3334 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003335{
Steve Block3856b092011-10-20 11:56:00 +01003336 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003337
Steve Blockb8a80522011-12-20 16:23:08 +00003338 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003339 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003340 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003341 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3342 if (sharedBuffer == 0) {
3343 size += bufferSize;
3344 }
3345
3346 if (client != NULL) {
3347 mCblkMemory = client->heap()->allocate(size);
3348 if (mCblkMemory != 0) {
3349 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003350 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003351 new(mCblk) audio_track_cblk_t();
3352 // clear all buffers
3353 mCblk->frameCount = frameCount;
3354 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003355 mChannelCount = channelCount;
3356 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003357 if (sharedBuffer == 0) {
3358 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3359 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3360 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003361 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003362 mCblk->flags = CBLK_UNDERRUN_ON;
3363 } else {
3364 mBuffer = sharedBuffer->pointer();
3365 }
3366 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3367 }
3368 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003369 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003370 client->heap()->dump("AudioTrack");
3371 return;
3372 }
3373 } else {
3374 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003375 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003376 new(mCblk) audio_track_cblk_t();
3377 // clear all buffers
3378 mCblk->frameCount = frameCount;
3379 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003380 mChannelCount = channelCount;
3381 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003382 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3383 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3384 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003385 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003386 mCblk->flags = CBLK_UNDERRUN_ON;
3387 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003388 }
3389}
3390
3391AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3392{
Glenn Kastena0d68332012-01-27 16:47:15 -08003393 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003394 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003395 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003396 } else {
3397 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003398 }
3399 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003400 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003401 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003402 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003403 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003404 // If the client's reference count drops to zero, the associated destructor
3405 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3406 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003407 mClient.clear();
3408 }
3409}
3410
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003411// AudioBufferProvider interface
3412// getNextBuffer() = 0;
3413// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07003414void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3415{
Glenn Kastene0feee32011-12-13 11:53:26 -08003416 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003417 mFrameCount = buffer->frameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003418 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003419 buffer->frameCount = 0;
3420}
3421
3422bool AudioFlinger::ThreadBase::TrackBase::step() {
3423 bool result;
3424 audio_track_cblk_t* cblk = this->cblk();
3425
3426 result = cblk->stepServer(mFrameCount);
3427 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003428 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003429 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003430 }
3431 return result;
3432}
3433
3434void AudioFlinger::ThreadBase::TrackBase::reset() {
3435 audio_track_cblk_t* cblk = this->cblk();
3436
3437 cblk->user = 0;
3438 cblk->server = 0;
3439 cblk->userBase = 0;
3440 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003441 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01003442 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003443}
3444
Mathias Agopian65ab4712010-07-14 17:59:35 -07003445int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3446 return (int)mCblk->sampleRate;
3447}
3448
Mathias Agopian65ab4712010-07-14 17:59:35 -07003449void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3450 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003451 size_t frameSize = cblk->frameSize;
3452 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3453 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003454
3455 // Check validity of returned pointer in case the track control block would have been corrupted.
3456 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003457 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003458 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 -07003459 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003460 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003461 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003462 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003463 }
3464
3465 return bufferStart;
3466}
3467
3468// ----------------------------------------------------------------------------
3469
3470// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3471AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003472 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003473 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003474 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003475 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003476 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003477 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003478 int frameCount,
3479 const sp<IMemory>& sharedBuffer,
3480 int sessionId)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003481 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003482 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3483 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003484{
3485 if (mCblk != NULL) {
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003486 if (thread != NULL) {
3487 mName = thread->getTrackName_l();
3488 mMainBuffer = thread->mixBuffer();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003489 }
Glenn Kasten23d82a92012-02-03 11:10:00 -08003490 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003491 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003492 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003493 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003494 mStreamType = streamType;
3495 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3496 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003497 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003498 }
3499}
3500
3501AudioFlinger::PlaybackThread::Track::~Track()
3502{
Steve Block3856b092011-10-20 11:56:00 +01003503 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003504 sp<ThreadBase> thread = mThread.promote();
3505 if (thread != 0) {
3506 Mutex::Autolock _l(thread->mLock);
3507 mState = TERMINATED;
3508 }
3509}
3510
3511void AudioFlinger::PlaybackThread::Track::destroy()
3512{
3513 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3514 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08003515 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003516 // we must acquire a strong reference on this Track before locking mLock
3517 // here so that the destructor is called only when exiting this function.
3518 // On the other hand, as long as Track::destroy() is only called by
3519 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3520 // this Track with its member mTrack.
3521 sp<Track> keep(this);
3522 { // scope for mLock
3523 sp<ThreadBase> thread = mThread.promote();
3524 if (thread != 0) {
3525 if (!isOutputTrack()) {
3526 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08003527 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003528
3529 // to track the speaker usage
3530 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003531 }
3532 AudioSystem::releaseOutput(thread->id());
3533 }
3534 Mutex::Autolock _l(thread->mLock);
3535 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3536 playbackThread->destroyTrack_l(this);
3537 }
3538 }
3539}
3540
3541void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3542{
Glenn Kasten83d86532012-01-17 14:39:34 -08003543 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003544 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 -07003545 mName - AudioMixer::TRACK0,
Glenn Kasten44deb052012-02-05 18:09:08 -08003546 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003547 mStreamType,
3548 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003549 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003550 mSessionId,
3551 mFrameCount,
3552 mState,
3553 mMute,
3554 mFillingUpStatus,
3555 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003556 vlr & 0xFFFF,
3557 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003558 mCblk->server,
3559 mCblk->user,
3560 (int)mMainBuffer,
3561 (int)mAuxBuffer);
3562}
3563
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003564// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08003565status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
3566 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003567{
3568 audio_track_cblk_t* cblk = this->cblk();
3569 uint32_t framesReady;
3570 uint32_t framesReq = buffer->frameCount;
3571
3572 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003573 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003574 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003575 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003576 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003577 }
3578
3579 framesReady = cblk->framesReady();
3580
Glenn Kastenf6b16782011-12-15 09:51:17 -08003581 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003582 uint32_t s = cblk->server;
3583 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3584
3585 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3586 if (framesReq > framesReady) {
3587 framesReq = framesReady;
3588 }
3589 if (s + framesReq > bufferEnd) {
3590 framesReq = bufferEnd - s;
3591 }
3592
3593 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003594 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003595
3596 buffer->frameCount = framesReq;
3597 return NO_ERROR;
3598 }
3599
3600getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003601 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003602 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003603 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003604 return NOT_ENOUGH_DATA;
3605}
3606
John Grossman4ff14ba2012-02-08 16:37:41 -08003607uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const{
3608 return mCblk->framesReady();
3609}
3610
Mathias Agopian65ab4712010-07-14 17:59:35 -07003611bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003612 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003613
John Grossman4ff14ba2012-02-08 16:37:41 -08003614 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003615 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3616 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003617 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003618 return true;
3619 }
3620 return false;
3621}
3622
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003623status_t AudioFlinger::PlaybackThread::Track::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003624{
3625 status_t status = NO_ERROR;
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003626 ALOGV("start(%d), calling pid %d session %d tid %d",
3627 mName, IPCThreadState::self()->getCallingPid(), mSessionId, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003628 sp<ThreadBase> thread = mThread.promote();
3629 if (thread != 0) {
3630 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003631 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003632 // here the track could be either new, or restarted
3633 // in both cases "unstop" the track
3634 if (mState == PAUSED) {
3635 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003636 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003637 } else {
3638 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003639 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003640 }
3641
3642 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3643 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003644 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003645 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003646
3647 // to track the speaker usage
3648 if (status == NO_ERROR) {
3649 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3650 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003651 }
3652 if (status == NO_ERROR) {
3653 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3654 playbackThread->addTrack_l(this);
3655 } else {
3656 mState = state;
3657 }
3658 } else {
3659 status = BAD_VALUE;
3660 }
3661 return status;
3662}
3663
3664void AudioFlinger::PlaybackThread::Track::stop()
3665{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003666 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003667 sp<ThreadBase> thread = mThread.promote();
3668 if (thread != 0) {
3669 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003670 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003671 if (mState > STOPPED) {
3672 mState = STOPPED;
3673 // If the track is not active (PAUSED and buffers full), flush buffers
3674 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3675 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3676 reset();
3677 }
Steve Block3856b092011-10-20 11:56:00 +01003678 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003679 }
3680 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3681 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003682 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003683 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003684
3685 // to track the speaker usage
3686 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003687 }
3688 }
3689}
3690
3691void AudioFlinger::PlaybackThread::Track::pause()
3692{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003693 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003694 sp<ThreadBase> thread = mThread.promote();
3695 if (thread != 0) {
3696 Mutex::Autolock _l(thread->mLock);
3697 if (mState == ACTIVE || mState == RESUMING) {
3698 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003699 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003700 if (!isOutputTrack()) {
3701 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003702 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003703 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003704
3705 // to track the speaker usage
3706 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003707 }
3708 }
3709 }
3710}
3711
3712void AudioFlinger::PlaybackThread::Track::flush()
3713{
Steve Block3856b092011-10-20 11:56:00 +01003714 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003715 sp<ThreadBase> thread = mThread.promote();
3716 if (thread != 0) {
3717 Mutex::Autolock _l(thread->mLock);
3718 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3719 return;
3720 }
3721 // No point remaining in PAUSED state after a flush => go to
3722 // STOPPED state
3723 mState = STOPPED;
3724
Eric Laurent38ccae22011-03-28 18:37:07 -07003725 // do not reset the track if it is still in the process of being stopped or paused.
3726 // this will be done by prepareTracks_l() when the track is stopped.
3727 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3728 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3729 reset();
3730 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003731 }
3732}
3733
3734void AudioFlinger::PlaybackThread::Track::reset()
3735{
3736 // Do not reset twice to avoid discarding data written just after a flush and before
3737 // the audioflinger thread detects the track is stopped.
3738 if (!mResetDone) {
3739 TrackBase::reset();
3740 // Force underrun condition to avoid false underrun callback until first data is
3741 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003742 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3743 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003744 mFillingUpStatus = FS_FILLING;
3745 mResetDone = true;
3746 }
3747}
3748
3749void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3750{
3751 mMute = muted;
3752}
3753
Mathias Agopian65ab4712010-07-14 17:59:35 -07003754status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3755{
3756 status_t status = DEAD_OBJECT;
3757 sp<ThreadBase> thread = mThread.promote();
3758 if (thread != 0) {
3759 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3760 status = playbackThread->attachAuxEffect(this, EffectId);
3761 }
3762 return status;
3763}
3764
3765void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3766{
3767 mAuxEffectId = EffectId;
3768 mAuxBuffer = buffer;
3769}
3770
John Grossman4ff14ba2012-02-08 16:37:41 -08003771// timed audio tracks
3772
3773sp<AudioFlinger::PlaybackThread::TimedTrack>
3774AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003775 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003776 const sp<Client>& client,
3777 audio_stream_type_t streamType,
3778 uint32_t sampleRate,
3779 audio_format_t format,
3780 uint32_t channelMask,
3781 int frameCount,
3782 const sp<IMemory>& sharedBuffer,
3783 int sessionId) {
3784 if (!client->reserveTimedTrack())
3785 return NULL;
3786
3787 sp<TimedTrack> track = new TimedTrack(
3788 thread, client, streamType, sampleRate, format, channelMask, frameCount,
3789 sharedBuffer, sessionId);
3790
3791 if (track == NULL) {
3792 client->releaseTimedTrack();
3793 return NULL;
3794 }
3795
3796 return track;
3797}
3798
3799AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003800 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003801 const sp<Client>& client,
3802 audio_stream_type_t streamType,
3803 uint32_t sampleRate,
3804 audio_format_t format,
3805 uint32_t channelMask,
3806 int frameCount,
3807 const sp<IMemory>& sharedBuffer,
3808 int sessionId)
3809 : Track(thread, client, streamType, sampleRate, format, channelMask,
3810 frameCount, sharedBuffer, sessionId),
3811 mTimedSilenceBuffer(NULL),
3812 mTimedSilenceBufferSize(0),
3813 mTimedAudioOutputOnTime(false),
3814 mMediaTimeTransformValid(false)
3815{
3816 LocalClock lc;
3817 mLocalTimeFreq = lc.getLocalFreq();
3818
3819 mLocalTimeToSampleTransform.a_zero = 0;
3820 mLocalTimeToSampleTransform.b_zero = 0;
3821 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3822 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3823 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3824 &mLocalTimeToSampleTransform.a_to_b_denom);
3825}
3826
3827AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3828 mClient->releaseTimedTrack();
3829 delete [] mTimedSilenceBuffer;
3830}
3831
3832status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3833 size_t size, sp<IMemory>* buffer) {
3834
3835 Mutex::Autolock _l(mTimedBufferQueueLock);
3836
3837 trimTimedBufferQueue_l();
3838
3839 // lazily initialize the shared memory heap for timed buffers
3840 if (mTimedMemoryDealer == NULL) {
3841 const int kTimedBufferHeapSize = 512 << 10;
3842
3843 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3844 "AudioFlingerTimed");
3845 if (mTimedMemoryDealer == NULL)
3846 return NO_MEMORY;
3847 }
3848
3849 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3850 if (newBuffer == NULL) {
3851 newBuffer = mTimedMemoryDealer->allocate(size);
3852 if (newBuffer == NULL)
3853 return NO_MEMORY;
3854 }
3855
3856 *buffer = newBuffer;
3857 return NO_ERROR;
3858}
3859
3860// caller must hold mTimedBufferQueueLock
3861void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
3862 int64_t mediaTimeNow;
3863 {
3864 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3865 if (!mMediaTimeTransformValid)
3866 return;
3867
3868 int64_t targetTimeNow;
3869 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
3870 ? mCCHelper.getCommonTime(&targetTimeNow)
3871 : mCCHelper.getLocalTime(&targetTimeNow);
3872
3873 if (OK != res)
3874 return;
3875
3876 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
3877 &mediaTimeNow)) {
3878 return;
3879 }
3880 }
3881
3882 size_t trimIndex;
3883 for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
3884 if (mTimedBufferQueue[trimIndex].pts() > mediaTimeNow)
3885 break;
3886 }
3887
3888 if (trimIndex) {
3889 mTimedBufferQueue.removeItemsAt(0, trimIndex);
3890 }
3891}
3892
3893status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
3894 const sp<IMemory>& buffer, int64_t pts) {
3895
3896 {
3897 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3898 if (!mMediaTimeTransformValid)
3899 return INVALID_OPERATION;
3900 }
3901
3902 Mutex::Autolock _l(mTimedBufferQueueLock);
3903
3904 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
3905
3906 return NO_ERROR;
3907}
3908
3909status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
3910 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
3911
3912 ALOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
3913 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
3914 target);
3915
3916 if (!(target == TimedAudioTrack::LOCAL_TIME ||
3917 target == TimedAudioTrack::COMMON_TIME)) {
3918 return BAD_VALUE;
3919 }
3920
3921 Mutex::Autolock lock(mMediaTimeTransformLock);
3922 mMediaTimeTransform = xform;
3923 mMediaTimeTransformTarget = target;
3924 mMediaTimeTransformValid = true;
3925
3926 return NO_ERROR;
3927}
3928
3929#define min(a, b) ((a) < (b) ? (a) : (b))
3930
3931// implementation of getNextBuffer for tracks whose buffers have timestamps
3932status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
3933 AudioBufferProvider::Buffer* buffer, int64_t pts)
3934{
3935 if (pts == AudioBufferProvider::kInvalidPTS) {
3936 buffer->raw = 0;
3937 buffer->frameCount = 0;
3938 return INVALID_OPERATION;
3939 }
3940
John Grossman4ff14ba2012-02-08 16:37:41 -08003941 Mutex::Autolock _l(mTimedBufferQueueLock);
3942
3943 while (true) {
3944
3945 // if we have no timed buffers, then fail
3946 if (mTimedBufferQueue.isEmpty()) {
3947 buffer->raw = 0;
3948 buffer->frameCount = 0;
3949 return NOT_ENOUGH_DATA;
3950 }
3951
3952 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
3953
3954 // calculate the PTS of the head of the timed buffer queue expressed in
3955 // local time
3956 int64_t headLocalPTS;
3957 {
3958 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3959
3960 assert(mMediaTimeTransformValid);
3961
3962 if (mMediaTimeTransform.a_to_b_denom == 0) {
3963 // the transform represents a pause, so yield silence
3964 timedYieldSilence(buffer->frameCount, buffer);
3965 return NO_ERROR;
3966 }
3967
3968 int64_t transformedPTS;
3969 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
3970 &transformedPTS)) {
3971 // the transform failed. this shouldn't happen, but if it does
3972 // then just drop this buffer
3973 ALOGW("timedGetNextBuffer transform failed");
3974 buffer->raw = 0;
3975 buffer->frameCount = 0;
3976 mTimedBufferQueue.removeAt(0);
3977 return NO_ERROR;
3978 }
3979
3980 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
3981 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
3982 &headLocalPTS)) {
3983 buffer->raw = 0;
3984 buffer->frameCount = 0;
3985 return INVALID_OPERATION;
3986 }
3987 } else {
3988 headLocalPTS = transformedPTS;
3989 }
3990 }
3991
3992 // adjust the head buffer's PTS to reflect the portion of the head buffer
3993 // that has already been consumed
3994 int64_t effectivePTS = headLocalPTS +
3995 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
3996
3997 // Calculate the delta in samples between the head of the input buffer
3998 // queue and the start of the next output buffer that will be written.
3999 // If the transformation fails because of over or underflow, it means
4000 // that the sample's position in the output stream is so far out of
4001 // whack that it should just be dropped.
4002 int64_t sampleDelta;
4003 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4004 ALOGV("*** head buffer is too far from PTS: dropped buffer");
4005 mTimedBufferQueue.removeAt(0);
4006 continue;
4007 }
4008 if (!mLocalTimeToSampleTransform.doForwardTransform(
4009 (effectivePTS - pts) << 32, &sampleDelta)) {
4010 ALOGV("*** too late during sample rate transform: dropped buffer");
4011 mTimedBufferQueue.removeAt(0);
4012 continue;
4013 }
4014
4015 ALOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
4016 __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
4017 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
4018 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
4019
4020 // if the delta between the ideal placement for the next input sample and
4021 // the current output position is within this threshold, then we will
4022 // concatenate the next input samples to the previous output
4023 const int64_t kSampleContinuityThreshold =
4024 (static_cast<int64_t>(sampleRate()) << 32) / 10;
4025
4026 // if this is the first buffer of audio that we're emitting from this track
4027 // then it should be almost exactly on time.
4028 const int64_t kSampleStartupThreshold = 1LL << 32;
4029
4030 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
4031 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
4032 // the next input is close enough to being on time, so concatenate it
4033 // with the last output
4034 timedYieldSamples(buffer);
4035
4036 ALOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4037 return NO_ERROR;
4038 } else if (sampleDelta > 0) {
4039 // the gap between the current output position and the proper start of
4040 // the next input sample is too big, so fill it with silence
4041 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4042
4043 timedYieldSilence(framesUntilNextInput, buffer);
4044 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4045 return NO_ERROR;
4046 } else {
4047 // the next input sample is late
4048 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4049 size_t onTimeSamplePosition =
4050 head.position() + lateFrames * mCblk->frameSize;
4051
4052 if (onTimeSamplePosition > head.buffer()->size()) {
4053 // all the remaining samples in the head are too late, so
4054 // drop it and move on
4055 ALOGV("*** too late: dropped buffer");
4056 mTimedBufferQueue.removeAt(0);
4057 continue;
4058 } else {
4059 // skip over the late samples
4060 head.setPosition(onTimeSamplePosition);
4061
4062 // yield the available samples
4063 timedYieldSamples(buffer);
4064
4065 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4066 return NO_ERROR;
4067 }
4068 }
4069 }
4070}
4071
4072// Yield samples from the timed buffer queue head up to the given output
4073// buffer's capacity.
4074//
4075// Caller must hold mTimedBufferQueueLock
4076void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples(
4077 AudioBufferProvider::Buffer* buffer) {
4078
4079 const TimedBuffer& head = mTimedBufferQueue[0];
4080
4081 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4082 head.position());
4083
4084 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4085 mCblk->frameSize);
4086 size_t framesRequested = buffer->frameCount;
4087 buffer->frameCount = min(framesLeftInHead, framesRequested);
4088
4089 mTimedAudioOutputOnTime = true;
4090}
4091
4092// Yield samples of silence up to the given output buffer's capacity
4093//
4094// Caller must hold mTimedBufferQueueLock
4095void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence(
4096 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4097
4098 // lazily allocate a buffer filled with silence
4099 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4100 delete [] mTimedSilenceBuffer;
4101 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4102 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4103 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4104 }
4105
4106 buffer->raw = mTimedSilenceBuffer;
4107 size_t framesRequested = buffer->frameCount;
4108 buffer->frameCount = min(numFrames, framesRequested);
4109
4110 mTimedAudioOutputOnTime = false;
4111}
4112
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004113// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004114void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4115 AudioBufferProvider::Buffer* buffer) {
4116
4117 Mutex::Autolock _l(mTimedBufferQueueLock);
4118
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004119 // If the buffer which was just released is part of the buffer at the head
4120 // of the queue, be sure to update the amt of the buffer which has been
4121 // consumed. If the buffer being returned is not part of the head of the
4122 // queue, its either because the buffer is part of the silence buffer, or
4123 // because the head of the timed queue was trimmed after the mixer called
4124 // getNextBuffer but before the mixer called releaseBuffer.
4125 if ((buffer->raw != mTimedSilenceBuffer) && mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004126 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004127
4128 void* start = head.buffer()->pointer();
Glenn Kastenf063b492012-02-17 16:24:10 -08004129 void* end = (char *) head.buffer()->pointer() + head.buffer()->size();
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004130
4131 if ((buffer->raw >= start) && (buffer->raw <= end)) {
4132 head.setPosition(head.position() +
4133 (buffer->frameCount * mCblk->frameSize));
4134 if (static_cast<size_t>(head.position()) >= head.buffer()->size()) {
4135 mTimedBufferQueue.removeAt(0);
4136 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004137 }
4138 }
4139
4140 buffer->raw = 0;
4141 buffer->frameCount = 0;
4142}
4143
4144uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4145 Mutex::Autolock _l(mTimedBufferQueueLock);
4146
4147 uint32_t frames = 0;
4148 for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4149 const TimedBuffer& tb = mTimedBufferQueue[i];
4150 frames += (tb.buffer()->size() - tb.position()) / mCblk->frameSize;
4151 }
4152
4153 return frames;
4154}
4155
4156AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4157 : mPTS(0), mPosition(0) {}
4158
4159AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4160 const sp<IMemory>& buffer, int64_t pts)
4161 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4162
Mathias Agopian65ab4712010-07-14 17:59:35 -07004163// ----------------------------------------------------------------------------
4164
4165// RecordTrack constructor must be called with AudioFlinger::mLock held
4166AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004167 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004168 const sp<Client>& client,
4169 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004170 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004171 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004172 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004173 int sessionId)
4174 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004175 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004176 mOverflow(false)
4177{
4178 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01004179 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07004180 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004181 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07004182 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004183 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004184 } else {
4185 mCblk->frameSize = sizeof(int8_t);
4186 }
4187 }
4188}
4189
4190AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4191{
4192 sp<ThreadBase> thread = mThread.promote();
4193 if (thread != 0) {
4194 AudioSystem::releaseInput(thread->id());
4195 }
4196}
4197
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004198// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004199status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004200{
4201 audio_track_cblk_t* cblk = this->cblk();
4202 uint32_t framesAvail;
4203 uint32_t framesReq = buffer->frameCount;
4204
4205 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004206 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004207 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004208 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004209 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004210 }
4211
4212 framesAvail = cblk->framesAvailable_l();
4213
Glenn Kastenf6b16782011-12-15 09:51:17 -08004214 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004215 uint32_t s = cblk->server;
4216 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4217
4218 if (framesReq > framesAvail) {
4219 framesReq = framesAvail;
4220 }
4221 if (s + framesReq > bufferEnd) {
4222 framesReq = bufferEnd - s;
4223 }
4224
4225 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004226 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004227
4228 buffer->frameCount = framesReq;
4229 return NO_ERROR;
4230 }
4231
4232getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004233 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004234 buffer->frameCount = 0;
4235 return NOT_ENOUGH_DATA;
4236}
4237
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004238status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004239{
4240 sp<ThreadBase> thread = mThread.promote();
4241 if (thread != 0) {
4242 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004243 return recordThread->start(this, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004244 } else {
4245 return BAD_VALUE;
4246 }
4247}
4248
4249void AudioFlinger::RecordThread::RecordTrack::stop()
4250{
4251 sp<ThreadBase> thread = mThread.promote();
4252 if (thread != 0) {
4253 RecordThread *recordThread = (RecordThread *)thread.get();
4254 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004255 TrackBase::reset();
4256 // Force overerrun condition to avoid false overrun callback until first data is
4257 // read from buffer
4258 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004259 }
4260}
4261
4262void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4263{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004264 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004265 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004266 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004267 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004268 mSessionId,
4269 mFrameCount,
4270 mState,
4271 mCblk->sampleRate,
4272 mCblk->server,
4273 mCblk->user);
4274}
4275
4276
4277// ----------------------------------------------------------------------------
4278
4279AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004280 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004281 DuplicatingThread *sourceThread,
4282 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004283 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004284 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004285 int frameCount)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004286 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004287 mActive(false), mSourceThread(sourceThread)
4288{
4289
Mathias Agopian65ab4712010-07-14 17:59:35 -07004290 if (mCblk != NULL) {
4291 mCblk->flags |= CBLK_DIRECTION_OUT;
4292 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004293 mOutBuffer.frameCount = 0;
4294 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01004295 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004296 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4297 mCblk, mBuffer, mCblk->buffers,
4298 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004299 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004300 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004301 }
4302}
4303
4304AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4305{
4306 clearBufferQueue();
4307}
4308
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004309status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004310{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004311 status_t status = Track::start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004312 if (status != NO_ERROR) {
4313 return status;
4314 }
4315
4316 mActive = true;
4317 mRetryCount = 127;
4318 return status;
4319}
4320
4321void AudioFlinger::PlaybackThread::OutputTrack::stop()
4322{
4323 Track::stop();
4324 clearBufferQueue();
4325 mOutBuffer.frameCount = 0;
4326 mActive = false;
4327}
4328
4329bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4330{
4331 Buffer *pInBuffer;
4332 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004333 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004334 bool outputBufferFull = false;
4335 inBuffer.frameCount = frames;
4336 inBuffer.i16 = data;
4337
4338 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4339
4340 if (!mActive && frames != 0) {
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004341 start(0);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004342 sp<ThreadBase> thread = mThread.promote();
4343 if (thread != 0) {
4344 MixerThread *mixerThread = (MixerThread *)thread.get();
4345 if (mCblk->frameCount > frames){
4346 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4347 uint32_t startFrames = (mCblk->frameCount - frames);
4348 pInBuffer = new Buffer;
4349 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4350 pInBuffer->frameCount = startFrames;
4351 pInBuffer->i16 = pInBuffer->mBuffer;
4352 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4353 mBufferQueue.add(pInBuffer);
4354 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004355 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004356 }
4357 }
4358 }
4359 }
4360
4361 while (waitTimeLeftMs) {
4362 // First write pending buffers, then new data
4363 if (mBufferQueue.size()) {
4364 pInBuffer = mBufferQueue.itemAt(0);
4365 } else {
4366 pInBuffer = &inBuffer;
4367 }
4368
4369 if (pInBuffer->frameCount == 0) {
4370 break;
4371 }
4372
4373 if (mOutBuffer.frameCount == 0) {
4374 mOutBuffer.frameCount = pInBuffer->frameCount;
4375 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08004376 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01004377 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004378 outputBufferFull = true;
4379 break;
4380 }
4381 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4382 if (waitTimeLeftMs >= waitTimeMs) {
4383 waitTimeLeftMs -= waitTimeMs;
4384 } else {
4385 waitTimeLeftMs = 0;
4386 }
4387 }
4388
4389 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4390 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4391 mCblk->stepUser(outFrames);
4392 pInBuffer->frameCount -= outFrames;
4393 pInBuffer->i16 += outFrames * channelCount;
4394 mOutBuffer.frameCount -= outFrames;
4395 mOutBuffer.i16 += outFrames * channelCount;
4396
4397 if (pInBuffer->frameCount == 0) {
4398 if (mBufferQueue.size()) {
4399 mBufferQueue.removeAt(0);
4400 delete [] pInBuffer->mBuffer;
4401 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01004402 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004403 } else {
4404 break;
4405 }
4406 }
4407 }
4408
4409 // If we could not write all frames, allocate a buffer and queue it for next time.
4410 if (inBuffer.frameCount) {
4411 sp<ThreadBase> thread = mThread.promote();
4412 if (thread != 0 && !thread->standby()) {
4413 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4414 pInBuffer = new Buffer;
4415 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4416 pInBuffer->frameCount = inBuffer.frameCount;
4417 pInBuffer->i16 = pInBuffer->mBuffer;
4418 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4419 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01004420 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004421 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004422 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004423 }
4424 }
4425 }
4426
4427 // Calling write() with a 0 length buffer, means that no more data will be written:
4428 // If no more buffers are pending, fill output track buffer to make sure it is started
4429 // by output mixer.
4430 if (frames == 0 && mBufferQueue.size() == 0) {
4431 if (mCblk->user < mCblk->frameCount) {
4432 frames = mCblk->frameCount - mCblk->user;
4433 pInBuffer = new Buffer;
4434 pInBuffer->mBuffer = new int16_t[frames * channelCount];
4435 pInBuffer->frameCount = frames;
4436 pInBuffer->i16 = pInBuffer->mBuffer;
4437 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4438 mBufferQueue.add(pInBuffer);
4439 } else if (mActive) {
4440 stop();
4441 }
4442 }
4443
4444 return outputBufferFull;
4445}
4446
4447status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4448{
4449 int active;
4450 status_t result;
4451 audio_track_cblk_t* cblk = mCblk;
4452 uint32_t framesReq = buffer->frameCount;
4453
Steve Block3856b092011-10-20 11:56:00 +01004454// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004455 buffer->frameCount = 0;
4456
4457 uint32_t framesAvail = cblk->framesAvailable();
4458
4459
4460 if (framesAvail == 0) {
4461 Mutex::Autolock _l(cblk->lock);
4462 goto start_loop_here;
4463 while (framesAvail == 0) {
4464 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004465 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004466 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004467 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004468 }
4469 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4470 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004471 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004472 }
4473 // read the server count again
4474 start_loop_here:
4475 framesAvail = cblk->framesAvailable_l();
4476 }
4477 }
4478
4479// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004480// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004481// }
4482
4483 if (framesReq > framesAvail) {
4484 framesReq = framesAvail;
4485 }
4486
4487 uint32_t u = cblk->user;
4488 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4489
4490 if (u + framesReq > bufferEnd) {
4491 framesReq = bufferEnd - u;
4492 }
4493
4494 buffer->frameCount = framesReq;
4495 buffer->raw = (void *)cblk->buffer(u);
4496 return NO_ERROR;
4497}
4498
4499
4500void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4501{
4502 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004503
4504 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004505 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004506 delete [] pBuffer->mBuffer;
4507 delete pBuffer;
4508 }
4509 mBufferQueue.clear();
4510}
4511
4512// ----------------------------------------------------------------------------
4513
4514AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4515 : RefBase(),
4516 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08004517 // 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 -07004518 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08004519 mPid(pid),
4520 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004521{
4522 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4523}
4524
4525// Client destructor must be called with AudioFlinger::mLock held
4526AudioFlinger::Client::~Client()
4527{
4528 mAudioFlinger->removeClient_l(mPid);
4529}
4530
Glenn Kasten435dbe62012-01-30 10:15:48 -08004531sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004532{
4533 return mMemoryDealer;
4534}
4535
John Grossman4ff14ba2012-02-08 16:37:41 -08004536// Reserve one of the limited slots for a timed audio track associated
4537// with this client
4538bool AudioFlinger::Client::reserveTimedTrack()
4539{
4540 const int kMaxTimedTracksPerClient = 4;
4541
4542 Mutex::Autolock _l(mTimedTrackLock);
4543
4544 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4545 ALOGW("can not create timed track - pid %d has exceeded the limit",
4546 mPid);
4547 return false;
4548 }
4549
4550 mTimedTrackCount++;
4551 return true;
4552}
4553
4554// Release a slot for a timed audio track
4555void AudioFlinger::Client::releaseTimedTrack()
4556{
4557 Mutex::Autolock _l(mTimedTrackLock);
4558 mTimedTrackCount--;
4559}
4560
Mathias Agopian65ab4712010-07-14 17:59:35 -07004561// ----------------------------------------------------------------------------
4562
4563AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4564 const sp<IAudioFlingerClient>& client,
4565 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004566 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004567{
4568}
4569
4570AudioFlinger::NotificationClient::~NotificationClient()
4571{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004572}
4573
4574void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4575{
4576 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08004577 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004578}
4579
4580// ----------------------------------------------------------------------------
4581
4582AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4583 : BnAudioTrack(),
4584 mTrack(track)
4585{
4586}
4587
4588AudioFlinger::TrackHandle::~TrackHandle() {
4589 // just stop the track on deletion, associated resources
4590 // will be freed from the main thread once all pending buffers have
4591 // been played. Unless it's not in the active track list, in which
4592 // case we free everything now...
4593 mTrack->destroy();
4594}
4595
Glenn Kasten90716c52012-01-26 13:40:12 -08004596sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4597 return mTrack->getCblk();
4598}
4599
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004600status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4601 return mTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004602}
4603
4604void AudioFlinger::TrackHandle::stop() {
4605 mTrack->stop();
4606}
4607
4608void AudioFlinger::TrackHandle::flush() {
4609 mTrack->flush();
4610}
4611
4612void AudioFlinger::TrackHandle::mute(bool e) {
4613 mTrack->mute(e);
4614}
4615
4616void AudioFlinger::TrackHandle::pause() {
4617 mTrack->pause();
4618}
4619
Mathias Agopian65ab4712010-07-14 17:59:35 -07004620status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4621{
4622 return mTrack->attachAuxEffect(EffectId);
4623}
4624
John Grossman4ff14ba2012-02-08 16:37:41 -08004625status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4626 sp<IMemory>* buffer) {
4627 if (!mTrack->isTimedTrack())
4628 return INVALID_OPERATION;
4629
4630 PlaybackThread::TimedTrack* tt =
4631 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4632 return tt->allocateTimedBuffer(size, buffer);
4633}
4634
4635status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4636 int64_t pts) {
4637 if (!mTrack->isTimedTrack())
4638 return INVALID_OPERATION;
4639
4640 PlaybackThread::TimedTrack* tt =
4641 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4642 return tt->queueTimedBuffer(buffer, pts);
4643}
4644
4645status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4646 const LinearTransform& xform, int target) {
4647
4648 if (!mTrack->isTimedTrack())
4649 return INVALID_OPERATION;
4650
4651 PlaybackThread::TimedTrack* tt =
4652 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4653 return tt->setMediaTimeTransform(
4654 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4655}
4656
Mathias Agopian65ab4712010-07-14 17:59:35 -07004657status_t AudioFlinger::TrackHandle::onTransact(
4658 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4659{
4660 return BnAudioTrack::onTransact(code, data, reply, flags);
4661}
4662
4663// ----------------------------------------------------------------------------
4664
4665sp<IAudioRecord> AudioFlinger::openRecord(
4666 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004667 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004668 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004669 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004670 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004671 int frameCount,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004672 // FIXME dead, remove from IAudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -07004673 uint32_t flags,
4674 int *sessionId,
4675 status_t *status)
4676{
4677 sp<RecordThread::RecordTrack> recordTrack;
4678 sp<RecordHandle> recordHandle;
4679 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004680 status_t lStatus;
4681 RecordThread *thread;
4682 size_t inFrameCount;
4683 int lSessionId;
4684
4685 // check calling permissions
4686 if (!recordingAllowed()) {
4687 lStatus = PERMISSION_DENIED;
4688 goto Exit;
4689 }
4690
4691 // add client to list
4692 { // scope for mLock
4693 Mutex::Autolock _l(mLock);
4694 thread = checkRecordThread_l(input);
4695 if (thread == NULL) {
4696 lStatus = BAD_VALUE;
4697 goto Exit;
4698 }
4699
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004700 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004701
4702 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004703 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004704 lSessionId = *sessionId;
4705 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004706 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004707 if (sessionId != NULL) {
4708 *sessionId = lSessionId;
4709 }
4710 }
4711 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004712 recordTrack = thread->createRecordTrack_l(client,
4713 sampleRate,
4714 format,
4715 channelMask,
4716 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004717 lSessionId,
4718 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004719 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004720 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004721 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4722 // destructor is called by the TrackBase destructor with mLock held
4723 client.clear();
4724 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004725 goto Exit;
4726 }
4727
4728 // return to handle to client
4729 recordHandle = new RecordHandle(recordTrack);
4730 lStatus = NO_ERROR;
4731
4732Exit:
4733 if (status) {
4734 *status = lStatus;
4735 }
4736 return recordHandle;
4737}
4738
4739// ----------------------------------------------------------------------------
4740
4741AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4742 : BnAudioRecord(),
4743 mRecordTrack(recordTrack)
4744{
4745}
4746
4747AudioFlinger::RecordHandle::~RecordHandle() {
4748 stop();
4749}
4750
Glenn Kasten90716c52012-01-26 13:40:12 -08004751sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4752 return mRecordTrack->getCblk();
4753}
4754
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004755status_t AudioFlinger::RecordHandle::start(pid_t tid) {
Steve Block3856b092011-10-20 11:56:00 +01004756 ALOGV("RecordHandle::start()");
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004757 return mRecordTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004758}
4759
4760void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004761 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004762 mRecordTrack->stop();
4763}
4764
Mathias Agopian65ab4712010-07-14 17:59:35 -07004765status_t AudioFlinger::RecordHandle::onTransact(
4766 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4767{
4768 return BnAudioRecord::onTransact(code, data, reply, flags);
4769}
4770
4771// ----------------------------------------------------------------------------
4772
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004773AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4774 AudioStreamIn *input,
4775 uint32_t sampleRate,
4776 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004777 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004778 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004779 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004780 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4781 // mRsmpInIndex and mInputBytes set by readInputParameters()
4782 mReqChannelCount(popcount(channels)),
4783 mReqSampleRate(sampleRate)
4784 // mBytesRead is only meaningful while active, and so is cleared in start()
4785 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004786{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004787 snprintf(mName, kNameLength, "AudioIn_%d", id);
4788
Mathias Agopian65ab4712010-07-14 17:59:35 -07004789 readInputParameters();
4790}
4791
4792
4793AudioFlinger::RecordThread::~RecordThread()
4794{
4795 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004796 delete mResampler;
4797 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004798}
4799
4800void AudioFlinger::RecordThread::onFirstRef()
4801{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004802 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004803}
4804
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004805status_t AudioFlinger::RecordThread::readyToRun()
4806{
4807 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004808 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004809 return status;
4810}
4811
Mathias Agopian65ab4712010-07-14 17:59:35 -07004812bool AudioFlinger::RecordThread::threadLoop()
4813{
4814 AudioBufferProvider::Buffer buffer;
4815 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004816 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004817
Eric Laurent44d98482010-09-30 16:12:31 -07004818 nsecs_t lastWarning = 0;
4819
Eric Laurentfeb0db62011-07-22 09:04:31 -07004820 acquireWakeLock();
4821
Mathias Agopian65ab4712010-07-14 17:59:35 -07004822 // start recording
4823 while (!exitPending()) {
4824
4825 processConfigEvents();
4826
4827 { // scope for mLock
4828 Mutex::Autolock _l(mLock);
4829 checkForNewParameters_l();
4830 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4831 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004832 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004833 mStandby = true;
4834 }
4835
4836 if (exitPending()) break;
4837
Eric Laurentfeb0db62011-07-22 09:04:31 -07004838 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004839 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004840 // go to sleep
4841 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004842 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004843 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004844 continue;
4845 }
4846 if (mActiveTrack != 0) {
4847 if (mActiveTrack->mState == TrackBase::PAUSING) {
4848 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004849 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004850 mStandby = true;
4851 }
4852 mActiveTrack.clear();
4853 mStartStopCond.broadcast();
4854 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4855 if (mReqChannelCount != mActiveTrack->channelCount()) {
4856 mActiveTrack.clear();
4857 mStartStopCond.broadcast();
4858 } else if (mBytesRead != 0) {
4859 // record start succeeds only if first read from audio input
4860 // succeeds
4861 if (mBytesRead > 0) {
4862 mActiveTrack->mState = TrackBase::ACTIVE;
4863 } else {
4864 mActiveTrack.clear();
4865 }
4866 mStartStopCond.broadcast();
4867 }
4868 mStandby = false;
4869 }
4870 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004871 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004872 }
4873
4874 if (mActiveTrack != 0) {
4875 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4876 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004877 unlockEffectChains(effectChains);
4878 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004879 continue;
4880 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004881 for (size_t i = 0; i < effectChains.size(); i ++) {
4882 effectChains[i]->process_l();
4883 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004884
Mathias Agopian65ab4712010-07-14 17:59:35 -07004885 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004886 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004887 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004888 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004889 // no resampling
4890 while (framesOut) {
4891 size_t framesIn = mFrameCount - mRsmpInIndex;
4892 if (framesIn) {
4893 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4894 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4895 if (framesIn > framesOut)
4896 framesIn = framesOut;
4897 mRsmpInIndex += framesIn;
4898 framesOut -= framesIn;
4899 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004900 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004901 memcpy(dst, src, framesIn * mFrameSize);
4902 } else {
4903 int16_t *src16 = (int16_t *)src;
4904 int16_t *dst16 = (int16_t *)dst;
4905 if (mChannelCount == 1) {
4906 while (framesIn--) {
4907 *dst16++ = *src16;
4908 *dst16++ = *src16++;
4909 }
4910 } else {
4911 while (framesIn--) {
4912 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4913 src16 += 2;
4914 }
4915 }
4916 }
4917 }
4918 if (framesOut && mFrameCount == mRsmpInIndex) {
4919 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004920 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004921 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004922 framesOut = 0;
4923 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004924 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004925 mRsmpInIndex = 0;
4926 }
4927 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004928 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004929 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4930 // Force input into standby so that it tries to
4931 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004932 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004933 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004934 }
4935 mRsmpInIndex = mFrameCount;
4936 framesOut = 0;
4937 buffer.frameCount = 0;
4938 }
4939 }
4940 }
4941 } else {
4942 // resampling
4943
4944 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4945 // alter output frame count as if we were expecting stereo samples
4946 if (mChannelCount == 1 && mReqChannelCount == 1) {
4947 framesOut >>= 1;
4948 }
4949 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4950 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4951 // are 32 bit aligned which should be always true.
4952 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004953 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004954 // the resampler always outputs stereo samples: do post stereo to mono conversion
4955 int16_t *src = (int16_t *)mRsmpOutBuffer;
4956 int16_t *dst = buffer.i16;
4957 while (framesOut--) {
4958 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4959 src += 2;
4960 }
4961 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004962 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004963 }
4964
4965 }
4966 mActiveTrack->releaseBuffer(&buffer);
4967 mActiveTrack->overflow();
4968 }
4969 // client isn't retrieving buffers fast enough
4970 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004971 if (!mActiveTrack->setOverflow()) {
4972 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004973 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004974 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004975 lastWarning = now;
4976 }
4977 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004978 // Release the processor for a while before asking for a new buffer.
4979 // This will give the application more chance to read from the buffer and
4980 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004981 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004982 }
4983 }
Eric Laurentec437d82011-07-26 20:54:46 -07004984 // enable changes in effect chain
4985 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004986 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004987 }
4988
4989 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004990 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004991 }
4992 mActiveTrack.clear();
4993
4994 mStartStopCond.broadcast();
4995
Eric Laurentfeb0db62011-07-22 09:04:31 -07004996 releaseWakeLock();
4997
Steve Block3856b092011-10-20 11:56:00 +01004998 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004999 return false;
5000}
5001
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005002
5003sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5004 const sp<AudioFlinger::Client>& client,
5005 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005006 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005007 int channelMask,
5008 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005009 int sessionId,
5010 status_t *status)
5011{
5012 sp<RecordTrack> track;
5013 status_t lStatus;
5014
5015 lStatus = initCheck();
5016 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005017 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005018 goto Exit;
5019 }
5020
5021 { // scope for mLock
5022 Mutex::Autolock _l(mLock);
5023
5024 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005025 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005026
Glenn Kasten7378ca52012-01-20 13:44:40 -08005027 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005028 lStatus = NO_MEMORY;
5029 goto Exit;
5030 }
5031
5032 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005033 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5034 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005035 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005036 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5037 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005038 }
5039 lStatus = NO_ERROR;
5040
5041Exit:
5042 if (status) {
5043 *status = lStatus;
5044 }
5045 return track;
5046}
5047
Glenn Kasten6dbc1352012-02-02 10:56:47 -08005048status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005049{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08005050 ALOGV("RecordThread::start tid=%d", tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005051 sp <ThreadBase> strongMe = this;
5052 status_t status = NO_ERROR;
5053 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005054 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005055 if (mActiveTrack != 0) {
5056 if (recordTrack != mActiveTrack.get()) {
5057 status = -EBUSY;
5058 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5059 mActiveTrack->mState = TrackBase::ACTIVE;
5060 }
5061 return status;
5062 }
5063
5064 recordTrack->mState = TrackBase::IDLE;
5065 mActiveTrack = recordTrack;
5066 mLock.unlock();
5067 status_t status = AudioSystem::startInput(mId);
5068 mLock.lock();
5069 if (status != NO_ERROR) {
5070 mActiveTrack.clear();
5071 return status;
5072 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005073 mRsmpInIndex = mFrameCount;
5074 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005075 if (mResampler != NULL) {
5076 mResampler->reset();
5077 }
5078 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005079 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005080 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005081 mWaitWorkCV.signal();
5082 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005083 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005084 mActiveTrack.clear();
5085 status = INVALID_OPERATION;
5086 goto startError;
5087 }
5088 mStartStopCond.wait(mLock);
5089 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005090 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005091 status = BAD_VALUE;
5092 goto startError;
5093 }
Steve Block3856b092011-10-20 11:56:00 +01005094 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005095 return status;
5096 }
5097startError:
5098 AudioSystem::stopInput(mId);
5099 return status;
5100}
5101
5102void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005103 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005104 sp <ThreadBase> strongMe = this;
5105 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005106 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005107 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5108 mActiveTrack->mState = TrackBase::PAUSING;
5109 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005110 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005111 return;
5112 }
5113 mStartStopCond.wait(mLock);
5114 // if we have been restarted, recordTrack == mActiveTrack.get() here
5115 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5116 mLock.unlock();
5117 AudioSystem::stopInput(mId);
5118 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005119 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005120 }
5121 }
5122 }
5123}
5124
5125status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5126{
5127 const size_t SIZE = 256;
5128 char buffer[SIZE];
5129 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005130
5131 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5132 result.append(buffer);
5133
5134 if (mActiveTrack != 0) {
5135 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005136 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005137 mActiveTrack->dump(buffer, SIZE);
5138 result.append(buffer);
5139
5140 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5141 result.append(buffer);
5142 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5143 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005144 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005145 result.append(buffer);
5146 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5147 result.append(buffer);
5148 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5149 result.append(buffer);
5150
5151
5152 } else {
5153 result.append("No record client\n");
5154 }
5155 write(fd, result.string(), result.size());
5156
5157 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005158 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005159
5160 return NO_ERROR;
5161}
5162
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005163// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005164status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005165{
5166 size_t framesReq = buffer->frameCount;
5167 size_t framesReady = mFrameCount - mRsmpInIndex;
5168 int channelCount;
5169
5170 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005171 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005172 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005173 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005174 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5175 // Force input into standby so that it tries to
5176 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005177 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005178 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005179 }
Glenn Kastene0feee32011-12-13 11:53:26 -08005180 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005181 buffer->frameCount = 0;
5182 return NOT_ENOUGH_DATA;
5183 }
5184 mRsmpInIndex = 0;
5185 framesReady = mFrameCount;
5186 }
5187
5188 if (framesReq > framesReady) {
5189 framesReq = framesReady;
5190 }
5191
5192 if (mChannelCount == 1 && mReqChannelCount == 2) {
5193 channelCount = 1;
5194 } else {
5195 channelCount = 2;
5196 }
5197 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5198 buffer->frameCount = framesReq;
5199 return NO_ERROR;
5200}
5201
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005202// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07005203void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5204{
5205 mRsmpInIndex += buffer->frameCount;
5206 buffer->frameCount = 0;
5207}
5208
5209bool AudioFlinger::RecordThread::checkForNewParameters_l()
5210{
5211 bool reconfig = false;
5212
5213 while (!mNewParameters.isEmpty()) {
5214 status_t status = NO_ERROR;
5215 String8 keyValuePair = mNewParameters[0];
5216 AudioParameter param = AudioParameter(keyValuePair);
5217 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08005218 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005219 int reqSamplingRate = mReqSampleRate;
5220 int reqChannelCount = mReqChannelCount;
5221
5222 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5223 reqSamplingRate = value;
5224 reconfig = true;
5225 }
5226 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08005227 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005228 reconfig = true;
5229 }
5230 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005231 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005232 reconfig = true;
5233 }
5234 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5235 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08005236 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005237 // if frame count is changed after track creation
5238 if (mActiveTrack != 0) {
5239 status = INVALID_OPERATION;
5240 } else {
5241 reconfig = true;
5242 }
5243 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005244 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5245 // forward device change to effects that have requested to be
5246 // aware of attached audio device.
5247 for (size_t i = 0; i < mEffectChains.size(); i++) {
5248 mEffectChains[i]->setDevice_l(value);
5249 }
5250 // store input device and output device but do not forward output device to audio HAL.
5251 // Note that status is ignored by the caller for output device
5252 // (see AudioFlinger::setParameters()
5253 if (value & AUDIO_DEVICE_OUT_ALL) {
5254 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5255 status = BAD_VALUE;
5256 } else {
5257 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07005258 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5259 if (mTrack != NULL) {
5260 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005261 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005262 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5263 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5264 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005265 }
5266 mDevice |= (uint32_t)value;
5267 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005268 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005269 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005270 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005271 mInput->stream->common.standby(&mInput->stream->common);
5272 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005273 }
5274 if (reconfig) {
5275 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005276 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005277 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005278 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
5279 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005280 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005281 status = NO_ERROR;
5282 }
5283 if (status == NO_ERROR) {
5284 readInputParameters();
5285 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5286 }
5287 }
5288 }
5289
5290 mNewParameters.removeAt(0);
5291
5292 mParamStatus = status;
5293 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07005294 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5295 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08005296 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005297 }
5298 return reconfig;
5299}
5300
5301String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5302{
Dima Zavinfce7a472011-04-19 22:30:36 -07005303 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005304 String8 out_s8 = String8();
5305
5306 Mutex::Autolock _l(mLock);
5307 if (initCheck() != NO_ERROR) {
5308 return out_s8;
5309 }
Dima Zavinfce7a472011-04-19 22:30:36 -07005310
Dima Zavin799a70e2011-04-18 16:57:27 -07005311 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07005312 out_s8 = String8(s);
5313 free(s);
5314 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005315}
5316
5317void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5318 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08005319 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005320
5321 switch (event) {
5322 case AudioSystem::INPUT_OPENED:
5323 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005324 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005325 desc.samplingRate = mSampleRate;
5326 desc.format = mFormat;
5327 desc.frameCount = mFrameCount;
5328 desc.latency = 0;
5329 param2 = &desc;
5330 break;
5331
5332 case AudioSystem::INPUT_CLOSED:
5333 default:
5334 break;
5335 }
5336 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5337}
5338
5339void AudioFlinger::RecordThread::readInputParameters()
5340{
Glenn Kastene9dd0172012-01-27 18:08:45 -08005341 delete mRsmpInBuffer;
5342 // mRsmpInBuffer is always assigned a new[] below
5343 delete mRsmpOutBuffer;
5344 mRsmpOutBuffer = NULL;
5345 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08005346 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005347
Dima Zavin799a70e2011-04-18 16:57:27 -07005348 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005349 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5350 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07005351 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08005352 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07005353 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005354 mFrameCount = mInputBytes / mFrameSize;
5355 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5356
5357 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
5358 {
5359 int channelCount;
5360 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5361 // stereo to mono post process as the resampler always outputs stereo.
5362 if (mChannelCount == 1 && mReqChannelCount == 2) {
5363 channelCount = 1;
5364 } else {
5365 channelCount = 2;
5366 }
5367 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5368 mResampler->setSampleRate(mSampleRate);
5369 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5370 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5371
5372 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5373 if (mChannelCount == 1 && mReqChannelCount == 1) {
5374 mFrameCount >>= 1;
5375 }
5376
5377 }
5378 mRsmpInIndex = mFrameCount;
5379}
5380
5381unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5382{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005383 Mutex::Autolock _l(mLock);
5384 if (initCheck() != NO_ERROR) {
5385 return 0;
5386 }
5387
Dima Zavin799a70e2011-04-18 16:57:27 -07005388 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005389}
5390
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005391uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5392{
5393 Mutex::Autolock _l(mLock);
5394 uint32_t result = 0;
5395 if (getEffectChain_l(sessionId) != 0) {
5396 result = EFFECT_SESSION;
5397 }
5398
5399 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5400 result |= TRACK_SESSION;
5401 }
5402
5403 return result;
5404}
5405
Eric Laurent59bd0da2011-08-01 09:52:20 -07005406AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5407{
5408 Mutex::Autolock _l(mLock);
5409 return mTrack;
5410}
5411
Glenn Kastenaed850d2012-01-26 09:46:34 -08005412AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005413{
5414 Mutex::Autolock _l(mLock);
5415 return mInput;
5416}
5417
5418AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5419{
5420 Mutex::Autolock _l(mLock);
5421 AudioStreamIn *input = mInput;
5422 mInput = NULL;
5423 return input;
5424}
5425
5426// this method must always be called either with ThreadBase mLock held or inside the thread loop
5427audio_stream_t* AudioFlinger::RecordThread::stream()
5428{
5429 if (mInput == NULL) {
5430 return NULL;
5431 }
5432 return &mInput->stream->common;
5433}
5434
5435
Mathias Agopian65ab4712010-07-14 17:59:35 -07005436// ----------------------------------------------------------------------------
5437
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005438audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005439 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005440 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005441 uint32_t *pChannels,
5442 uint32_t *pLatencyMs,
5443 uint32_t flags)
5444{
5445 status_t status;
5446 PlaybackThread *thread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005447 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005448 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005449 uint32_t channels = pChannels ? *pChannels : 0;
5450 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07005451 audio_stream_out_t *outStream;
5452 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005453
Steve Block3856b092011-10-20 11:56:00 +01005454 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07005455 pDevices ? *pDevices : 0,
5456 samplingRate,
5457 format,
5458 channels,
5459 flags);
5460
5461 if (pDevices == NULL || *pDevices == 0) {
5462 return 0;
5463 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005464
Mathias Agopian65ab4712010-07-14 17:59:35 -07005465 Mutex::Autolock _l(mLock);
5466
Dima Zavin799a70e2011-04-18 16:57:27 -07005467 outHwDev = findSuitableHwDev_l(*pDevices);
5468 if (outHwDev == NULL)
5469 return 0;
5470
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005471 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Glenn Kasten58f30212012-01-12 12:27:51 -08005472 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005473 &channels, &samplingRate, &outStream);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005474 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01005475 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005476 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005477 samplingRate,
5478 format,
5479 channels,
5480 status);
5481
Dima Zavin799a70e2011-04-18 16:57:27 -07005482 if (outStream != NULL) {
5483 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005484 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07005485
Dima Zavinfce7a472011-04-19 22:30:36 -07005486 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5487 (format != AUDIO_FORMAT_PCM_16_BIT) ||
5488 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005489 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005490 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005491 } else {
5492 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005493 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005494 }
5495 mPlaybackThreads.add(id, thread);
5496
Glenn Kastena0d68332012-01-27 16:47:15 -08005497 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5498 if (pFormat != NULL) *pFormat = format;
5499 if (pChannels != NULL) *pChannels = channels;
5500 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005501
5502 // notify client processes of the new output creation
5503 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5504 return id;
5505 }
5506
5507 return 0;
5508}
5509
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005510audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
5511 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005512{
5513 Mutex::Autolock _l(mLock);
5514 MixerThread *thread1 = checkMixerThread_l(output1);
5515 MixerThread *thread2 = checkMixerThread_l(output2);
5516
5517 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005518 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005519 return 0;
5520 }
5521
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005522 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005523 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5524 thread->addOutputTrack(thread2);
5525 mPlaybackThreads.add(id, thread);
5526 // notify client processes of the new output creation
5527 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5528 return id;
5529}
5530
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005531status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005532{
5533 // keep strong reference on the playback thread so that
5534 // it is not destroyed while exit() is executed
5535 sp <PlaybackThread> thread;
5536 {
5537 Mutex::Autolock _l(mLock);
5538 thread = checkPlaybackThread_l(output);
5539 if (thread == NULL) {
5540 return BAD_VALUE;
5541 }
5542
Steve Block3856b092011-10-20 11:56:00 +01005543 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005544
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005545 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005546 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005547 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005548 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5549 dupThread->removeOutputTrack((MixerThread *)thread.get());
5550 }
5551 }
5552 }
Glenn Kastena1117922012-01-26 10:53:32 -08005553 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005554 mPlaybackThreads.removeItem(output);
5555 }
5556 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005557 // The thread entity (active unit of execution) is no longer running here,
5558 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005559
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005560 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005561 AudioStreamOut *out = thread->clearOutput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005562 assert(out != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005563 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005564 out->hwDev->close_output_stream(out->hwDev, out->stream);
5565 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005566 }
5567 return NO_ERROR;
5568}
5569
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005570status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005571{
5572 Mutex::Autolock _l(mLock);
5573 PlaybackThread *thread = checkPlaybackThread_l(output);
5574
5575 if (thread == NULL) {
5576 return BAD_VALUE;
5577 }
5578
Steve Block3856b092011-10-20 11:56:00 +01005579 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005580 thread->suspend();
5581
5582 return NO_ERROR;
5583}
5584
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005585status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005586{
5587 Mutex::Autolock _l(mLock);
5588 PlaybackThread *thread = checkPlaybackThread_l(output);
5589
5590 if (thread == NULL) {
5591 return BAD_VALUE;
5592 }
5593
Steve Block3856b092011-10-20 11:56:00 +01005594 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005595
5596 thread->restore();
5597
5598 return NO_ERROR;
5599}
5600
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005601audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005602 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005603 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005604 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005605 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005606{
5607 status_t status;
5608 RecordThread *thread = NULL;
5609 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005610 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005611 uint32_t channels = pChannels ? *pChannels : 0;
5612 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005613 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005614 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005615 audio_stream_in_t *inStream;
5616 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005617
5618 if (pDevices == NULL || *pDevices == 0) {
5619 return 0;
5620 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005621
Mathias Agopian65ab4712010-07-14 17:59:35 -07005622 Mutex::Autolock _l(mLock);
5623
Dima Zavin799a70e2011-04-18 16:57:27 -07005624 inHwDev = findSuitableHwDev_l(*pDevices);
5625 if (inHwDev == NULL)
5626 return 0;
5627
Glenn Kasten58f30212012-01-12 12:27:51 -08005628 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005629 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005630 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005631 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005632 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005633 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005634 samplingRate,
5635 format,
5636 channels,
5637 acoustics,
5638 status);
5639
5640 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5641 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5642 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005643 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005644 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005645 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005646 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005647 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005648 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005649 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005650 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005651 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005652 }
5653
Dima Zavin799a70e2011-04-18 16:57:27 -07005654 if (inStream != NULL) {
5655 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5656
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005657 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005658 // Start record thread
5659 // RecorThread require both input and output device indication to forward to audio
5660 // pre processing modules
5661 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5662 thread = new RecordThread(this,
5663 input,
5664 reqSamplingRate,
5665 reqChannels,
5666 id,
5667 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005668 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005669 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005670 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5671 if (pFormat != NULL) *pFormat = format;
5672 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005673
Dima Zavin799a70e2011-04-18 16:57:27 -07005674 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005675
5676 // notify client processes of the new input creation
5677 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5678 return id;
5679 }
5680
5681 return 0;
5682}
5683
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005684status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005685{
5686 // keep strong reference on the record thread so that
5687 // it is not destroyed while exit() is executed
5688 sp <RecordThread> thread;
5689 {
5690 Mutex::Autolock _l(mLock);
5691 thread = checkRecordThread_l(input);
5692 if (thread == NULL) {
5693 return BAD_VALUE;
5694 }
5695
Steve Block3856b092011-10-20 11:56:00 +01005696 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08005697 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005698 mRecordThreads.removeItem(input);
5699 }
5700 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005701 // The thread entity (active unit of execution) is no longer running here,
5702 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005703
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005704 AudioStreamIn *in = thread->clearInput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005705 assert(in != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005706 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005707 in->hwDev->close_input_stream(in->hwDev, in->stream);
5708 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005709
5710 return NO_ERROR;
5711}
5712
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005713status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005714{
5715 Mutex::Autolock _l(mLock);
5716 MixerThread *dstThread = checkMixerThread_l(output);
5717 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005718 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005719 return BAD_VALUE;
5720 }
5721
Steve Block3856b092011-10-20 11:56:00 +01005722 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005723 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5724
Eric Laurent9f6530f2011-08-30 10:18:54 -07005725 dstThread->setStreamValid(stream, true);
5726
Mathias Agopian65ab4712010-07-14 17:59:35 -07005727 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5728 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08005729 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005730 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005731 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005732 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005733 }
Eric Laurentde070132010-07-13 04:45:46 -07005734 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005735
5736 return NO_ERROR;
5737}
5738
5739
5740int AudioFlinger::newAudioSessionId()
5741{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005742 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005743}
5744
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005745void AudioFlinger::acquireAudioSessionId(int audioSession)
5746{
5747 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005748 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005749 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005750 size_t num = mAudioSessionRefs.size();
5751 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005752 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5753 if (ref->sessionid == audioSession && ref->pid == caller) {
5754 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005755 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005756 return;
5757 }
5758 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005759 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5760 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005761}
5762
5763void AudioFlinger::releaseAudioSessionId(int audioSession)
5764{
5765 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005766 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005767 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005768 size_t num = mAudioSessionRefs.size();
5769 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005770 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5771 if (ref->sessionid == audioSession && ref->pid == caller) {
5772 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005773 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005774 if (ref->cnt == 0) {
5775 mAudioSessionRefs.removeAt(i);
5776 delete ref;
5777 purgeStaleEffects_l();
5778 }
5779 return;
5780 }
5781 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005782 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005783}
5784
5785void AudioFlinger::purgeStaleEffects_l() {
5786
Steve Block3856b092011-10-20 11:56:00 +01005787 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005788
5789 Vector< sp<EffectChain> > chains;
5790
5791 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5792 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5793 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5794 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005795 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5796 chains.push(ec);
5797 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005798 }
5799 }
5800 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5801 sp<RecordThread> t = mRecordThreads.valueAt(i);
5802 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5803 sp<EffectChain> ec = t->mEffectChains[j];
5804 chains.push(ec);
5805 }
5806 }
5807
5808 for (size_t i = 0; i < chains.size(); i++) {
5809 sp<EffectChain> ec = chains[i];
5810 int sessionid = ec->sessionId();
5811 sp<ThreadBase> t = ec->mThread.promote();
5812 if (t == 0) {
5813 continue;
5814 }
5815 size_t numsessionrefs = mAudioSessionRefs.size();
5816 bool found = false;
5817 for (size_t k = 0; k < numsessionrefs; k++) {
5818 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5819 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005820 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005821 sessionid, ref->pid, ref->cnt);
5822 found = true;
5823 break;
5824 }
5825 }
5826 if (!found) {
5827 // remove all effects from the chain
5828 while (ec->mEffects.size()) {
5829 sp<EffectModule> effect = ec->mEffects[0];
5830 effect->unPin();
5831 Mutex::Autolock _l (t->mLock);
5832 t->removeEffect_l(effect);
5833 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5834 sp<EffectHandle> handle = effect->mHandles[j].promote();
5835 if (handle != 0) {
5836 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005837 if (handle->mHasControl && handle->mEnabled) {
5838 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5839 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005840 }
5841 }
5842 AudioSystem::unregisterEffect(effect->id());
5843 }
5844 }
5845 }
5846 return;
5847}
5848
Mathias Agopian65ab4712010-07-14 17:59:35 -07005849// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005850AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005851{
Glenn Kastena1117922012-01-26 10:53:32 -08005852 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005853}
5854
5855// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005856AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005857{
5858 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08005859 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005860}
5861
5862// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005863AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005864{
Glenn Kastena1117922012-01-26 10:53:32 -08005865 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005866}
5867
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005868uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005869{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005870 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005871}
5872
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005873AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5874{
5875 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5876 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005877 AudioStreamOut *output = thread->getOutput();
5878 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005879 return thread;
5880 }
5881 }
5882 return NULL;
5883}
5884
5885uint32_t AudioFlinger::primaryOutputDevice_l()
5886{
5887 PlaybackThread *thread = primaryPlaybackThread_l();
5888
5889 if (thread == NULL) {
5890 return 0;
5891 }
5892
5893 return thread->device();
5894}
5895
5896
Mathias Agopian65ab4712010-07-14 17:59:35 -07005897// ----------------------------------------------------------------------------
5898// Effect management
5899// ----------------------------------------------------------------------------
5900
5901
Glenn Kastenf587ba52012-01-26 16:25:10 -08005902status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005903{
5904 Mutex::Autolock _l(mLock);
5905 return EffectQueryNumberEffects(numEffects);
5906}
5907
Glenn Kastenf587ba52012-01-26 16:25:10 -08005908status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005909{
5910 Mutex::Autolock _l(mLock);
5911 return EffectQueryEffect(index, descriptor);
5912}
5913
Glenn Kasten5e92a782012-01-30 07:40:52 -08005914status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08005915 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005916{
5917 Mutex::Autolock _l(mLock);
5918 return EffectGetDescriptor(pUuid, descriptor);
5919}
5920
5921
Mathias Agopian65ab4712010-07-14 17:59:35 -07005922sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5923 effect_descriptor_t *pDesc,
5924 const sp<IEffectClient>& effectClient,
5925 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005926 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005927 int sessionId,
5928 status_t *status,
5929 int *id,
5930 int *enabled)
5931{
5932 status_t lStatus = NO_ERROR;
5933 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005934 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005935
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005936 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005937 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005938
5939 if (pDesc == NULL) {
5940 lStatus = BAD_VALUE;
5941 goto Exit;
5942 }
5943
Eric Laurent84e9a102010-09-23 16:10:16 -07005944 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005945 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005946 lStatus = PERMISSION_DENIED;
5947 goto Exit;
5948 }
5949
Dima Zavinfce7a472011-04-19 22:30:36 -07005950 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005951 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08005952 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005953 lStatus = PERMISSION_DENIED;
5954 goto Exit;
5955 }
5956
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005957 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005958 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005959 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005960 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005961 lStatus = BAD_VALUE;
5962 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005963 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005964 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005965 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005966 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005967 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005968 }
5969 }
5970
Mathias Agopian65ab4712010-07-14 17:59:35 -07005971 {
5972 Mutex::Autolock _l(mLock);
5973
Mathias Agopian65ab4712010-07-14 17:59:35 -07005974
5975 if (!EffectIsNullUuid(&pDesc->uuid)) {
5976 // if uuid is specified, request effect descriptor
5977 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5978 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005979 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005980 goto Exit;
5981 }
5982 } else {
5983 // if uuid is not specified, look for an available implementation
5984 // of the required type in effect factory
5985 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005986 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005987 lStatus = BAD_VALUE;
5988 goto Exit;
5989 }
5990 uint32_t numEffects = 0;
5991 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005992 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005993 bool found = false;
5994
5995 lStatus = EffectQueryNumberEffects(&numEffects);
5996 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005997 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005998 goto Exit;
5999 }
6000 for (uint32_t i = 0; i < numEffects; i++) {
6001 lStatus = EffectQueryEffect(i, &desc);
6002 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006003 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006004 continue;
6005 }
6006 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
6007 // If matching type found save effect descriptor. If the session is
6008 // 0 and the effect is not auxiliary, continue enumeration in case
6009 // an auxiliary version of this effect type is available
6010 found = true;
6011 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07006012 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006013 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6014 break;
6015 }
6016 }
6017 }
6018 if (!found) {
6019 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00006020 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006021 goto Exit;
6022 }
6023 // For same effect type, chose auxiliary version over insert version if
6024 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07006025 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006026 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
6027 memcpy(&desc, &d, sizeof(effect_descriptor_t));
6028 }
6029 }
6030
6031 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07006032 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006033 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6034 lStatus = INVALID_OPERATION;
6035 goto Exit;
6036 }
6037
Eric Laurent59255e42011-07-27 19:49:51 -07006038 // check recording permission for visualizer
6039 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
6040 !recordingAllowed()) {
6041 lStatus = PERMISSION_DENIED;
6042 goto Exit;
6043 }
6044
Mathias Agopian65ab4712010-07-14 17:59:35 -07006045 // return effect descriptor
6046 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
6047
6048 // If output is not specified try to find a matching audio session ID in one of the
6049 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07006050 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
6051 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006052 // Note: io is never 0 when creating an effect on an input
6053 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006054 // look for the thread where the specified audio session is present
6055 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6056 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006057 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07006058 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07006059 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006060 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006061 if (io == 0) {
6062 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6063 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6064 io = mRecordThreads.keyAt(i);
6065 break;
6066 }
6067 }
6068 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006069 // If no output thread contains the requested session ID, default to
6070 // first output. The effect chain will be moved to the correct output
6071 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006072 if (io == 0 && mPlaybackThreads.size()) {
6073 io = mPlaybackThreads.keyAt(0);
6074 }
Steve Block3856b092011-10-20 11:56:00 +01006075 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006076 }
6077 ThreadBase *thread = checkRecordThread_l(io);
6078 if (thread == NULL) {
6079 thread = checkPlaybackThread_l(io);
6080 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00006081 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006082 lStatus = BAD_VALUE;
6083 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07006084 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006085 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006086
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006087 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006088
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006089 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07006090 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6091 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006092 if (handle != 0 && id != NULL) {
6093 *id = handle->id();
6094 }
6095 }
6096
6097Exit:
6098 if(status) {
6099 *status = lStatus;
6100 }
6101 return handle;
6102}
6103
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006104status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
6105 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07006106{
Steve Block3856b092011-10-20 11:56:00 +01006107 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07006108 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006109 Mutex::Autolock _l(mLock);
6110 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006111 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006112 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006113 }
Eric Laurentde070132010-07-13 04:45:46 -07006114 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6115 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006116 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006117 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006118 }
Eric Laurentde070132010-07-13 04:45:46 -07006119 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6120 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006121 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006122 return BAD_VALUE;
6123 }
6124
6125 Mutex::Autolock _dl(dstThread->mLock);
6126 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07006127 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07006128
Mathias Agopian65ab4712010-07-14 17:59:35 -07006129 return NO_ERROR;
6130}
6131
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006132// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07006133status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07006134 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07006135 AudioFlinger::PlaybackThread *dstThread,
6136 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07006137{
Steve Block3856b092011-10-20 11:56:00 +01006138 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006139 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07006140
Eric Laurent59255e42011-07-27 19:49:51 -07006141 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006142 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006143 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006144 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07006145 return INVALID_OPERATION;
6146 }
6147
Eric Laurent39e94f82010-07-28 01:32:47 -07006148 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07006149 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07006150 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07006151 // removed.
6152 srcThread->removeEffectChain_l(chain);
6153
6154 // transfer all effects one by one so that new effect chain is created on new thread with
6155 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006156 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07006157 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006158 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07006159 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6160 while (effect != 0) {
6161 srcThread->removeEffect_l(effect);
6162 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07006163 // removeEffect_l() has stopped the effect if it was active so it must be restarted
6164 if (effect->state() == EffectModule::ACTIVE ||
6165 effect->state() == EffectModule::STOPPING) {
6166 effect->start();
6167 }
Eric Laurent39e94f82010-07-28 01:32:47 -07006168 // if the move request is not received from audio policy manager, the effect must be
6169 // re-registered with the new strategy and output
6170 if (dstChain == 0) {
6171 dstChain = effect->chain().promote();
6172 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006173 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07006174 srcThread->addEffect_l(effect);
6175 return NO_INIT;
6176 }
6177 strategy = dstChain->strategy();
6178 }
6179 if (reRegister) {
6180 AudioSystem::unregisterEffect(effect->id());
6181 AudioSystem::registerEffect(&effect->desc(),
6182 dstOutput,
6183 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07006184 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07006185 effect->id());
6186 }
Eric Laurentde070132010-07-13 04:45:46 -07006187 effect = chain->getEffectFromId_l(0);
6188 }
6189
6190 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006191}
6192
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006193
Mathias Agopian65ab4712010-07-14 17:59:35 -07006194// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006195sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07006196 const sp<AudioFlinger::Client>& client,
6197 const sp<IEffectClient>& effectClient,
6198 int32_t priority,
6199 int sessionId,
6200 effect_descriptor_t *desc,
6201 int *enabled,
6202 status_t *status
6203 )
6204{
6205 sp<EffectModule> effect;
6206 sp<EffectHandle> handle;
6207 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006208 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07006209 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006210 bool effectCreated = false;
6211 bool effectRegistered = false;
6212
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006213 lStatus = initCheck();
6214 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006215 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006216 goto Exit;
6217 }
6218
6219 // Do not allow effects with session ID 0 on direct output or duplicating threads
6220 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07006221 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006222 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07006223 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006224 lStatus = BAD_VALUE;
6225 goto Exit;
6226 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006227 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08006228 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006229 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006230 desc->name, desc->flags, mType);
6231 lStatus = BAD_VALUE;
6232 goto Exit;
6233 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006234
Steve Block3856b092011-10-20 11:56:00 +01006235 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006236
6237 { // scope for mLock
6238 Mutex::Autolock _l(mLock);
6239
6240 // check for existing effect chain with the requested audio session
6241 chain = getEffectChain_l(sessionId);
6242 if (chain == 0) {
6243 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006244 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006245 chain = new EffectChain(this, sessionId);
6246 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07006247 chain->setStrategy(getStrategyForSession_l(sessionId));
6248 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006249 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07006250 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006251 }
6252
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08006253 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006254
6255 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006256 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006257 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07006258 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006259 if (lStatus != NO_ERROR) {
6260 goto Exit;
6261 }
6262 effectRegistered = true;
6263 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07006264 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006265 lStatus = effect->status();
6266 if (lStatus != NO_ERROR) {
6267 goto Exit;
6268 }
Eric Laurentcab11242010-07-15 12:50:15 -07006269 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006270 if (lStatus != NO_ERROR) {
6271 goto Exit;
6272 }
6273 effectCreated = true;
6274
6275 effect->setDevice(mDevice);
6276 effect->setMode(mAudioFlinger->getMode());
6277 }
6278 // create effect handle and connect it to effect module
6279 handle = new EffectHandle(effect, client, effectClient, priority);
6280 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08006281 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006282 *enabled = (int)effect->isEnabled();
6283 }
6284 }
6285
6286Exit:
6287 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07006288 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006289 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07006290 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006291 }
6292 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07006293 AudioSystem::unregisterEffect(effect->id());
6294 }
6295 if (chainCreated) {
6296 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006297 }
6298 handle.clear();
6299 }
6300
6301 if(status) {
6302 *status = lStatus;
6303 }
6304 return handle;
6305}
6306
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006307sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6308{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006309 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08006310 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006311}
6312
Eric Laurentde070132010-07-13 04:45:46 -07006313// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6314// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006315status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07006316{
6317 // check for existing effect chain with the requested audio session
6318 int sessionId = effect->sessionId();
6319 sp<EffectChain> chain = getEffectChain_l(sessionId);
6320 bool chainCreated = false;
6321
6322 if (chain == 0) {
6323 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006324 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006325 chain = new EffectChain(this, sessionId);
6326 addEffectChain_l(chain);
6327 chain->setStrategy(getStrategyForSession_l(sessionId));
6328 chainCreated = true;
6329 }
Steve Block3856b092011-10-20 11:56:00 +01006330 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006331
6332 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006333 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07006334 this, effect->desc().name, chain.get());
6335 return BAD_VALUE;
6336 }
6337
6338 status_t status = chain->addEffect_l(effect);
6339 if (status != NO_ERROR) {
6340 if (chainCreated) {
6341 removeEffectChain_l(chain);
6342 }
6343 return status;
6344 }
6345
6346 effect->setDevice(mDevice);
6347 effect->setMode(mAudioFlinger->getMode());
6348 return NO_ERROR;
6349}
6350
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006351void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07006352
Steve Block3856b092011-10-20 11:56:00 +01006353 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006354 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07006355 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6356 detachAuxEffect_l(effect->id());
6357 }
6358
6359 sp<EffectChain> chain = effect->chain().promote();
6360 if (chain != 0) {
6361 // remove effect chain if removing last effect
6362 if (chain->removeEffect_l(effect) == 0) {
6363 removeEffectChain_l(chain);
6364 }
6365 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00006366 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006367 }
6368}
6369
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006370void AudioFlinger::ThreadBase::lockEffectChains_l(
6371 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
6372{
6373 effectChains = mEffectChains;
6374 for (size_t i = 0; i < mEffectChains.size(); i++) {
6375 mEffectChains[i]->lock();
6376 }
6377}
6378
6379void AudioFlinger::ThreadBase::unlockEffectChains(
6380 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
6381{
6382 for (size_t i = 0; i < effectChains.size(); i++) {
6383 effectChains[i]->unlock();
6384 }
6385}
6386
6387sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6388{
6389 Mutex::Autolock _l(mLock);
6390 return getEffectChain_l(sessionId);
6391}
6392
6393sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6394{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006395 size_t size = mEffectChains.size();
6396 for (size_t i = 0; i < size; i++) {
6397 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08006398 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006399 }
6400 }
Glenn Kasten090f0192012-01-30 13:00:02 -08006401 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006402}
6403
Glenn Kastenf78aee72012-01-04 11:00:47 -08006404void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006405{
6406 Mutex::Autolock _l(mLock);
6407 size_t size = mEffectChains.size();
6408 for (size_t i = 0; i < size; i++) {
6409 mEffectChains[i]->setMode_l(mode);
6410 }
6411}
6412
6413void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006414 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08006415 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07006416
Mathias Agopian65ab4712010-07-14 17:59:35 -07006417 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006418 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006419 // delete the effect module if removing last handle on it
6420 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006421 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006422 removeEffect_l(effect);
6423 AudioSystem::unregisterEffect(effect->id());
6424 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006425 }
6426}
6427
6428status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6429{
6430 int session = chain->sessionId();
6431 int16_t *buffer = mMixBuffer;
6432 bool ownsBuffer = false;
6433
Steve Block3856b092011-10-20 11:56:00 +01006434 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006435 if (session > 0) {
6436 // Only one effect chain can be present in direct output thread and it uses
6437 // the mix buffer as input
6438 if (mType != DIRECT) {
6439 size_t numSamples = mFrameCount * mChannelCount;
6440 buffer = new int16_t[numSamples];
6441 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01006442 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006443 ownsBuffer = true;
6444 }
6445
6446 // Attach all tracks with same session ID to this chain.
6447 for (size_t i = 0; i < mTracks.size(); ++i) {
6448 sp<Track> track = mTracks[i];
6449 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006450 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006451 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006452 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006453 }
6454 }
6455
6456 // indicate all active tracks in the chain
6457 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6458 sp<Track> track = mActiveTracks[i].promote();
6459 if (track == 0) continue;
6460 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006461 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07006462 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006463 }
6464 }
6465 }
6466
6467 chain->setInBuffer(buffer, ownsBuffer);
6468 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006469 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006470 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006471 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6472 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006473 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006474 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6475 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006476 // Effect chain for other sessions are inserted at beginning of effect
6477 // chains list to be processed before output mix effects. Relative order between other
6478 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006479 size_t size = mEffectChains.size();
6480 size_t i = 0;
6481 for (i = 0; i < size; i++) {
6482 if (mEffectChains[i]->sessionId() < session) break;
6483 }
6484 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006485 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006486
6487 return NO_ERROR;
6488}
6489
6490size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6491{
6492 int session = chain->sessionId();
6493
Steve Block3856b092011-10-20 11:56:00 +01006494 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006495
6496 for (size_t i = 0; i < mEffectChains.size(); i++) {
6497 if (chain == mEffectChains[i]) {
6498 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006499 // detach all active tracks from the chain
6500 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6501 sp<Track> track = mActiveTracks[i].promote();
6502 if (track == 0) continue;
6503 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006504 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006505 chain.get(), session);
6506 chain->decActiveTrackCnt();
6507 }
6508 }
6509
Mathias Agopian65ab4712010-07-14 17:59:35 -07006510 // detach all tracks with same session ID from this chain
6511 for (size_t i = 0; i < mTracks.size(); ++i) {
6512 sp<Track> track = mTracks[i];
6513 if (session == track->sessionId()) {
6514 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006515 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006516 }
6517 }
Eric Laurentde070132010-07-13 04:45:46 -07006518 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006519 }
6520 }
6521 return mEffectChains.size();
6522}
6523
Eric Laurentde070132010-07-13 04:45:46 -07006524status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6525 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006526{
6527 Mutex::Autolock _l(mLock);
6528 return attachAuxEffect_l(track, EffectId);
6529}
6530
Eric Laurentde070132010-07-13 04:45:46 -07006531status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6532 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006533{
6534 status_t status = NO_ERROR;
6535
6536 if (EffectId == 0) {
6537 track->setAuxBuffer(0, NULL);
6538 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006539 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6540 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006541 if (effect != 0) {
6542 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6543 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6544 } else {
6545 status = INVALID_OPERATION;
6546 }
6547 } else {
6548 status = BAD_VALUE;
6549 }
6550 }
6551 return status;
6552}
6553
6554void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6555{
6556 for (size_t i = 0; i < mTracks.size(); ++i) {
6557 sp<Track> track = mTracks[i];
6558 if (track->auxEffectId() == effectId) {
6559 attachAuxEffect_l(track, 0);
6560 }
6561 }
6562}
6563
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006564status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6565{
6566 // only one chain per input thread
6567 if (mEffectChains.size() != 0) {
6568 return INVALID_OPERATION;
6569 }
Steve Block3856b092011-10-20 11:56:00 +01006570 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006571
6572 chain->setInBuffer(NULL);
6573 chain->setOutBuffer(NULL);
6574
Eric Laurent59255e42011-07-27 19:49:51 -07006575 checkSuspendOnAddEffectChain_l(chain);
6576
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006577 mEffectChains.add(chain);
6578
6579 return NO_ERROR;
6580}
6581
6582size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6583{
Steve Block3856b092011-10-20 11:56:00 +01006584 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006585 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006586 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6587 chain.get(), mEffectChains.size(), this);
6588 if (mEffectChains.size() == 1) {
6589 mEffectChains.removeAt(0);
6590 }
6591 return 0;
6592}
6593
Mathias Agopian65ab4712010-07-14 17:59:35 -07006594// ----------------------------------------------------------------------------
6595// EffectModule implementation
6596// ----------------------------------------------------------------------------
6597
6598#undef LOG_TAG
6599#define LOG_TAG "AudioFlinger::EffectModule"
6600
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006601AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006602 const wp<AudioFlinger::EffectChain>& chain,
6603 effect_descriptor_t *desc,
6604 int id,
6605 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006606 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006607 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006608{
Steve Block3856b092011-10-20 11:56:00 +01006609 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006610 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006611 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006612 return;
6613 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006614
6615 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6616
6617 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006618 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006619
6620 if (mStatus != NO_ERROR) {
6621 return;
6622 }
6623 lStatus = init();
6624 if (lStatus < 0) {
6625 mStatus = lStatus;
6626 goto Error;
6627 }
6628
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006629 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6630 mPinned = true;
6631 }
Steve Block3856b092011-10-20 11:56:00 +01006632 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006633 return;
6634Error:
6635 EffectRelease(mEffectInterface);
6636 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006637 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006638}
6639
6640AudioFlinger::EffectModule::~EffectModule()
6641{
Steve Block3856b092011-10-20 11:56:00 +01006642 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006643 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006644 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6645 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6646 sp<ThreadBase> thread = mThread.promote();
6647 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006648 audio_stream_t *stream = thread->stream();
6649 if (stream != NULL) {
6650 stream->remove_audio_effect(stream, mEffectInterface);
6651 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006652 }
6653 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006654 // release effect engine
6655 EffectRelease(mEffectInterface);
6656 }
6657}
6658
Glenn Kasten435dbe62012-01-30 10:15:48 -08006659status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006660{
6661 status_t status;
6662
6663 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006664 int priority = handle->priority();
6665 size_t size = mHandles.size();
6666 sp<EffectHandle> h;
6667 size_t i;
6668 for (i = 0; i < size; i++) {
6669 h = mHandles[i].promote();
6670 if (h == 0) continue;
6671 if (h->priority() <= priority) break;
6672 }
6673 // if inserted in first place, move effect control from previous owner to this handle
6674 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006675 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006676 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006677 enabled = h->enabled();
6678 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006679 }
Eric Laurent59255e42011-07-27 19:49:51 -07006680 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006681 status = NO_ERROR;
6682 } else {
6683 status = ALREADY_EXISTS;
6684 }
Steve Block3856b092011-10-20 11:56:00 +01006685 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006686 mHandles.insertAt(handle, i);
6687 return status;
6688}
6689
6690size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6691{
6692 Mutex::Autolock _l(mLock);
6693 size_t size = mHandles.size();
6694 size_t i;
6695 for (i = 0; i < size; i++) {
6696 if (mHandles[i] == handle) break;
6697 }
6698 if (i == size) {
6699 return size;
6700 }
Steve Block3856b092011-10-20 11:56:00 +01006701 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006702
6703 bool enabled = false;
6704 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006705 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006706 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006707 enabled = hdl->enabled();
6708 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006709 mHandles.removeAt(i);
6710 size = mHandles.size();
6711 // if removed from first place, move effect control from this handle to next in line
6712 if (i == 0 && size != 0) {
6713 sp<EffectHandle> h = mHandles[0].promote();
6714 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006715 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006716 }
6717 }
6718
Eric Laurentec437d82011-07-26 20:54:46 -07006719 // Prevent calls to process() and other functions on effect interface from now on.
6720 // The effect engine will be released by the destructor when the last strong reference on
6721 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006722 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006723 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006724 }
6725
Mathias Agopian65ab4712010-07-14 17:59:35 -07006726 return size;
6727}
6728
Eric Laurent59255e42011-07-27 19:49:51 -07006729sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6730{
6731 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08006732 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07006733}
6734
Glenn Kasten58123c32012-02-03 10:32:24 -08006735void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006736{
Glenn Kasten90bebef2012-01-27 15:24:38 -08006737 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006738 // keep a strong reference on this EffectModule to avoid calling the
6739 // destructor before we exit
6740 sp<EffectModule> keep(this);
6741 {
6742 sp<ThreadBase> thread = mThread.promote();
6743 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006744 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006745 }
6746 }
6747}
6748
6749void AudioFlinger::EffectModule::updateState() {
6750 Mutex::Autolock _l(mLock);
6751
6752 switch (mState) {
6753 case RESTART:
6754 reset_l();
6755 // FALL THROUGH
6756
6757 case STARTING:
6758 // clear auxiliary effect input buffer for next accumulation
6759 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6760 memset(mConfig.inputCfg.buffer.raw,
6761 0,
6762 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6763 }
6764 start_l();
6765 mState = ACTIVE;
6766 break;
6767 case STOPPING:
6768 stop_l();
6769 mDisableWaitCnt = mMaxDisableWaitCnt;
6770 mState = STOPPED;
6771 break;
6772 case STOPPED:
6773 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6774 // turn off sequence.
6775 if (--mDisableWaitCnt == 0) {
6776 reset_l();
6777 mState = IDLE;
6778 }
6779 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006780 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006781 break;
6782 }
6783}
6784
6785void AudioFlinger::EffectModule::process()
6786{
6787 Mutex::Autolock _l(mLock);
6788
Eric Laurentec437d82011-07-26 20:54:46 -07006789 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006790 mConfig.inputCfg.buffer.raw == NULL ||
6791 mConfig.outputCfg.buffer.raw == NULL) {
6792 return;
6793 }
6794
Eric Laurent8f45bd72010-08-31 13:50:07 -07006795 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006796 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6797 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006798 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006799 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006800 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006801 }
6802
6803 // do the actual processing in the effect engine
6804 int ret = (*mEffectInterface)->process(mEffectInterface,
6805 &mConfig.inputCfg.buffer,
6806 &mConfig.outputCfg.buffer);
6807
6808 // force transition to IDLE state when engine is ready
6809 if (mState == STOPPED && ret == -ENODATA) {
6810 mDisableWaitCnt = 1;
6811 }
6812
6813 // clear auxiliary effect input buffer for next accumulation
6814 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006815 memset(mConfig.inputCfg.buffer.raw, 0,
6816 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006817 }
6818 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006819 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6820 // If an insert effect is idle and input buffer is different from output buffer,
6821 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006822 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006823 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006824 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6825 int16_t *in = mConfig.inputCfg.buffer.s16;
6826 int16_t *out = mConfig.outputCfg.buffer.s16;
6827 for (size_t i = 0; i < frameCnt; i++) {
6828 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006829 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006830 }
6831 }
6832}
6833
6834void AudioFlinger::EffectModule::reset_l()
6835{
6836 if (mEffectInterface == NULL) {
6837 return;
6838 }
6839 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6840}
6841
6842status_t AudioFlinger::EffectModule::configure()
6843{
6844 uint32_t channels;
6845 if (mEffectInterface == NULL) {
6846 return NO_INIT;
6847 }
6848
6849 sp<ThreadBase> thread = mThread.promote();
6850 if (thread == 0) {
6851 return DEAD_OBJECT;
6852 }
6853
6854 // TODO: handle configuration of effects replacing track process
6855 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006856 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006857 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006858 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006859 }
6860
6861 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006862 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006863 } else {
6864 mConfig.inputCfg.channels = channels;
6865 }
6866 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006867 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6868 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006869 mConfig.inputCfg.samplingRate = thread->sampleRate();
6870 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6871 mConfig.inputCfg.bufferProvider.cookie = NULL;
6872 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6873 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6874 mConfig.outputCfg.bufferProvider.cookie = NULL;
6875 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6876 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6877 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6878 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006879 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006880 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006881 // - in other sessions:
6882 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6883 // other effect: overwrites output buffer: input buffer == output buffer
6884 // Auxiliary effect:
6885 // accumulates in output buffer: input buffer != output buffer
6886 // Therefore: accumulate <=> input buffer != output buffer
6887 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6888 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6889 } else {
6890 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6891 }
6892 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6893 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6894 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6895 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6896
Steve Block3856b092011-10-20 11:56:00 +01006897 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006898 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6899
Mathias Agopian65ab4712010-07-14 17:59:35 -07006900 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006901 uint32_t size = sizeof(int);
6902 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006903 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006904 sizeof(effect_config_t),
6905 &mConfig,
6906 &size,
6907 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006908 if (status == 0) {
6909 status = cmdStatus;
6910 }
6911
6912 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6913 (1000 * mConfig.outputCfg.buffer.frameCount);
6914
6915 return status;
6916}
6917
6918status_t AudioFlinger::EffectModule::init()
6919{
6920 Mutex::Autolock _l(mLock);
6921 if (mEffectInterface == NULL) {
6922 return NO_INIT;
6923 }
6924 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006925 uint32_t size = sizeof(status_t);
6926 status_t status = (*mEffectInterface)->command(mEffectInterface,
6927 EFFECT_CMD_INIT,
6928 0,
6929 NULL,
6930 &size,
6931 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006932 if (status == 0) {
6933 status = cmdStatus;
6934 }
6935 return status;
6936}
6937
Eric Laurentec35a142011-10-05 17:42:25 -07006938status_t AudioFlinger::EffectModule::start()
6939{
6940 Mutex::Autolock _l(mLock);
6941 return start_l();
6942}
6943
Mathias Agopian65ab4712010-07-14 17:59:35 -07006944status_t AudioFlinger::EffectModule::start_l()
6945{
6946 if (mEffectInterface == NULL) {
6947 return NO_INIT;
6948 }
6949 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006950 uint32_t size = sizeof(status_t);
6951 status_t status = (*mEffectInterface)->command(mEffectInterface,
6952 EFFECT_CMD_ENABLE,
6953 0,
6954 NULL,
6955 &size,
6956 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006957 if (status == 0) {
6958 status = cmdStatus;
6959 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006960 if (status == 0 &&
6961 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6962 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6963 sp<ThreadBase> thread = mThread.promote();
6964 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006965 audio_stream_t *stream = thread->stream();
6966 if (stream != NULL) {
6967 stream->add_audio_effect(stream, mEffectInterface);
6968 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006969 }
6970 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006971 return status;
6972}
6973
Eric Laurentec437d82011-07-26 20:54:46 -07006974status_t AudioFlinger::EffectModule::stop()
6975{
6976 Mutex::Autolock _l(mLock);
6977 return stop_l();
6978}
6979
Mathias Agopian65ab4712010-07-14 17:59:35 -07006980status_t AudioFlinger::EffectModule::stop_l()
6981{
6982 if (mEffectInterface == NULL) {
6983 return NO_INIT;
6984 }
6985 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006986 uint32_t size = sizeof(status_t);
6987 status_t status = (*mEffectInterface)->command(mEffectInterface,
6988 EFFECT_CMD_DISABLE,
6989 0,
6990 NULL,
6991 &size,
6992 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006993 if (status == 0) {
6994 status = cmdStatus;
6995 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006996 if (status == 0 &&
6997 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6998 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6999 sp<ThreadBase> thread = mThread.promote();
7000 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007001 audio_stream_t *stream = thread->stream();
7002 if (stream != NULL) {
7003 stream->remove_audio_effect(stream, mEffectInterface);
7004 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007005 }
7006 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007007 return status;
7008}
7009
Eric Laurent25f43952010-07-28 05:40:18 -07007010status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
7011 uint32_t cmdSize,
7012 void *pCmdData,
7013 uint32_t *replySize,
7014 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007015{
7016 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007017// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007018
Eric Laurentec437d82011-07-26 20:54:46 -07007019 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007020 return NO_INIT;
7021 }
Eric Laurent25f43952010-07-28 05:40:18 -07007022 status_t status = (*mEffectInterface)->command(mEffectInterface,
7023 cmdCode,
7024 cmdSize,
7025 pCmdData,
7026 replySize,
7027 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007028 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07007029 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007030 for (size_t i = 1; i < mHandles.size(); i++) {
7031 sp<EffectHandle> h = mHandles[i].promote();
7032 if (h != 0) {
7033 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
7034 }
7035 }
7036 }
7037 return status;
7038}
7039
7040status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
7041{
Eric Laurentdb7c0792011-08-10 10:37:50 -07007042
Mathias Agopian65ab4712010-07-14 17:59:35 -07007043 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007044 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007045
7046 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007047 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
7048 if (enabled && status != NO_ERROR) {
7049 return status;
7050 }
7051
Mathias Agopian65ab4712010-07-14 17:59:35 -07007052 switch (mState) {
7053 // going from disabled to enabled
7054 case IDLE:
7055 mState = STARTING;
7056 break;
7057 case STOPPED:
7058 mState = RESTART;
7059 break;
7060 case STOPPING:
7061 mState = ACTIVE;
7062 break;
7063
7064 // going from enabled to disabled
7065 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007066 mState = STOPPED;
7067 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007068 case STARTING:
7069 mState = IDLE;
7070 break;
7071 case ACTIVE:
7072 mState = STOPPING;
7073 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007074 case DESTROYED:
7075 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007076 }
7077 for (size_t i = 1; i < mHandles.size(); i++) {
7078 sp<EffectHandle> h = mHandles[i].promote();
7079 if (h != 0) {
7080 h->setEnabled(enabled);
7081 }
7082 }
7083 }
7084 return NO_ERROR;
7085}
7086
Glenn Kastenc59c0042012-02-02 14:06:11 -08007087bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007088{
7089 switch (mState) {
7090 case RESTART:
7091 case STARTING:
7092 case ACTIVE:
7093 return true;
7094 case IDLE:
7095 case STOPPING:
7096 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07007097 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07007098 default:
7099 return false;
7100 }
7101}
7102
Glenn Kastenc59c0042012-02-02 14:06:11 -08007103bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07007104{
7105 switch (mState) {
7106 case RESTART:
7107 case ACTIVE:
7108 case STOPPING:
7109 case STOPPED:
7110 return true;
7111 case IDLE:
7112 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07007113 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007114 default:
7115 return false;
7116 }
7117}
7118
Mathias Agopian65ab4712010-07-14 17:59:35 -07007119status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7120{
7121 Mutex::Autolock _l(mLock);
7122 status_t status = NO_ERROR;
7123
7124 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7125 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07007126 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07007127 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7128 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007129 status_t cmdStatus;
7130 uint32_t volume[2];
7131 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07007132 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007133 volume[0] = *left;
7134 volume[1] = *right;
7135 if (controller) {
7136 pVolume = volume;
7137 }
Eric Laurent25f43952010-07-28 05:40:18 -07007138 status = (*mEffectInterface)->command(mEffectInterface,
7139 EFFECT_CMD_SET_VOLUME,
7140 size,
7141 volume,
7142 &size,
7143 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007144 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7145 *left = volume[0];
7146 *right = volume[1];
7147 }
7148 }
7149 return status;
7150}
7151
7152status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7153{
7154 Mutex::Autolock _l(mLock);
7155 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007156 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7157 // audio pre processing modules on RecordThread can receive both output and
7158 // input device indication in the same call
7159 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7160 if (dev) {
7161 status_t cmdStatus;
7162 uint32_t size = sizeof(status_t);
7163
7164 status = (*mEffectInterface)->command(mEffectInterface,
7165 EFFECT_CMD_SET_DEVICE,
7166 sizeof(uint32_t),
7167 &dev,
7168 &size,
7169 &cmdStatus);
7170 if (status == NO_ERROR) {
7171 status = cmdStatus;
7172 }
7173 }
7174 dev = device & AUDIO_DEVICE_IN_ALL;
7175 if (dev) {
7176 status_t cmdStatus;
7177 uint32_t size = sizeof(status_t);
7178
7179 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7180 EFFECT_CMD_SET_INPUT_DEVICE,
7181 sizeof(uint32_t),
7182 &dev,
7183 &size,
7184 &cmdStatus);
7185 if (status2 == NO_ERROR) {
7186 status2 = cmdStatus;
7187 }
7188 if (status == NO_ERROR) {
7189 status = status2;
7190 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007191 }
7192 }
7193 return status;
7194}
7195
Glenn Kastenf78aee72012-01-04 11:00:47 -08007196status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007197{
7198 Mutex::Autolock _l(mLock);
7199 status_t status = NO_ERROR;
7200 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007201 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007202 uint32_t size = sizeof(status_t);
7203 status = (*mEffectInterface)->command(mEffectInterface,
7204 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08007205 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07007206 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07007207 &size,
7208 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007209 if (status == NO_ERROR) {
7210 status = cmdStatus;
7211 }
7212 }
7213 return status;
7214}
7215
Eric Laurent59255e42011-07-27 19:49:51 -07007216void AudioFlinger::EffectModule::setSuspended(bool suspended)
7217{
7218 Mutex::Autolock _l(mLock);
7219 mSuspended = suspended;
7220}
Glenn Kastena3a85482012-01-04 11:01:11 -08007221
7222bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07007223{
7224 Mutex::Autolock _l(mLock);
7225 return mSuspended;
7226}
7227
Mathias Agopian65ab4712010-07-14 17:59:35 -07007228status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7229{
7230 const size_t SIZE = 256;
7231 char buffer[SIZE];
7232 String8 result;
7233
7234 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7235 result.append(buffer);
7236
7237 bool locked = tryLock(mLock);
7238 // failed to lock - AudioFlinger is probably deadlocked
7239 if (!locked) {
7240 result.append("\t\tCould not lock Fx mutex:\n");
7241 }
7242
7243 result.append("\t\tSession Status State Engine:\n");
7244 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7245 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7246 result.append(buffer);
7247
7248 result.append("\t\tDescriptor:\n");
7249 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7250 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7251 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7252 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7253 result.append(buffer);
7254 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7255 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7256 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7257 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7258 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07007259 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007260 mDescriptor.apiVersion,
7261 mDescriptor.flags);
7262 result.append(buffer);
7263 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7264 mDescriptor.name);
7265 result.append(buffer);
7266 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7267 mDescriptor.implementor);
7268 result.append(buffer);
7269
7270 result.append("\t\t- Input configuration:\n");
7271 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7272 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7273 (uint32_t)mConfig.inputCfg.buffer.raw,
7274 mConfig.inputCfg.buffer.frameCount,
7275 mConfig.inputCfg.samplingRate,
7276 mConfig.inputCfg.channels,
7277 mConfig.inputCfg.format);
7278 result.append(buffer);
7279
7280 result.append("\t\t- Output configuration:\n");
7281 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7282 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7283 (uint32_t)mConfig.outputCfg.buffer.raw,
7284 mConfig.outputCfg.buffer.frameCount,
7285 mConfig.outputCfg.samplingRate,
7286 mConfig.outputCfg.channels,
7287 mConfig.outputCfg.format);
7288 result.append(buffer);
7289
7290 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7291 result.append(buffer);
7292 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7293 for (size_t i = 0; i < mHandles.size(); ++i) {
7294 sp<EffectHandle> handle = mHandles[i].promote();
7295 if (handle != 0) {
7296 handle->dump(buffer, SIZE);
7297 result.append(buffer);
7298 }
7299 }
7300
7301 result.append("\n");
7302
7303 write(fd, result.string(), result.length());
7304
7305 if (locked) {
7306 mLock.unlock();
7307 }
7308
7309 return NO_ERROR;
7310}
7311
7312// ----------------------------------------------------------------------------
7313// EffectHandle implementation
7314// ----------------------------------------------------------------------------
7315
7316#undef LOG_TAG
7317#define LOG_TAG "AudioFlinger::EffectHandle"
7318
7319AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7320 const sp<AudioFlinger::Client>& client,
7321 const sp<IEffectClient>& effectClient,
7322 int32_t priority)
7323 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007324 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007325 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007326{
Steve Block3856b092011-10-20 11:56:00 +01007327 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007328
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007329 if (client == 0) {
7330 return;
7331 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007332 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7333 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7334 if (mCblkMemory != 0) {
7335 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7336
Glenn Kastena0d68332012-01-27 16:47:15 -08007337 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007338 new(mCblk) effect_param_cblk_t();
7339 mBuffer = (uint8_t *)mCblk + bufOffset;
7340 }
7341 } else {
Steve Block29357bc2012-01-06 19:20:56 +00007342 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007343 return;
7344 }
7345}
7346
7347AudioFlinger::EffectHandle::~EffectHandle()
7348{
Steve Block3856b092011-10-20 11:56:00 +01007349 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007350 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01007351 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007352}
7353
7354status_t AudioFlinger::EffectHandle::enable()
7355{
Steve Block3856b092011-10-20 11:56:00 +01007356 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007357 if (!mHasControl) return INVALID_OPERATION;
7358 if (mEffect == 0) return DEAD_OBJECT;
7359
Eric Laurentdb7c0792011-08-10 10:37:50 -07007360 if (mEnabled) {
7361 return NO_ERROR;
7362 }
7363
Eric Laurent59255e42011-07-27 19:49:51 -07007364 mEnabled = true;
7365
7366 sp<ThreadBase> thread = mEffect->thread().promote();
7367 if (thread != 0) {
7368 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7369 }
7370
7371 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7372 if (mEffect->suspended()) {
7373 return NO_ERROR;
7374 }
7375
Eric Laurentdb7c0792011-08-10 10:37:50 -07007376 status_t status = mEffect->setEnabled(true);
7377 if (status != NO_ERROR) {
7378 if (thread != 0) {
7379 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7380 }
7381 mEnabled = false;
7382 }
7383 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007384}
7385
7386status_t AudioFlinger::EffectHandle::disable()
7387{
Steve Block3856b092011-10-20 11:56:00 +01007388 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007389 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07007390 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007391
Eric Laurentdb7c0792011-08-10 10:37:50 -07007392 if (!mEnabled) {
7393 return NO_ERROR;
7394 }
Eric Laurent59255e42011-07-27 19:49:51 -07007395 mEnabled = false;
7396
7397 if (mEffect->suspended()) {
7398 return NO_ERROR;
7399 }
7400
7401 status_t status = mEffect->setEnabled(false);
7402
7403 sp<ThreadBase> thread = mEffect->thread().promote();
7404 if (thread != 0) {
7405 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7406 }
7407
7408 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007409}
7410
7411void AudioFlinger::EffectHandle::disconnect()
7412{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007413 disconnect(true);
7414}
7415
Glenn Kasten58123c32012-02-03 10:32:24 -08007416void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007417{
Glenn Kasten58123c32012-02-03 10:32:24 -08007418 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007419 if (mEffect == 0) {
7420 return;
7421 }
Glenn Kasten58123c32012-02-03 10:32:24 -08007422 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07007423
Eric Laurenta85a74a2011-10-19 11:44:54 -07007424 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007425 sp<ThreadBase> thread = mEffect->thread().promote();
7426 if (thread != 0) {
7427 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7428 }
Eric Laurent59255e42011-07-27 19:49:51 -07007429 }
7430
Mathias Agopian65ab4712010-07-14 17:59:35 -07007431 // release sp on module => module destructor can be called now
7432 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007433 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08007434 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08007435 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007436 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7437 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08007438 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007439 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07007440 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7441 mClient.clear();
7442 }
7443}
7444
Eric Laurent25f43952010-07-28 05:40:18 -07007445status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7446 uint32_t cmdSize,
7447 void *pCmdData,
7448 uint32_t *replySize,
7449 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007450{
Steve Block3856b092011-10-20 11:56:00 +01007451// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07007452// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007453
7454 // only get parameter command is permitted for applications not controlling the effect
7455 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7456 return INVALID_OPERATION;
7457 }
7458 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007459 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007460
7461 // handle commands that are not forwarded transparently to effect engine
7462 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7463 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7464 // no risk to block the whole media server process or mixer threads is we are stuck here
7465 Mutex::Autolock _l(mCblk->lock);
7466 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7467 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7468 mCblk->serverIndex = 0;
7469 mCblk->clientIndex = 0;
7470 return BAD_VALUE;
7471 }
7472 status_t status = NO_ERROR;
7473 while (mCblk->serverIndex < mCblk->clientIndex) {
7474 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007475 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007476 int *p = (int *)(mBuffer + mCblk->serverIndex);
7477 int size = *p++;
7478 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007479 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007480 break;
7481 }
7482 effect_param_t *param = (effect_param_t *)p;
7483 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007484 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007485 mCblk->serverIndex += size;
7486 continue;
7487 }
Eric Laurent25f43952010-07-28 05:40:18 -07007488 uint32_t psize = sizeof(effect_param_t) +
7489 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7490 param->vsize;
7491 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7492 psize,
7493 p,
7494 &rsize,
7495 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007496 // stop at first error encountered
7497 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007498 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007499 *(int *)pReplyData = reply;
7500 break;
7501 } else if (reply != NO_ERROR) {
7502 *(int *)pReplyData = reply;
7503 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007504 }
7505 mCblk->serverIndex += size;
7506 }
7507 mCblk->serverIndex = 0;
7508 mCblk->clientIndex = 0;
7509 return status;
7510 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007511 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007512 return enable();
7513 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007514 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007515 return disable();
7516 }
7517
7518 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7519}
7520
Eric Laurent59255e42011-07-27 19:49:51 -07007521void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007522{
Steve Block3856b092011-10-20 11:56:00 +01007523 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007524
7525 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007526 mEnabled = enabled;
7527
Mathias Agopian65ab4712010-07-14 17:59:35 -07007528 if (signal && mEffectClient != 0) {
7529 mEffectClient->controlStatusChanged(hasControl);
7530 }
7531}
7532
Eric Laurent25f43952010-07-28 05:40:18 -07007533void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7534 uint32_t cmdSize,
7535 void *pCmdData,
7536 uint32_t replySize,
7537 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007538{
7539 if (mEffectClient != 0) {
7540 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7541 }
7542}
7543
7544
7545
7546void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7547{
7548 if (mEffectClient != 0) {
7549 mEffectClient->enableStatusChanged(enabled);
7550 }
7551}
7552
7553status_t AudioFlinger::EffectHandle::onTransact(
7554 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7555{
7556 return BnEffect::onTransact(code, data, reply, flags);
7557}
7558
7559
7560void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7561{
Glenn Kastena0d68332012-01-27 16:47:15 -08007562 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007563
7564 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08007565 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007566 mPriority,
7567 mHasControl,
7568 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007569 mCblk ? mCblk->clientIndex : 0,
7570 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007571 );
7572
7573 if (locked) {
7574 mCblk->lock.unlock();
7575 }
7576}
7577
7578#undef LOG_TAG
7579#define LOG_TAG "AudioFlinger::EffectChain"
7580
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007581AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007582 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007583 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007584 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7585 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007586{
Dima Zavinfce7a472011-04-19 22:30:36 -07007587 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007588 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007589 return;
7590 }
7591 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7592 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007593}
7594
7595AudioFlinger::EffectChain::~EffectChain()
7596{
7597 if (mOwnInBuffer) {
7598 delete mInBuffer;
7599 }
7600
7601}
7602
Eric Laurent59255e42011-07-27 19:49:51 -07007603// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007604sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007605{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007606 size_t size = mEffects.size();
7607
7608 for (size_t i = 0; i < size; i++) {
7609 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007610 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007611 }
7612 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007613 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007614}
7615
Eric Laurent59255e42011-07-27 19:49:51 -07007616// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007617sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007618{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007619 size_t size = mEffects.size();
7620
7621 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007622 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7623 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007624 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007625 }
7626 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007627 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007628}
7629
Eric Laurent59255e42011-07-27 19:49:51 -07007630// getEffectFromType_l() must be called with ThreadBase::mLock held
7631sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7632 const effect_uuid_t *type)
7633{
Eric Laurent59255e42011-07-27 19:49:51 -07007634 size_t size = mEffects.size();
7635
7636 for (size_t i = 0; i < size; i++) {
7637 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007638 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007639 }
7640 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007641 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007642}
7643
Mathias Agopian65ab4712010-07-14 17:59:35 -07007644// Must be called with EffectChain::mLock locked
7645void AudioFlinger::EffectChain::process_l()
7646{
Eric Laurentdac69112010-09-28 14:09:57 -07007647 sp<ThreadBase> thread = mThread.promote();
7648 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007649 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007650 return;
7651 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007652 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7653 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007654 // always process effects unless no more tracks are on the session and the effect tail
7655 // has been rendered
7656 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007657 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007658 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007659
Eric Laurent544fe9b2011-11-11 15:42:52 -08007660 if (!tracksOnSession && mTailBufferCount == 0) {
7661 doProcess = false;
7662 }
7663
7664 if (activeTrackCnt() == 0) {
7665 // if no track is active and the effect tail has not been rendered,
7666 // the input buffer must be cleared here as the mixer process will not do it
7667 if (tracksOnSession || mTailBufferCount > 0) {
7668 size_t numSamples = thread->frameCount() * thread->channelCount();
7669 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7670 if (mTailBufferCount > 0) {
7671 mTailBufferCount--;
7672 }
7673 }
7674 }
Eric Laurentdac69112010-09-28 14:09:57 -07007675 }
7676
Mathias Agopian65ab4712010-07-14 17:59:35 -07007677 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007678 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007679 for (size_t i = 0; i < size; i++) {
7680 mEffects[i]->process();
7681 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007682 }
7683 for (size_t i = 0; i < size; i++) {
7684 mEffects[i]->updateState();
7685 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007686}
7687
Eric Laurentcab11242010-07-15 12:50:15 -07007688// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007689status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007690{
7691 effect_descriptor_t desc = effect->desc();
7692 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7693
7694 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007695 effect->setChain(this);
7696 sp<ThreadBase> thread = mThread.promote();
7697 if (thread == 0) {
7698 return NO_INIT;
7699 }
7700 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007701
7702 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7703 // Auxiliary effects are inserted at the beginning of mEffects vector as
7704 // they are processed first and accumulated in chain input buffer
7705 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007706
Mathias Agopian65ab4712010-07-14 17:59:35 -07007707 // the input buffer for auxiliary effect contains mono samples in
7708 // 32 bit format. This is to avoid saturation in AudoMixer
7709 // accumulation stage. Saturation is done in EffectModule::process() before
7710 // calling the process in effect engine
7711 size_t numSamples = thread->frameCount();
7712 int32_t *buffer = new int32_t[numSamples];
7713 memset(buffer, 0, numSamples * sizeof(int32_t));
7714 effect->setInBuffer((int16_t *)buffer);
7715 // auxiliary effects output samples to chain input buffer for further processing
7716 // by insert effects
7717 effect->setOutBuffer(mInBuffer);
7718 } else {
7719 // Insert effects are inserted at the end of mEffects vector as they are processed
7720 // after track and auxiliary effects.
7721 // Insert effect order as a function of indicated preference:
7722 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7723 // another effect is present
7724 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7725 // last effect claiming first position
7726 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7727 // first effect claiming last position
7728 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7729 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7730 // already present
7731
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007732 size_t size = mEffects.size();
7733 size_t idx_insert = size;
7734 ssize_t idx_insert_first = -1;
7735 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007736
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007737 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007738 effect_descriptor_t d = mEffects[i]->desc();
7739 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7740 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7741 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7742 // check invalid effect chaining combinations
7743 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7744 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007745 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007746 return INVALID_OPERATION;
7747 }
7748 // remember position of first insert effect and by default
7749 // select this as insert position for new effect
7750 if (idx_insert == size) {
7751 idx_insert = i;
7752 }
7753 // remember position of last insert effect claiming
7754 // first position
7755 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7756 idx_insert_first = i;
7757 }
7758 // remember position of first insert effect claiming
7759 // last position
7760 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7761 idx_insert_last == -1) {
7762 idx_insert_last = i;
7763 }
7764 }
7765 }
7766
7767 // modify idx_insert from first position if needed
7768 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7769 if (idx_insert_last != -1) {
7770 idx_insert = idx_insert_last;
7771 } else {
7772 idx_insert = size;
7773 }
7774 } else {
7775 if (idx_insert_first != -1) {
7776 idx_insert = idx_insert_first + 1;
7777 }
7778 }
7779
7780 // always read samples from chain input buffer
7781 effect->setInBuffer(mInBuffer);
7782
7783 // if last effect in the chain, output samples to chain
7784 // output buffer, otherwise to chain input buffer
7785 if (idx_insert == size) {
7786 if (idx_insert != 0) {
7787 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7788 mEffects[idx_insert-1]->configure();
7789 }
7790 effect->setOutBuffer(mOutBuffer);
7791 } else {
7792 effect->setOutBuffer(mInBuffer);
7793 }
7794 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007795
Steve Block3856b092011-10-20 11:56:00 +01007796 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007797 }
7798 effect->configure();
7799 return NO_ERROR;
7800}
7801
Eric Laurentcab11242010-07-15 12:50:15 -07007802// removeEffect_l() must be called with PlaybackThread::mLock held
7803size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007804{
7805 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007806 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007807 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7808
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007809 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007810 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007811 // calling stop here will remove pre-processing effect from the audio HAL.
7812 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7813 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007814 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7815 mEffects[i]->state() == EffectModule::STOPPING) {
7816 mEffects[i]->stop();
7817 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007818 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7819 delete[] effect->inBuffer();
7820 } else {
7821 if (i == size - 1 && i != 0) {
7822 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7823 mEffects[i - 1]->configure();
7824 }
7825 }
7826 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007827 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007828 break;
7829 }
7830 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007831
7832 return mEffects.size();
7833}
7834
Eric Laurentcab11242010-07-15 12:50:15 -07007835// setDevice_l() must be called with PlaybackThread::mLock held
7836void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007837{
7838 size_t size = mEffects.size();
7839 for (size_t i = 0; i < size; i++) {
7840 mEffects[i]->setDevice(device);
7841 }
7842}
7843
Eric Laurentcab11242010-07-15 12:50:15 -07007844// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007845void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007846{
7847 size_t size = mEffects.size();
7848 for (size_t i = 0; i < size; i++) {
7849 mEffects[i]->setMode(mode);
7850 }
7851}
7852
Eric Laurentcab11242010-07-15 12:50:15 -07007853// setVolume_l() must be called with PlaybackThread::mLock held
7854bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007855{
7856 uint32_t newLeft = *left;
7857 uint32_t newRight = *right;
7858 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007859 int ctrlIdx = -1;
7860 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007861
Eric Laurentcab11242010-07-15 12:50:15 -07007862 // first update volume controller
7863 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007864 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007865 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7866 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007867 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007868 break;
7869 }
7870 }
7871
7872 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007873 if (hasControl) {
7874 *left = mNewLeftVolume;
7875 *right = mNewRightVolume;
7876 }
7877 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007878 }
7879
7880 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007881 mLeftVolume = newLeft;
7882 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007883
7884 // second get volume update from volume controller
7885 if (ctrlIdx >= 0) {
7886 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007887 mNewLeftVolume = newLeft;
7888 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007889 }
7890 // then indicate volume to all other effects in chain.
7891 // Pass altered volume to effects before volume controller
7892 // and requested volume to effects after controller
7893 uint32_t lVol = newLeft;
7894 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007895
Mathias Agopian65ab4712010-07-14 17:59:35 -07007896 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007897 if ((int)i == ctrlIdx) continue;
7898 // this also works for ctrlIdx == -1 when there is no volume controller
7899 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007900 lVol = *left;
7901 rVol = *right;
7902 }
7903 mEffects[i]->setVolume(&lVol, &rVol, false);
7904 }
7905 *left = newLeft;
7906 *right = newRight;
7907
7908 return hasControl;
7909}
7910
Mathias Agopian65ab4712010-07-14 17:59:35 -07007911status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7912{
7913 const size_t SIZE = 256;
7914 char buffer[SIZE];
7915 String8 result;
7916
7917 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7918 result.append(buffer);
7919
7920 bool locked = tryLock(mLock);
7921 // failed to lock - AudioFlinger is probably deadlocked
7922 if (!locked) {
7923 result.append("\tCould not lock mutex:\n");
7924 }
7925
Eric Laurentcab11242010-07-15 12:50:15 -07007926 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7927 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007928 mEffects.size(),
7929 (uint32_t)mInBuffer,
7930 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007931 mActiveTrackCnt);
7932 result.append(buffer);
7933 write(fd, result.string(), result.size());
7934
7935 for (size_t i = 0; i < mEffects.size(); ++i) {
7936 sp<EffectModule> effect = mEffects[i];
7937 if (effect != 0) {
7938 effect->dump(fd, args);
7939 }
7940 }
7941
7942 if (locked) {
7943 mLock.unlock();
7944 }
7945
7946 return NO_ERROR;
7947}
7948
Eric Laurent59255e42011-07-27 19:49:51 -07007949// must be called with ThreadBase::mLock held
7950void AudioFlinger::EffectChain::setEffectSuspended_l(
7951 const effect_uuid_t *type, bool suspend)
7952{
7953 sp<SuspendedEffectDesc> desc;
7954 // use effect type UUID timelow as key as there is no real risk of identical
7955 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007956 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007957 if (suspend) {
7958 if (index >= 0) {
7959 desc = mSuspendedEffects.valueAt(index);
7960 } else {
7961 desc = new SuspendedEffectDesc();
7962 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7963 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007964 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007965 }
7966 if (desc->mRefCount++ == 0) {
7967 sp<EffectModule> effect = getEffectIfEnabled(type);
7968 if (effect != 0) {
7969 desc->mEffect = effect;
7970 effect->setSuspended(true);
7971 effect->setEnabled(false);
7972 }
7973 }
7974 } else {
7975 if (index < 0) {
7976 return;
7977 }
7978 desc = mSuspendedEffects.valueAt(index);
7979 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007980 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007981 desc->mRefCount = 1;
7982 }
7983 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007984 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007985 if (desc->mEffect != 0) {
7986 sp<EffectModule> effect = desc->mEffect.promote();
7987 if (effect != 0) {
7988 effect->setSuspended(false);
7989 sp<EffectHandle> handle = effect->controlHandle();
7990 if (handle != 0) {
7991 effect->setEnabled(handle->enabled());
7992 }
7993 }
7994 desc->mEffect.clear();
7995 }
7996 mSuspendedEffects.removeItemsAt(index);
7997 }
7998 }
7999}
8000
8001// must be called with ThreadBase::mLock held
8002void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
8003{
8004 sp<SuspendedEffectDesc> desc;
8005
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008006 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07008007 if (suspend) {
8008 if (index >= 0) {
8009 desc = mSuspendedEffects.valueAt(index);
8010 } else {
8011 desc = new SuspendedEffectDesc();
8012 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01008013 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07008014 }
8015 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08008016 Vector< sp<EffectModule> > effects;
8017 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07008018 for (size_t i = 0; i < effects.size(); i++) {
8019 setEffectSuspended_l(&effects[i]->desc().type, true);
8020 }
8021 }
8022 } else {
8023 if (index < 0) {
8024 return;
8025 }
8026 desc = mSuspendedEffects.valueAt(index);
8027 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008028 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008029 desc->mRefCount = 1;
8030 }
8031 if (--desc->mRefCount == 0) {
8032 Vector<const effect_uuid_t *> types;
8033 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
8034 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
8035 continue;
8036 }
8037 types.add(&mSuspendedEffects.valueAt(i)->mType);
8038 }
8039 for (size_t i = 0; i < types.size(); i++) {
8040 setEffectSuspended_l(types[i], false);
8041 }
Steve Block3856b092011-10-20 11:56:00 +01008042 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008043 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
8044 }
8045 }
8046}
8047
Eric Laurent6bffdb82011-09-23 08:40:41 -07008048
8049// The volume effect is used for automated tests only
8050#ifndef OPENSL_ES_H_
8051static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
8052 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
8053const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
8054#endif //OPENSL_ES_H_
8055
Eric Laurentdb7c0792011-08-10 10:37:50 -07008056bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
8057{
8058 // auxiliary effects and visualizer are never suspended on output mix
8059 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8060 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07008061 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8062 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008063 return false;
8064 }
8065 return true;
8066}
8067
Glenn Kastend0539712012-01-30 12:56:03 -08008068void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07008069{
Glenn Kastend0539712012-01-30 12:56:03 -08008070 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07008071 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08008072 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8073 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07008074 }
Eric Laurent59255e42011-07-27 19:49:51 -07008075 }
Eric Laurent59255e42011-07-27 19:49:51 -07008076}
8077
8078sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8079 const effect_uuid_t *type)
8080{
Glenn Kasten090f0192012-01-30 13:00:02 -08008081 sp<EffectModule> effect = getEffectFromType_l(type);
8082 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008083}
8084
8085void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8086 bool enabled)
8087{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008088 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008089 if (enabled) {
8090 if (index < 0) {
8091 // if the effect is not suspend check if all effects are suspended
8092 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8093 if (index < 0) {
8094 return;
8095 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07008096 if (!isEffectEligibleForSuspend(effect->desc())) {
8097 return;
8098 }
Eric Laurent59255e42011-07-27 19:49:51 -07008099 setEffectSuspended_l(&effect->desc().type, enabled);
8100 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07008101 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008102 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07008103 return;
8104 }
Eric Laurent59255e42011-07-27 19:49:51 -07008105 }
Steve Block3856b092011-10-20 11:56:00 +01008106 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07008107 effect->desc().type.timeLow);
8108 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8109 // if effect is requested to suspended but was not yet enabled, supend it now.
8110 if (desc->mEffect == 0) {
8111 desc->mEffect = effect;
8112 effect->setEnabled(false);
8113 effect->setSuspended(true);
8114 }
8115 } else {
8116 if (index < 0) {
8117 return;
8118 }
Steve Block3856b092011-10-20 11:56:00 +01008119 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07008120 effect->desc().type.timeLow);
8121 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8122 desc->mEffect.clear();
8123 effect->setSuspended(false);
8124 }
8125}
8126
Mathias Agopian65ab4712010-07-14 17:59:35 -07008127#undef LOG_TAG
8128#define LOG_TAG "AudioFlinger"
8129
8130// ----------------------------------------------------------------------------
8131
8132status_t AudioFlinger::onTransact(
8133 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8134{
8135 return BnAudioFlinger::onTransact(code, data, reply, flags);
8136}
8137
Mathias Agopian65ab4712010-07-14 17:59:35 -07008138}; // namespace android