blob: 4446681399b6f8e957e6ebeadfe1b5fa5b41b752 [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,
435 uint32_t flags,
436 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800437 audio_io_handle_t output,
John Grossman4ff14ba2012-02-08 16:37:41 -0800438 bool isTimed,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700439 int *sessionId,
440 status_t *status)
441{
442 sp<PlaybackThread::Track> track;
443 sp<TrackHandle> trackHandle;
444 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700445 status_t lStatus;
446 int lSessionId;
447
Glenn Kasten263709e2012-01-06 08:40:01 -0800448 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
449 // but if someone uses binder directly they could bypass that and cause us to crash
450 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000451 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700452 lStatus = BAD_VALUE;
453 goto Exit;
454 }
455
456 {
457 Mutex::Autolock _l(mLock);
458 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700459 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700460 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000461 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700462 lStatus = BAD_VALUE;
463 goto Exit;
464 }
465
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800466 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700467
Steve Block3856b092011-10-20 11:56:00 +0100468 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700469 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700470 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700471 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
472 if (mPlaybackThreads.keyAt(i) != output) {
473 // prevent same audio session on different output threads
474 uint32_t sessions = t->hasAudioSession(*sessionId);
475 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000476 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700477 lStatus = BAD_VALUE;
478 goto Exit;
479 }
480 // check if an effect with same session ID is waiting for a track to be created
481 if (sessions & PlaybackThread::EFFECT_SESSION) {
482 effectThread = t.get();
483 }
Eric Laurentde070132010-07-13 04:45:46 -0700484 }
485 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700486 lSessionId = *sessionId;
487 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700488 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700489 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700490 if (sessionId != NULL) {
491 *sessionId = lSessionId;
492 }
493 }
Steve Block3856b092011-10-20 11:56:00 +0100494 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700495
496 track = thread->createTrack_l(client, streamType, sampleRate, format,
John Grossman4ff14ba2012-02-08 16:37:41 -0800497 channelMask, frameCount, sharedBuffer, lSessionId, isTimed, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700498
499 // move effect chain to this output thread if an effect on same session was waiting
500 // for a track to be created
501 if (lStatus == NO_ERROR && effectThread != NULL) {
502 Mutex::Autolock _dl(thread->mLock);
503 Mutex::Autolock _sl(effectThread->mLock);
504 moveEffectChain_l(lSessionId, effectThread, thread, true);
505 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700506 }
507 if (lStatus == NO_ERROR) {
508 trackHandle = new TrackHandle(track);
509 } else {
510 // remove local strong reference to Client before deleting the Track so that the Client
511 // destructor is called by the TrackBase destructor with mLock held
512 client.clear();
513 track.clear();
514 }
515
516Exit:
517 if(status) {
518 *status = lStatus;
519 }
520 return trackHandle;
521}
522
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800523uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700524{
525 Mutex::Autolock _l(mLock);
526 PlaybackThread *thread = checkPlaybackThread_l(output);
527 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000528 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700529 return 0;
530 }
531 return thread->sampleRate();
532}
533
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800534int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700535{
536 Mutex::Autolock _l(mLock);
537 PlaybackThread *thread = checkPlaybackThread_l(output);
538 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000539 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700540 return 0;
541 }
542 return thread->channelCount();
543}
544
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800545audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700546{
547 Mutex::Autolock _l(mLock);
548 PlaybackThread *thread = checkPlaybackThread_l(output);
549 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000550 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800551 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700552 }
553 return thread->format();
554}
555
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800556size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700557{
558 Mutex::Autolock _l(mLock);
559 PlaybackThread *thread = checkPlaybackThread_l(output);
560 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000561 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700562 return 0;
563 }
564 return thread->frameCount();
565}
566
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800567uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700568{
569 Mutex::Autolock _l(mLock);
570 PlaybackThread *thread = checkPlaybackThread_l(output);
571 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000572 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700573 return 0;
574 }
575 return thread->latency();
576}
577
578status_t AudioFlinger::setMasterVolume(float value)
579{
Eric Laurenta1884f92011-08-23 08:25:03 -0700580 status_t ret = initCheck();
581 if (ret != NO_ERROR) {
582 return ret;
583 }
584
Mathias Agopian65ab4712010-07-14 17:59:35 -0700585 // check calling permissions
586 if (!settingsAllowed()) {
587 return PERMISSION_DENIED;
588 }
589
John Grossman4ff14ba2012-02-08 16:37:41 -0800590 float swmv = value;
591
Mathias Agopian65ab4712010-07-14 17:59:35 -0700592 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800593 if (MVS_NONE != mMasterVolumeSupportLvl) {
594 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
595 AutoMutex lock(mHardwareLock);
596 audio_hw_device_t *dev = mAudioHwDevs[i];
597
598 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
599 if (NULL != dev->set_master_volume) {
600 dev->set_master_volume(dev, value);
601 }
602 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800603 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800604
605 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700606 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700607
Eric Laurent93575202011-01-18 18:39:02 -0800608 Mutex::Autolock _l(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -0800609 mMasterVolume = value;
610 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800611 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossman4ff14ba2012-02-08 16:37:41 -0800612 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700613
614 return NO_ERROR;
615}
616
Glenn Kastenf78aee72012-01-04 11:00:47 -0800617status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700618{
Eric Laurenta1884f92011-08-23 08:25:03 -0700619 status_t ret = initCheck();
620 if (ret != NO_ERROR) {
621 return ret;
622 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700623
624 // check calling permissions
625 if (!settingsAllowed()) {
626 return PERMISSION_DENIED;
627 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800628 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000629 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700630 return BAD_VALUE;
631 }
632
633 { // scope for the lock
634 AutoMutex lock(mHardwareLock);
635 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700636 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700637 mHardwareStatus = AUDIO_HW_IDLE;
638 }
639
640 if (NO_ERROR == ret) {
641 Mutex::Autolock _l(mLock);
642 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800643 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700644 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700645 }
646
647 return ret;
648}
649
650status_t AudioFlinger::setMicMute(bool state)
651{
Eric Laurenta1884f92011-08-23 08:25:03 -0700652 status_t ret = initCheck();
653 if (ret != NO_ERROR) {
654 return ret;
655 }
656
Mathias Agopian65ab4712010-07-14 17:59:35 -0700657 // check calling permissions
658 if (!settingsAllowed()) {
659 return PERMISSION_DENIED;
660 }
661
662 AutoMutex lock(mHardwareLock);
663 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700664 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700665 mHardwareStatus = AUDIO_HW_IDLE;
666 return ret;
667}
668
669bool AudioFlinger::getMicMute() const
670{
Eric Laurenta1884f92011-08-23 08:25:03 -0700671 status_t ret = initCheck();
672 if (ret != NO_ERROR) {
673 return false;
674 }
675
Dima Zavinfce7a472011-04-19 22:30:36 -0700676 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800677 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700678 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700679 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700680 mHardwareStatus = AUDIO_HW_IDLE;
681 return state;
682}
683
684status_t AudioFlinger::setMasterMute(bool muted)
685{
686 // check calling permissions
687 if (!settingsAllowed()) {
688 return PERMISSION_DENIED;
689 }
690
Eric Laurent93575202011-01-18 18:39:02 -0800691 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800692 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700693 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800694 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700695 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
696
697 return NO_ERROR;
698}
699
700float AudioFlinger::masterVolume() const
701{
Glenn Kasten98067102011-12-13 11:47:54 -0800702 Mutex::Autolock _l(mLock);
703 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700704}
705
John Grossman4ff14ba2012-02-08 16:37:41 -0800706float AudioFlinger::masterVolumeSW() const
707{
708 Mutex::Autolock _l(mLock);
709 return masterVolumeSW_l();
710}
711
Mathias Agopian65ab4712010-07-14 17:59:35 -0700712bool AudioFlinger::masterMute() const
713{
Glenn Kasten98067102011-12-13 11:47:54 -0800714 Mutex::Autolock _l(mLock);
715 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700716}
717
John Grossman4ff14ba2012-02-08 16:37:41 -0800718float AudioFlinger::masterVolume_l() const
719{
720 if (MVS_FULL == mMasterVolumeSupportLvl) {
721 float ret_val;
722 AutoMutex lock(mHardwareLock);
723
724 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
725 assert(NULL != mPrimaryHardwareDev);
726 assert(NULL != mPrimaryHardwareDev->get_master_volume);
727
728 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
729 mHardwareStatus = AUDIO_HW_IDLE;
730 return ret_val;
731 }
732
733 return mMasterVolume;
734}
735
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800736status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
737 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700738{
739 // check calling permissions
740 if (!settingsAllowed()) {
741 return PERMISSION_DENIED;
742 }
743
Glenn Kasten263709e2012-01-06 08:40:01 -0800744 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000745 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700746 return BAD_VALUE;
747 }
748
749 AutoMutex lock(mLock);
750 PlaybackThread *thread = NULL;
751 if (output) {
752 thread = checkPlaybackThread_l(output);
753 if (thread == NULL) {
754 return BAD_VALUE;
755 }
756 }
757
758 mStreamTypes[stream].volume = value;
759
760 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800761 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700762 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
763 }
764 } else {
765 thread->setStreamVolume(stream, value);
766 }
767
768 return NO_ERROR;
769}
770
Glenn Kastenfff6d712012-01-12 16:38:12 -0800771status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700772{
773 // check calling permissions
774 if (!settingsAllowed()) {
775 return PERMISSION_DENIED;
776 }
777
Glenn Kasten263709e2012-01-06 08:40:01 -0800778 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700779 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000780 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700781 return BAD_VALUE;
782 }
783
Eric Laurent93575202011-01-18 18:39:02 -0800784 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700785 mStreamTypes[stream].mute = muted;
786 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
787 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
788
789 return NO_ERROR;
790}
791
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800792float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700793{
Glenn Kasten263709e2012-01-06 08:40:01 -0800794 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700795 return 0.0f;
796 }
797
798 AutoMutex lock(mLock);
799 float volume;
800 if (output) {
801 PlaybackThread *thread = checkPlaybackThread_l(output);
802 if (thread == NULL) {
803 return 0.0f;
804 }
805 volume = thread->streamVolume(stream);
806 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800807 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700808 }
809
810 return volume;
811}
812
Glenn Kastenfff6d712012-01-12 16:38:12 -0800813bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814{
Glenn Kasten263709e2012-01-06 08:40:01 -0800815 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700816 return true;
817 }
818
Glenn Kasten6637baa2012-01-09 09:40:36 -0800819 AutoMutex lock(mLock);
820 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821}
822
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800823status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700824{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800825 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700826 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
827 // check calling permissions
828 if (!settingsAllowed()) {
829 return PERMISSION_DENIED;
830 }
831
Mathias Agopian65ab4712010-07-14 17:59:35 -0700832 // ioHandle == 0 means the parameters are global to the audio hardware interface
833 if (ioHandle == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700834 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800835 {
836 AutoMutex lock(mHardwareLock);
837 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700838 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
839 audio_hw_device_t *dev = mAudioHwDevs[i];
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800840 status_t result = dev->set_parameters(dev, keyValuePairs.string());
Dima Zavin799a70e2011-04-18 16:57:27 -0700841 final_result = result ?: final_result;
842 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700843 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800844 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700845 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
846 AudioParameter param = AudioParameter(keyValuePairs);
847 String8 value;
848 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
849 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700850 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
851 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700852 for (size_t i = 0; i < mRecordThreads.size(); i++) {
853 sp<RecordThread> thread = mRecordThreads.valueAt(i);
854 RecordThread::RecordTrack *track = thread->track();
855 if (track != NULL) {
856 audio_devices_t device = (audio_devices_t)(
857 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700858 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700859 thread->setEffectSuspended(FX_IID_AEC,
860 suspend,
861 track->sessionId());
862 thread->setEffectSuspended(FX_IID_NS,
863 suspend,
864 track->sessionId());
865 }
866 }
Eric Laurentbee53372011-08-29 12:42:48 -0700867 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700868 }
869 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700870 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700871 }
872
873 // hold a strong ref on thread in case closeOutput() or closeInput() is called
874 // and the thread is exited once the lock is released
875 sp<ThreadBase> thread;
876 {
877 Mutex::Autolock _l(mLock);
878 thread = checkPlaybackThread_l(ioHandle);
879 if (thread == NULL) {
880 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800881 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700882 // indicate output device change to all input threads for pre processing
883 AudioParameter param = AudioParameter(keyValuePairs);
884 int value;
885 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
886 for (size_t i = 0; i < mRecordThreads.size(); i++) {
887 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
888 }
889 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700890 }
891 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800892 if (thread != 0) {
893 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700894 }
895 return BAD_VALUE;
896}
897
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800898String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700899{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800900// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700901// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
902
903 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700904 String8 out_s8;
905
Dima Zavin799a70e2011-04-18 16:57:27 -0700906 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800907 char *s;
908 {
909 AutoMutex lock(mHardwareLock);
910 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700911 audio_hw_device_t *dev = mAudioHwDevs[i];
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800912 s = dev->get_parameters(dev, keys.string());
913 mHardwareStatus = AUDIO_HW_IDLE;
914 }
John Grossmanef7740b2012-02-09 11:28:36 -0800915 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700916 free(s);
917 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700918 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700919 }
920
921 Mutex::Autolock _l(mLock);
922
923 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
924 if (playbackThread != NULL) {
925 return playbackThread->getParameters(keys);
926 }
927 RecordThread *recordThread = checkRecordThread_l(ioHandle);
928 if (recordThread != NULL) {
929 return recordThread->getParameters(keys);
930 }
931 return String8("");
932}
933
Glenn Kastenf587ba52012-01-26 16:25:10 -0800934size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700935{
Eric Laurenta1884f92011-08-23 08:25:03 -0700936 status_t ret = initCheck();
937 if (ret != NO_ERROR) {
938 return 0;
939 }
940
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800941 AutoMutex lock(mHardwareLock);
942 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
943 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
944 mHardwareStatus = AUDIO_HW_IDLE;
945 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700946}
947
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800948unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700949{
950 if (ioHandle == 0) {
951 return 0;
952 }
953
954 Mutex::Autolock _l(mLock);
955
956 RecordThread *recordThread = checkRecordThread_l(ioHandle);
957 if (recordThread != NULL) {
958 return recordThread->getInputFramesLost();
959 }
960 return 0;
961}
962
963status_t AudioFlinger::setVoiceVolume(float value)
964{
Eric Laurenta1884f92011-08-23 08:25:03 -0700965 status_t ret = initCheck();
966 if (ret != NO_ERROR) {
967 return ret;
968 }
969
Mathias Agopian65ab4712010-07-14 17:59:35 -0700970 // check calling permissions
971 if (!settingsAllowed()) {
972 return PERMISSION_DENIED;
973 }
974
975 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800976 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700977 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700978 mHardwareStatus = AUDIO_HW_IDLE;
979
980 return ret;
981}
982
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800983status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
984 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700985{
986 status_t status;
987
988 Mutex::Autolock _l(mLock);
989
990 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
991 if (playbackThread != NULL) {
992 return playbackThread->getRenderPosition(halFrames, dspFrames);
993 }
994
995 return BAD_VALUE;
996}
997
998void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
999{
1000
1001 Mutex::Autolock _l(mLock);
1002
Glenn Kastenbb001922012-02-03 11:10:26 -08001003 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001004 if (mNotificationClients.indexOfKey(pid) < 0) {
1005 sp<NotificationClient> notificationClient = new NotificationClient(this,
1006 client,
1007 pid);
Steve Block3856b092011-10-20 11:56:00 +01001008 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001009
1010 mNotificationClients.add(pid, notificationClient);
1011
1012 sp<IBinder> binder = client->asBinder();
1013 binder->linkToDeath(notificationClient);
1014
1015 // the config change is always sent from playback or record threads to avoid deadlock
1016 // with AudioSystem::gLock
1017 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1018 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1019 }
1020
1021 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1022 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1023 }
1024 }
1025}
1026
1027void AudioFlinger::removeNotificationClient(pid_t pid)
1028{
1029 Mutex::Autolock _l(mLock);
1030
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001031 ssize_t index = mNotificationClients.indexOfKey(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001032 if (index >= 0) {
1033 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block3856b092011-10-20 11:56:00 +01001034 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001035 mNotificationClients.removeItem(pid);
1036 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001037
Steve Block3856b092011-10-20 11:56:00 +01001038 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001039 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001040 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001041 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001042 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +01001043 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001044 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +01001045 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001046 mAudioSessionRefs.removeAt(i);
1047 delete ref;
1048 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001049 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001050 } else {
1051 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001052 }
1053 }
1054 if (removed) {
1055 purgeStaleEffects_l();
1056 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001057}
1058
1059// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001060void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001061{
1062 size_t size = mNotificationClients.size();
1063 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001064 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1065 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001066 }
1067}
1068
1069// removeClient_l() must be called with AudioFlinger::mLock held
1070void AudioFlinger::removeClient_l(pid_t pid)
1071{
Steve Block3856b092011-10-20 11:56:00 +01001072 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001073 mClients.removeItem(pid);
1074}
1075
1076
1077// ----------------------------------------------------------------------------
1078
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001079AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1080 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001081 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001082 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001083 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
1084 // mChannelMask
1085 mChannelCount(0),
1086 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1087 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001088 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001089 mDevice(device),
1090 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001091{
1092}
1093
1094AudioFlinger::ThreadBase::~ThreadBase()
1095{
1096 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001097 // do not lock the mutex in destructor
1098 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001099 if (mPowerManager != 0) {
1100 sp<IBinder> binder = mPowerManager->asBinder();
1101 binder->unlinkToDeath(mDeathRecipient);
1102 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001103}
1104
1105void AudioFlinger::ThreadBase::exit()
1106{
Steve Block3856b092011-10-20 11:56:00 +01001107 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001108 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001109 // This lock prevents the following race in thread (uniprocessor for illustration):
1110 // if (!exitPending()) {
1111 // // context switch from here to exit()
1112 // // exit() calls requestExit(), what exitPending() observes
1113 // // exit() calls signal(), which is dropped since no waiters
1114 // // context switch back from exit() to here
1115 // mWaitWorkCV.wait(...);
1116 // // now thread is hung
1117 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001118 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001119 requestExit();
1120 mWaitWorkCV.signal();
1121 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001122 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1123 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001124 requestExitAndWait();
1125}
1126
Mathias Agopian65ab4712010-07-14 17:59:35 -07001127status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1128{
1129 status_t status;
1130
Steve Block3856b092011-10-20 11:56:00 +01001131 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001132 Mutex::Autolock _l(mLock);
1133
1134 mNewParameters.add(keyValuePairs);
1135 mWaitWorkCV.signal();
1136 // wait condition with timeout in case the thread loop has exited
1137 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001138 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001139 status = mParamStatus;
1140 mWaitWorkCV.signal();
1141 } else {
1142 status = TIMED_OUT;
1143 }
1144 return status;
1145}
1146
1147void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1148{
1149 Mutex::Autolock _l(mLock);
1150 sendConfigEvent_l(event, param);
1151}
1152
1153// sendConfigEvent_l() must be called with ThreadBase::mLock held
1154void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1155{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001156 ConfigEvent configEvent;
1157 configEvent.mEvent = event;
1158 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001159 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001160 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001161 mWaitWorkCV.signal();
1162}
1163
1164void AudioFlinger::ThreadBase::processConfigEvents()
1165{
1166 mLock.lock();
1167 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001168 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001169 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001170 mConfigEvents.removeAt(0);
1171 // release mLock before locking AudioFlinger mLock: lock order is always
1172 // AudioFlinger then ThreadBase to avoid cross deadlock
1173 mLock.unlock();
1174 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001175 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001176 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001177 mLock.lock();
1178 }
1179 mLock.unlock();
1180}
1181
1182status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1183{
1184 const size_t SIZE = 256;
1185 char buffer[SIZE];
1186 String8 result;
1187
1188 bool locked = tryLock(mLock);
1189 if (!locked) {
1190 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1191 write(fd, buffer, strlen(buffer));
1192 }
1193
1194 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1195 result.append(buffer);
1196 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1197 result.append(buffer);
1198 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1199 result.append(buffer);
1200 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1201 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001202 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1203 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001204 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1205 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001206 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001207 result.append(buffer);
1208
1209 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1210 result.append(buffer);
1211 result.append(" Index Command");
1212 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1213 snprintf(buffer, SIZE, "\n %02d ", i);
1214 result.append(buffer);
1215 result.append(mNewParameters[i]);
1216 }
1217
1218 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1219 result.append(buffer);
1220 snprintf(buffer, SIZE, " Index event param\n");
1221 result.append(buffer);
1222 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001223 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001224 result.append(buffer);
1225 }
1226 result.append("\n");
1227
1228 write(fd, result.string(), result.size());
1229
1230 if (locked) {
1231 mLock.unlock();
1232 }
1233 return NO_ERROR;
1234}
1235
Eric Laurent1d2bff02011-07-24 17:49:51 -07001236status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1237{
1238 const size_t SIZE = 256;
1239 char buffer[SIZE];
1240 String8 result;
1241
1242 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1243 write(fd, buffer, strlen(buffer));
1244
1245 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1246 sp<EffectChain> chain = mEffectChains[i];
1247 if (chain != 0) {
1248 chain->dump(fd, args);
1249 }
1250 }
1251 return NO_ERROR;
1252}
1253
Eric Laurentfeb0db62011-07-22 09:04:31 -07001254void AudioFlinger::ThreadBase::acquireWakeLock()
1255{
1256 Mutex::Autolock _l(mLock);
1257 acquireWakeLock_l();
1258}
1259
1260void AudioFlinger::ThreadBase::acquireWakeLock_l()
1261{
1262 if (mPowerManager == 0) {
1263 // use checkService() to avoid blocking if power service is not up yet
1264 sp<IBinder> binder =
1265 defaultServiceManager()->checkService(String16("power"));
1266 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001267 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001268 } else {
1269 mPowerManager = interface_cast<IPowerManager>(binder);
1270 binder->linkToDeath(mDeathRecipient);
1271 }
1272 }
1273 if (mPowerManager != 0) {
1274 sp<IBinder> binder = new BBinder();
1275 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1276 binder,
1277 String16(mName));
1278 if (status == NO_ERROR) {
1279 mWakeLockToken = binder;
1280 }
Steve Block3856b092011-10-20 11:56:00 +01001281 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001282 }
1283}
1284
1285void AudioFlinger::ThreadBase::releaseWakeLock()
1286{
1287 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001288 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001289}
1290
1291void AudioFlinger::ThreadBase::releaseWakeLock_l()
1292{
1293 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001294 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001295 if (mPowerManager != 0) {
1296 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1297 }
1298 mWakeLockToken.clear();
1299 }
1300}
1301
1302void AudioFlinger::ThreadBase::clearPowerManager()
1303{
1304 Mutex::Autolock _l(mLock);
1305 releaseWakeLock_l();
1306 mPowerManager.clear();
1307}
1308
1309void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1310{
1311 sp<ThreadBase> thread = mThread.promote();
1312 if (thread != 0) {
1313 thread->clearPowerManager();
1314 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001315 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001316}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001317
Eric Laurent59255e42011-07-27 19:49:51 -07001318void AudioFlinger::ThreadBase::setEffectSuspended(
1319 const effect_uuid_t *type, bool suspend, int sessionId)
1320{
1321 Mutex::Autolock _l(mLock);
1322 setEffectSuspended_l(type, suspend, sessionId);
1323}
1324
1325void AudioFlinger::ThreadBase::setEffectSuspended_l(
1326 const effect_uuid_t *type, bool suspend, int sessionId)
1327{
Glenn Kasten090f0192012-01-30 13:00:02 -08001328 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001329 if (chain != 0) {
1330 if (type != NULL) {
1331 chain->setEffectSuspended_l(type, suspend);
1332 } else {
1333 chain->setEffectSuspendedAll_l(suspend);
1334 }
1335 }
1336
1337 updateSuspendedSessions_l(type, suspend, sessionId);
1338}
1339
1340void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1341{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001342 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001343 if (index < 0) {
1344 return;
1345 }
1346
1347 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1348 mSuspendedSessions.editValueAt(index);
1349
1350 for (size_t i = 0; i < sessionEffects.size(); i++) {
1351 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1352 for (int j = 0; j < desc->mRefCount; j++) {
1353 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1354 chain->setEffectSuspendedAll_l(true);
1355 } else {
Steve Block3856b092011-10-20 11:56:00 +01001356 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001357 desc->mType.timeLow);
1358 chain->setEffectSuspended_l(&desc->mType, true);
1359 }
1360 }
1361 }
1362}
1363
Eric Laurent59255e42011-07-27 19:49:51 -07001364void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1365 bool suspend,
1366 int sessionId)
1367{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001368 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001369
1370 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1371
1372 if (suspend) {
1373 if (index >= 0) {
1374 sessionEffects = mSuspendedSessions.editValueAt(index);
1375 } else {
1376 mSuspendedSessions.add(sessionId, sessionEffects);
1377 }
1378 } else {
1379 if (index < 0) {
1380 return;
1381 }
1382 sessionEffects = mSuspendedSessions.editValueAt(index);
1383 }
1384
1385
1386 int key = EffectChain::kKeyForSuspendAll;
1387 if (type != NULL) {
1388 key = type->timeLow;
1389 }
1390 index = sessionEffects.indexOfKey(key);
1391
1392 sp <SuspendedSessionDesc> desc;
1393 if (suspend) {
1394 if (index >= 0) {
1395 desc = sessionEffects.valueAt(index);
1396 } else {
1397 desc = new SuspendedSessionDesc();
1398 if (type != NULL) {
1399 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1400 }
1401 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001402 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001403 }
1404 desc->mRefCount++;
1405 } else {
1406 if (index < 0) {
1407 return;
1408 }
1409 desc = sessionEffects.valueAt(index);
1410 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001411 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001412 sessionEffects.removeItemsAt(index);
1413 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001414 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001415 sessionId);
1416 mSuspendedSessions.removeItem(sessionId);
1417 }
1418 }
1419 }
1420 if (!sessionEffects.isEmpty()) {
1421 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1422 }
1423}
1424
1425void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1426 bool enabled,
1427 int sessionId)
1428{
1429 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001430 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1431}
Eric Laurent59255e42011-07-27 19:49:51 -07001432
Eric Laurenta85a74a2011-10-19 11:44:54 -07001433void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1434 bool enabled,
1435 int sessionId)
1436{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001437 if (mType != RECORD) {
1438 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1439 // another session. This gives the priority to well behaved effect control panels
1440 // and applications not using global effects.
1441 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1442 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1443 }
1444 }
Eric Laurent59255e42011-07-27 19:49:51 -07001445
1446 sp<EffectChain> chain = getEffectChain_l(sessionId);
1447 if (chain != 0) {
1448 chain->checkSuspendOnEffectEnabled(effect, enabled);
1449 }
1450}
1451
Mathias Agopian65ab4712010-07-14 17:59:35 -07001452// ----------------------------------------------------------------------------
1453
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001454AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1455 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001456 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001457 uint32_t device,
1458 type_t type)
1459 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001460 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1461 // Assumes constructor is called by AudioFlinger with it's mLock held,
1462 // but it would be safer to explicitly pass initial masterMute as parameter
1463 mMasterMute(audioFlinger->masterMute_l()),
1464 // mStreamTypes[] initialized in constructor body
1465 mOutput(output),
1466 // Assumes constructor is called by AudioFlinger with it's mLock held,
1467 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001468 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001469 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001470{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001471 snprintf(mName, kNameLength, "AudioOut_%d", id);
1472
Mathias Agopian65ab4712010-07-14 17:59:35 -07001473 readOutputParameters();
1474
Glenn Kasten263709e2012-01-06 08:40:01 -08001475 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001476 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1477 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1478 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001479 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1480 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001481 // initialized by stream_type_t default constructor
1482 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001483 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001484 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1485 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001486}
1487
1488AudioFlinger::PlaybackThread::~PlaybackThread()
1489{
1490 delete [] mMixBuffer;
1491}
1492
1493status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1494{
1495 dumpInternals(fd, args);
1496 dumpTracks(fd, args);
1497 dumpEffectChains(fd, args);
1498 return NO_ERROR;
1499}
1500
1501status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1502{
1503 const size_t SIZE = 256;
1504 char buffer[SIZE];
1505 String8 result;
1506
1507 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1508 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001509 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001510 for (size_t i = 0; i < mTracks.size(); ++i) {
1511 sp<Track> track = mTracks[i];
1512 if (track != 0) {
1513 track->dump(buffer, SIZE);
1514 result.append(buffer);
1515 }
1516 }
1517
1518 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1519 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001520 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001521 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001522 sp<Track> track = mActiveTracks[i].promote();
1523 if (track != 0) {
1524 track->dump(buffer, SIZE);
1525 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001526 }
1527 }
1528 write(fd, result.string(), result.size());
1529 return NO_ERROR;
1530}
1531
Mathias Agopian65ab4712010-07-14 17:59:35 -07001532status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1533{
1534 const size_t SIZE = 256;
1535 char buffer[SIZE];
1536 String8 result;
1537
1538 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1539 result.append(buffer);
1540 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1541 result.append(buffer);
1542 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1543 result.append(buffer);
1544 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1545 result.append(buffer);
1546 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1547 result.append(buffer);
1548 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1549 result.append(buffer);
1550 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1551 result.append(buffer);
1552 write(fd, result.string(), result.size());
1553
1554 dumpBase(fd, args);
1555
1556 return NO_ERROR;
1557}
1558
1559// Thread virtuals
1560status_t AudioFlinger::PlaybackThread::readyToRun()
1561{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001562 status_t status = initCheck();
1563 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001564 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001565 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001566 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001567 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001568 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001569}
1570
1571void AudioFlinger::PlaybackThread::onFirstRef()
1572{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001573 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001574}
1575
1576// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1577sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1578 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001579 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001580 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001581 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001582 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001583 int frameCount,
1584 const sp<IMemory>& sharedBuffer,
1585 int sessionId,
John Grossman4ff14ba2012-02-08 16:37:41 -08001586 bool isTimed,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001587 status_t *status)
1588{
1589 sp<Track> track;
1590 status_t lStatus;
1591
1592 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001593 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1594 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001595 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001596 "for output %p with format %d",
1597 sampleRate, format, channelMask, mOutput, mFormat);
1598 lStatus = BAD_VALUE;
1599 goto Exit;
1600 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001601 }
1602 } else {
1603 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1604 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001605 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001606 lStatus = BAD_VALUE;
1607 goto Exit;
1608 }
1609 }
1610
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001611 lStatus = initCheck();
1612 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001613 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001614 goto Exit;
1615 }
1616
1617 { // scope for mLock
1618 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001619
1620 // all tracks in same audio session must share the same routing strategy otherwise
1621 // conflicts will happen when tracks are moved from one output to another by audio policy
1622 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001623 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001624 for (size_t i = 0; i < mTracks.size(); ++i) {
1625 sp<Track> t = mTracks[i];
1626 if (t != 0) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001627 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001628 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001629 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001630 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001631 lStatus = BAD_VALUE;
1632 goto Exit;
1633 }
1634 }
1635 }
1636
John Grossman4ff14ba2012-02-08 16:37:41 -08001637 if (!isTimed) {
1638 track = new Track(this, client, streamType, sampleRate, format,
1639 channelMask, frameCount, sharedBuffer, sessionId);
1640 } else {
1641 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1642 channelMask, frameCount, sharedBuffer, sessionId);
1643 }
1644 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001645 lStatus = NO_MEMORY;
1646 goto Exit;
1647 }
1648 mTracks.add(track);
1649
1650 sp<EffectChain> chain = getEffectChain_l(sessionId);
1651 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001652 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001653 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001654 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001655 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001656 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001657
1658 // invalidate track immediately if the stream type was moved to another thread since
1659 // createTrack() was called by the client process.
1660 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001661 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001662 this, streamType);
1663 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1664 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001665 }
1666 lStatus = NO_ERROR;
1667
1668Exit:
1669 if(status) {
1670 *status = lStatus;
1671 }
1672 return track;
1673}
1674
1675uint32_t AudioFlinger::PlaybackThread::latency() const
1676{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001677 Mutex::Autolock _l(mLock);
1678 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001679 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001680 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001681 return 0;
1682 }
1683}
1684
Glenn Kasten6637baa2012-01-09 09:40:36 -08001685void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001686{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001687 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001688 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001689}
1690
Glenn Kasten6637baa2012-01-09 09:40:36 -08001691void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001692{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001693 Mutex::Autolock _l(mLock);
1694 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695}
1696
Glenn Kasten6637baa2012-01-09 09:40:36 -08001697void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001698{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001699 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001700 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001701}
1702
Glenn Kasten6637baa2012-01-09 09:40:36 -08001703void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001704{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001705 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001706 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001707}
1708
Glenn Kastenfff6d712012-01-12 16:38:12 -08001709float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001710{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001711 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001712 return mStreamTypes[stream].volume;
1713}
1714
Mathias Agopian65ab4712010-07-14 17:59:35 -07001715// addTrack_l() must be called with ThreadBase::mLock held
1716status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1717{
1718 status_t status = ALREADY_EXISTS;
1719
1720 // set retry count for buffer fill
1721 track->mRetryCount = kMaxTrackStartupRetries;
1722 if (mActiveTracks.indexOf(track) < 0) {
1723 // the track is newly added, make sure it fills up all its
1724 // buffers before playing. This is to ensure the client will
1725 // effectively get the latency it requested.
1726 track->mFillingUpStatus = Track::FS_FILLING;
1727 track->mResetDone = false;
1728 mActiveTracks.add(track);
1729 if (track->mainBuffer() != mMixBuffer) {
1730 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1731 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001732 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001733 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001734 }
1735 }
1736
1737 status = NO_ERROR;
1738 }
1739
Steve Block3856b092011-10-20 11:56:00 +01001740 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001741 mWaitWorkCV.broadcast();
1742
1743 return status;
1744}
1745
1746// destroyTrack_l() must be called with ThreadBase::mLock held
1747void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1748{
1749 track->mState = TrackBase::TERMINATED;
1750 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001751 removeTrack_l(track);
1752 }
1753}
1754
1755void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1756{
1757 mTracks.remove(track);
1758 deleteTrackName_l(track->name());
1759 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1760 if (chain != 0) {
1761 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001762 }
1763}
1764
1765String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1766{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001767 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001768 char *s;
1769
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001770 Mutex::Autolock _l(mLock);
1771 if (initCheck() != NO_ERROR) {
1772 return out_s8;
1773 }
1774
Dima Zavin799a70e2011-04-18 16:57:27 -07001775 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001776 out_s8 = String8(s);
1777 free(s);
1778 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001779}
1780
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001781// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001782void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1783 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001784 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001785
Steve Block3856b092011-10-20 11:56:00 +01001786 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001787
1788 switch (event) {
1789 case AudioSystem::OUTPUT_OPENED:
1790 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001791 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001792 desc.samplingRate = mSampleRate;
1793 desc.format = mFormat;
1794 desc.frameCount = mFrameCount;
1795 desc.latency = latency();
1796 param2 = &desc;
1797 break;
1798
1799 case AudioSystem::STREAM_CONFIG_CHANGED:
1800 param2 = &param;
1801 case AudioSystem::OUTPUT_CLOSED:
1802 default:
1803 break;
1804 }
1805 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1806}
1807
1808void AudioFlinger::PlaybackThread::readOutputParameters()
1809{
Dima Zavin799a70e2011-04-18 16:57:27 -07001810 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001811 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1812 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001813 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001814 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001815 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001816
1817 // FIXME - Current mixer implementation only supports stereo output: Always
1818 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001819 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001820 mMixBuffer = new int16_t[mFrameCount * 2];
1821 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1822
Eric Laurentde070132010-07-13 04:45:46 -07001823 // force reconfiguration of effect chains and engines to take new buffer size and audio
1824 // parameters into account
1825 // Note that mLock is not held when readOutputParameters() is called from the constructor
1826 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1827 // matter.
1828 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1829 Vector< sp<EffectChain> > effectChains = mEffectChains;
1830 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001831 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001832 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833}
1834
1835status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1836{
Glenn Kastena0d68332012-01-27 16:47:15 -08001837 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001838 return BAD_VALUE;
1839 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001840 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001841 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001842 return INVALID_OPERATION;
1843 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001844 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001845
Dima Zavin799a70e2011-04-18 16:57:27 -07001846 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001847}
1848
Eric Laurent39e94f82010-07-28 01:32:47 -07001849uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001850{
1851 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001852 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001854 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001855 }
1856
1857 for (size_t i = 0; i < mTracks.size(); ++i) {
1858 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001859 if (sessionId == track->sessionId() &&
1860 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001861 result |= TRACK_SESSION;
1862 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001863 }
1864 }
1865
Eric Laurent39e94f82010-07-28 01:32:47 -07001866 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001867}
1868
Eric Laurentde070132010-07-13 04:45:46 -07001869uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1870{
Dima Zavinfce7a472011-04-19 22:30:36 -07001871 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001872 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001873 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1874 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001875 }
1876 for (size_t i = 0; i < mTracks.size(); i++) {
1877 sp<Track> track = mTracks[i];
1878 if (sessionId == track->sessionId() &&
1879 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001880 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07001881 }
1882 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001883 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001884}
1885
Mathias Agopian65ab4712010-07-14 17:59:35 -07001886
Glenn Kastenaed850d2012-01-26 09:46:34 -08001887AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001888{
1889 Mutex::Autolock _l(mLock);
1890 return mOutput;
1891}
1892
1893AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1894{
1895 Mutex::Autolock _l(mLock);
1896 AudioStreamOut *output = mOutput;
1897 mOutput = NULL;
1898 return output;
1899}
1900
1901// this method must always be called either with ThreadBase mLock held or inside the thread loop
1902audio_stream_t* AudioFlinger::PlaybackThread::stream()
1903{
1904 if (mOutput == NULL) {
1905 return NULL;
1906 }
1907 return &mOutput->stream->common;
1908}
1909
Eric Laurent162b40b2011-12-05 09:47:19 -08001910uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1911{
1912 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1913 // decoding and transfer time. So sleeping for half of the latency would likely cause
1914 // underruns
1915 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1916 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1917 } else {
1918 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1919 }
1920}
1921
Mathias Agopian65ab4712010-07-14 17:59:35 -07001922// ----------------------------------------------------------------------------
1923
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001924AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001925 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001926 : PlaybackThread(audioFlinger, output, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001927 mAudioMixer(new AudioMixer(mFrameCount, mSampleRate)),
1928 mPrevMixerStatus(MIXER_IDLE)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001929{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001930 // FIXME - Current mixer implementation only supports stereo output
1931 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001932 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001933 }
1934}
1935
1936AudioFlinger::MixerThread::~MixerThread()
1937{
1938 delete mAudioMixer;
1939}
1940
1941bool AudioFlinger::MixerThread::threadLoop()
1942{
1943 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08001944 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001945 nsecs_t standbyTime = systemTime();
1946 size_t mixBufferSize = mFrameCount * mFrameSize;
1947 // FIXME: Relaxed timing because of a certain device that can't meet latency
1948 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001949 // increase threshold again due to low power audio mode. The way this warning threshold is
1950 // calculated and its usefulness should be reconsidered anyway.
1951 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001952 nsecs_t lastWarning = 0;
1953 bool longStandbyExit = false;
1954 uint32_t activeSleepTime = activeSleepTimeUs();
1955 uint32_t idleSleepTime = idleSleepTimeUs();
1956 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001957 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001958 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001959#ifdef DEBUG_CPU_USAGE
1960 ThreadCpuUsage cpu;
1961 const CentralTendencyStatistics& stats = cpu.statistics();
1962#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001963
Eric Laurentfeb0db62011-07-22 09:04:31 -07001964 acquireWakeLock();
1965
Mathias Agopian65ab4712010-07-14 17:59:35 -07001966 while (!exitPending())
1967 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001968#ifdef DEBUG_CPU_USAGE
1969 cpu.sampleAndEnable();
1970 unsigned n = stats.n();
1971 // cpu.elapsed() is expensive, so don't call it every loop
1972 if ((n & 127) == 1) {
1973 long long elapsed = cpu.elapsed();
1974 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1975 double perLoop = elapsed / (double) n;
1976 double perLoop100 = perLoop * 0.01;
1977 double mean = stats.mean();
1978 double stddev = stats.stddev();
1979 double minimum = stats.minimum();
1980 double maximum = stats.maximum();
1981 cpu.resetStatistics();
Steve Blockdf64d152012-01-04 20:05:49 +00001982 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",
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001983 elapsed * .000000001, n, perLoop * .000001,
1984 mean * .001,
1985 stddev * .001,
1986 minimum * .001,
1987 maximum * .001,
1988 mean / perLoop100,
1989 stddev / perLoop100,
1990 minimum / perLoop100,
1991 maximum / perLoop100);
1992 }
1993 }
1994#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001995 processConfigEvents();
1996
1997 mixerStatus = MIXER_IDLE;
1998 { // scope for mLock
1999
2000 Mutex::Autolock _l(mLock);
2001
2002 if (checkForNewParameters_l()) {
2003 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
2007 // threshold is calculated and its usefulness should be reconsidered anyway.
2008 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002009 activeSleepTime = activeSleepTimeUs();
2010 idleSleepTime = idleSleepTimeUs();
2011 }
2012
2013 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2014
2015 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002016 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2017 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002018 if (!mStandby) {
Glenn Kasten90bebef2012-01-27 15:24:38 -08002019 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07002020 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002021 mStandby = true;
2022 mBytesWritten = 0;
2023 }
2024
2025 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2026 // we're about to wait, flush the binder command buffer
2027 IPCThreadState::self()->flushCommands();
2028
2029 if (exitPending()) break;
2030
Eric Laurentfeb0db62011-07-22 09:04:31 -07002031 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002032 // wait until we have something to do...
Glenn Kasten90bebef2012-01-27 15:24:38 -08002033 ALOGV("MixerThread %p TID %d going to sleep", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002034 mWaitWorkCV.wait(mLock);
Glenn Kasten90bebef2012-01-27 15:24:38 -08002035 ALOGV("MixerThread %p TID %d waking up", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002036 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002037
Eric Laurent27741442012-01-17 19:20:12 -08002038 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08002039 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002040 char value[PROPERTY_VALUE_MAX];
2041 property_get("ro.audio.silent", value, "0");
2042 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002043 ALOGD("Silence is golden");
Glenn Kasten6637baa2012-01-09 09:40:36 -08002044 setMasterMute_l(true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002045 }
2046 }
2047
John Grossman4ff14ba2012-02-08 16:37:41 -08002048 standbyTime = systemTime() + mStandbyTimeInNsecs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002049 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08002050 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002051 continue;
2052 }
2053 }
2054
2055 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
2056
2057 // prevent any changes in effect chain list and in each effect chain
2058 // during mixing and effect process as the audio buffers could be deleted
2059 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002060 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002061 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002062
Glenn Kastenf6b16782011-12-15 09:51:17 -08002063 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08002064 // obtain the presentation timestamp of the next output buffer
2065 int64_t pts;
2066 status_t status = INVALID_OPERATION;
2067
2068 if (NULL != mOutput->stream->get_next_write_timestamp) {
2069 status = mOutput->stream->get_next_write_timestamp(
2070 mOutput->stream, &pts);
2071 }
2072
2073 if (status != NO_ERROR) {
2074 pts = AudioBufferProvider::kInvalidPTS;
2075 }
2076
Mathias Agopian65ab4712010-07-14 17:59:35 -07002077 // mix buffers...
John Grossman4ff14ba2012-02-08 16:37:41 -08002078 mAudioMixer->process(pts);
Eric Laurent21e4b6e2012-01-23 18:56:59 -08002079 // increase sleep time progressively when application underrun condition clears.
2080 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2081 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2082 // such that we would underrun the audio HAL.
2083 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08002084 sleepTimeShift--;
2085 }
Eric Laurent21e4b6e2012-01-23 18:56:59 -08002086 sleepTime = 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08002087 standbyTime = systemTime() + mStandbyTimeInNsecs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002088 //TODO: delay standby when effects have a tail
2089 } else {
2090 // If no tracks are ready, sleep once for the duration of an output
2091 // buffer size, then write 0s to the output
2092 if (sleepTime == 0) {
2093 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08002094 sleepTime = activeSleepTime >> sleepTimeShift;
2095 if (sleepTime < kMinThreadSleepTimeUs) {
2096 sleepTime = kMinThreadSleepTimeUs;
2097 }
2098 // reduce sleep time in case of consecutive application underruns to avoid
2099 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2100 // duration we would end up writing less data than needed by the audio HAL if
2101 // the condition persists.
2102 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2103 sleepTimeShift++;
2104 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002105 } else {
2106 sleepTime = idleSleepTime;
2107 }
2108 } else if (mBytesWritten != 0 ||
2109 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2110 memset (mMixBuffer, 0, mixBufferSize);
2111 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01002112 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002113 }
2114 // TODO add standby time extension fct of effect tail
2115 }
2116
2117 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002118 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002119 }
2120 // sleepTime == 0 means we must write to audio hardware
2121 if (sleepTime == 0) {
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002122 for (size_t i = 0; i < effectChains.size(); i ++) {
2123 effectChains[i]->process_l();
2124 }
2125 // enable changes in effect chain
2126 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002127 mLastWriteTime = systemTime();
2128 mInWrite = true;
2129 mBytesWritten += mixBufferSize;
2130
Dima Zavin799a70e2011-04-18 16:57:27 -07002131 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002132 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2133 mNumWrites++;
2134 mInWrite = false;
2135 nsecs_t now = systemTime();
2136 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002137 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002138 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002139 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002140 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002141 ns2ms(delta), mNumDelayedWrites, this);
2142 lastWarning = now;
2143 }
2144 if (mStandby) {
2145 longStandbyExit = true;
2146 }
2147 }
2148 mStandby = false;
2149 } else {
2150 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002151 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002152 usleep(sleepTime);
2153 }
2154
2155 // finally let go of all our tracks, without the lock held
2156 // since we can't guarantee the destructors won't acquire that
2157 // same lock.
2158 tracksToRemove.clear();
2159
2160 // Effect chains will be actually deleted here if they were removed from
2161 // mEffectChains list during mixing or effects processing
2162 effectChains.clear();
2163 }
2164
2165 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002166 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002167 }
2168
Eric Laurentfeb0db62011-07-22 09:04:31 -07002169 releaseWakeLock();
2170
Steve Block3856b092011-10-20 11:56:00 +01002171 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002172 return false;
2173}
2174
2175// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002176AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2177 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002178{
2179
Glenn Kasten29c23c32012-01-26 13:37:52 -08002180 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002181 // find out which tracks need to be processed
2182 size_t count = activeTracks.size();
2183 size_t mixedTracks = 0;
2184 size_t tracksWithEffect = 0;
2185
2186 float masterVolume = mMasterVolume;
2187 bool masterMute = mMasterMute;
2188
Eric Laurent571d49c2010-08-11 05:20:11 -07002189 if (masterMute) {
2190 masterVolume = 0;
2191 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002192 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002193 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002194 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002195 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002196 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002197 masterVolume = (float)((v + (1 << 23)) >> 24);
2198 chain.clear();
2199 }
2200
2201 for (size_t i=0 ; i<count ; i++) {
2202 sp<Track> t = activeTracks[i].promote();
2203 if (t == 0) continue;
2204
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002205 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002206 Track* const track = t.get();
2207 audio_track_cblk_t* cblk = track->cblk();
2208
2209 // The first time a track is added we wait
2210 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002211 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002212 // make sure that we have enough frames to mix one full buffer.
2213 // enforce this condition only once to enable draining the buffer in case the client
2214 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002215 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002216 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002217 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002218 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002219 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002220 if (t->sampleRate() == (int)mSampleRate) {
2221 minFrames = mFrameCount;
2222 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002223 // +1 for rounding and +1 for additional sample needed for interpolation
2224 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2225 // add frames already consumed but not yet released by the resampler
2226 // because cblk->framesReady() will include these frames
2227 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2228 // the minimum track buffer size is normally twice the number of frames necessary
2229 // to fill one buffer and the resampler should not leave more than one buffer worth
2230 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002231 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002232 }
2233 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002234 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002235 !track->isPaused() && !track->isTerminated())
2236 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002237 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002238
2239 mixedTracks++;
2240
2241 // track->mainBuffer() != mMixBuffer means there is an effect chain
2242 // connected to the track
2243 chain.clear();
2244 if (track->mainBuffer() != mMixBuffer) {
2245 chain = getEffectChain_l(track->sessionId());
2246 // Delegate volume control to effect in track effect chain if needed
2247 if (chain != 0) {
2248 tracksWithEffect++;
2249 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002250 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002251 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002252 }
2253 }
2254
2255
2256 int param = AudioMixer::VOLUME;
2257 if (track->mFillingUpStatus == Track::FS_FILLED) {
2258 // no ramp for the first volume setting
2259 track->mFillingUpStatus = Track::FS_ACTIVE;
2260 if (track->mState == TrackBase::RESUMING) {
2261 track->mState = TrackBase::ACTIVE;
2262 param = AudioMixer::RAMP_VOLUME;
2263 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002264 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002265 } else if (cblk->server != 0) {
2266 // If the track is stopped before the first frame was mixed,
2267 // do not apply ramp
2268 param = AudioMixer::RAMP_VOLUME;
2269 }
2270
2271 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002272 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002273 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002274 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002275 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002276 if (track->isPausing()) {
2277 track->setPaused();
2278 }
2279 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002280
Mathias Agopian65ab4712010-07-14 17:59:35 -07002281 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002282 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002283 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002284 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002285 vl = vlr & 0xFFFF;
2286 vr = vlr >> 16;
2287 // track volumes come from shared memory, so can't be trusted and must be clamped
2288 if (vl > MAX_GAIN_INT) {
2289 ALOGV("Track left volume out of range: %04X", vl);
2290 vl = MAX_GAIN_INT;
2291 }
2292 if (vr > MAX_GAIN_INT) {
2293 ALOGV("Track right volume out of range: %04X", vr);
2294 vr = MAX_GAIN_INT;
2295 }
2296 // now apply the master volume and stream type volume
2297 vl = (uint32_t)(v * vl) << 12;
2298 vr = (uint32_t)(v * vr) << 12;
2299 // assuming master volume and stream type volume each go up to 1.0,
2300 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002301
Glenn Kasten05632a52012-01-03 14:22:33 -08002302 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2303 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002304 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002305 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002306 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002307 }
2308 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002309 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002310 // Delegate volume control to effect in track effect chain if needed
2311 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2312 // Do not ramp volume if volume is controlled by effect
2313 param = AudioMixer::VOLUME;
2314 track->mHasVolumeController = true;
2315 } else {
2316 // force no volume ramp when volume controller was just disabled or removed
2317 // from effect chain to avoid volume spike
2318 if (track->mHasVolumeController) {
2319 param = AudioMixer::VOLUME;
2320 }
2321 track->mHasVolumeController = false;
2322 }
2323
2324 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002325 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002326 vl = (vl + (1 << 11)) >> 12;
2327 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2328 vr = (vr + (1 << 11)) >> 12;
2329 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002330
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002331 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 -07002332
Mathias Agopian65ab4712010-07-14 17:59:35 -07002333 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002334 mAudioMixer->setBufferProvider(name, track);
2335 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002336
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002337 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2338 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2339 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002340 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002341 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002342 AudioMixer::TRACK,
2343 AudioMixer::FORMAT, (void *)track->format());
2344 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002345 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002346 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002347 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002348 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002349 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002350 AudioMixer::RESAMPLE,
2351 AudioMixer::SAMPLE_RATE,
2352 (void *)(cblk->sampleRate));
2353 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002354 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002355 AudioMixer::TRACK,
2356 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2357 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002358 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002359 AudioMixer::TRACK,
2360 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2361
2362 // reset retry count
2363 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002364 // If one track is ready, set the mixer ready if:
2365 // - the mixer was not ready during previous round OR
2366 // - no other track is not ready
2367 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2368 mixerStatus != MIXER_TRACKS_ENABLED) {
2369 mixerStatus = MIXER_TRACKS_READY;
2370 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002371 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002372 //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 -07002373 if (track->isStopped()) {
2374 track->reset();
2375 }
2376 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2377 // We have consumed all the buffers of this track.
2378 // Remove it from the list of active tracks.
2379 tracksToRemove->add(track);
2380 } else {
2381 // No buffers for this track. Give it a few chances to
2382 // fill a buffer, then remove it from active list.
2383 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002384 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002385 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002386 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002387 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002388 // If one track is not ready, mark the mixer also not ready if:
2389 // - the mixer was ready during previous round OR
2390 // - no other track is ready
2391 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2392 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002393 mixerStatus = MIXER_TRACKS_ENABLED;
2394 }
2395 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002396 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002397 }
2398 }
2399
2400 // remove all the tracks that need to be...
2401 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002402 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002403 for (size_t i=0 ; i<count ; i++) {
2404 const sp<Track>& track = tracksToRemove->itemAt(i);
2405 mActiveTracks.remove(track);
2406 if (track->mainBuffer() != mMixBuffer) {
2407 chain = getEffectChain_l(track->sessionId());
2408 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002409 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002410 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002411 }
2412 }
2413 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002414 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002415 }
2416 }
2417 }
2418
2419 // mix buffer must be cleared if all tracks are connected to an
2420 // effect chain as in this case the mixer will not write to
2421 // mix buffer and track effects will accumulate into it
2422 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2423 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2424 }
2425
Eric Laurent27741442012-01-17 19:20:12 -08002426 mPrevMixerStatus = mixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002427 return mixerStatus;
2428}
2429
Glenn Kastenfff6d712012-01-12 16:38:12 -08002430void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002431{
Steve Block3856b092011-10-20 11:56:00 +01002432 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002433 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002434 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002435
Mathias Agopian65ab4712010-07-14 17:59:35 -07002436 size_t size = mTracks.size();
2437 for (size_t i = 0; i < size; i++) {
2438 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08002439 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002440 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002441 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002442 }
2443 }
2444}
2445
Glenn Kastenfff6d712012-01-12 16:38:12 -08002446void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002447{
Steve Block3856b092011-10-20 11:56:00 +01002448 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002449 this, streamType, valid);
2450 Mutex::Autolock _l(mLock);
2451
2452 mStreamTypes[streamType].valid = valid;
2453}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002454
2455// getTrackName_l() must be called with ThreadBase::mLock held
2456int AudioFlinger::MixerThread::getTrackName_l()
2457{
2458 return mAudioMixer->getTrackName();
2459}
2460
2461// deleteTrackName_l() must be called with ThreadBase::mLock held
2462void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2463{
Steve Block3856b092011-10-20 11:56:00 +01002464 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002465 mAudioMixer->deleteTrackName(name);
2466}
2467
2468// checkForNewParameters_l() must be called with ThreadBase::mLock held
2469bool AudioFlinger::MixerThread::checkForNewParameters_l()
2470{
2471 bool reconfig = false;
2472
2473 while (!mNewParameters.isEmpty()) {
2474 status_t status = NO_ERROR;
2475 String8 keyValuePair = mNewParameters[0];
2476 AudioParameter param = AudioParameter(keyValuePair);
2477 int value;
2478
2479 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2480 reconfig = true;
2481 }
2482 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002483 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002484 status = BAD_VALUE;
2485 } else {
2486 reconfig = true;
2487 }
2488 }
2489 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002490 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002491 status = BAD_VALUE;
2492 } else {
2493 reconfig = true;
2494 }
2495 }
2496 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2497 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002498 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002499 // if frame count is changed after track creation
2500 if (!mTracks.isEmpty()) {
2501 status = INVALID_OPERATION;
2502 } else {
2503 reconfig = true;
2504 }
2505 }
2506 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002507 // when changing the audio output device, call addBatteryData to notify
2508 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002509 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002510 uint32_t params = 0;
2511 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002512 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002513 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2514 }
2515
2516 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002517 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002518 // check if any other device (except speaker) is on
2519 if (value & deviceWithoutSpeaker ) {
2520 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2521 }
2522
2523 if (params != 0) {
2524 addBatteryData(params);
2525 }
2526 }
2527
Mathias Agopian65ab4712010-07-14 17:59:35 -07002528 // forward device change to effects that have requested to be
2529 // aware of attached audio device.
2530 mDevice = (uint32_t)value;
2531 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002532 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002533 }
2534 }
2535
2536 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002537 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002538 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002539 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002540 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002541 mStandby = true;
2542 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002543 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002544 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002545 }
2546 if (status == NO_ERROR && reconfig) {
2547 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002548 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2549 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002550 readOutputParameters();
2551 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2552 for (size_t i = 0; i < mTracks.size() ; i++) {
2553 int name = getTrackName_l();
2554 if (name < 0) break;
2555 mTracks[i]->mName = name;
2556 // limit track sample rate to 2 x new output sample rate
2557 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2558 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2559 }
2560 }
2561 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2562 }
2563 }
2564
2565 mNewParameters.removeAt(0);
2566
2567 mParamStatus = status;
2568 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002569 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2570 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002571 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002572 }
2573 return reconfig;
2574}
2575
2576status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2577{
2578 const size_t SIZE = 256;
2579 char buffer[SIZE];
2580 String8 result;
2581
2582 PlaybackThread::dumpInternals(fd, args);
2583
2584 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2585 result.append(buffer);
2586 write(fd, result.string(), result.size());
2587 return NO_ERROR;
2588}
2589
Mathias Agopian65ab4712010-07-14 17:59:35 -07002590uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2591{
Eric Laurent60e18242010-07-29 06:50:24 -07002592 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002593}
2594
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002595uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2596{
2597 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2598}
2599
Mathias Agopian65ab4712010-07-14 17:59:35 -07002600// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002601AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2602 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002603 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002604 // mLeftVolFloat, mRightVolFloat
2605 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002606{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002607}
2608
2609AudioFlinger::DirectOutputThread::~DirectOutputThread()
2610{
2611}
2612
Mathias Agopian65ab4712010-07-14 17:59:35 -07002613void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2614{
2615 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002616 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002617 return;
2618 }
2619
2620 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002621 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002622 size_t count = mFrameCount * mChannelCount;
2623 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2624 int16_t *dst = mMixBuffer + count-1;
2625 while(count--) {
2626 *dst-- = (int16_t)(*src--^0x80) << 8;
2627 }
2628 }
2629
2630 size_t frameCount = mFrameCount;
2631 int16_t *out = mMixBuffer;
2632 if (ramp) {
2633 if (mChannelCount == 1) {
2634 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2635 int32_t vlInc = d / (int32_t)frameCount;
2636 int32_t vl = ((int32_t)mLeftVolShort << 16);
2637 do {
2638 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2639 out++;
2640 vl += vlInc;
2641 } while (--frameCount);
2642
2643 } else {
2644 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2645 int32_t vlInc = d / (int32_t)frameCount;
2646 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2647 int32_t vrInc = d / (int32_t)frameCount;
2648 int32_t vl = ((int32_t)mLeftVolShort << 16);
2649 int32_t vr = ((int32_t)mRightVolShort << 16);
2650 do {
2651 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2652 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2653 out += 2;
2654 vl += vlInc;
2655 vr += vrInc;
2656 } while (--frameCount);
2657 }
2658 } else {
2659 if (mChannelCount == 1) {
2660 do {
2661 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2662 out++;
2663 } while (--frameCount);
2664 } else {
2665 do {
2666 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2667 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2668 out += 2;
2669 } while (--frameCount);
2670 }
2671 }
2672
2673 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002674 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002675 size_t count = mFrameCount * mChannelCount;
2676 int16_t *src = mMixBuffer;
2677 uint8_t *dst = (uint8_t *)mMixBuffer;
2678 while(count--) {
2679 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2680 }
2681 }
2682
2683 mLeftVolShort = leftVol;
2684 mRightVolShort = rightVol;
2685}
2686
2687bool AudioFlinger::DirectOutputThread::threadLoop()
2688{
Glenn Kasten29c23c32012-01-26 13:37:52 -08002689 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002690 sp<Track> trackToRemove;
2691 sp<Track> activeTrack;
2692 nsecs_t standbyTime = systemTime();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002693 size_t mixBufferSize = mFrameCount*mFrameSize;
2694 uint32_t activeSleepTime = activeSleepTimeUs();
2695 uint32_t idleSleepTime = idleSleepTimeUs();
2696 uint32_t sleepTime = idleSleepTime;
2697 // use shorter standby delay as on normal output to release
2698 // hardware resources as soon as possible
2699 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2700
Eric Laurentfeb0db62011-07-22 09:04:31 -07002701 acquireWakeLock();
2702
Mathias Agopian65ab4712010-07-14 17:59:35 -07002703 while (!exitPending())
2704 {
2705 bool rampVolume;
2706 uint16_t leftVol;
2707 uint16_t rightVol;
2708 Vector< sp<EffectChain> > effectChains;
2709
2710 processConfigEvents();
2711
2712 mixerStatus = MIXER_IDLE;
2713
2714 { // scope for the mLock
2715
2716 Mutex::Autolock _l(mLock);
2717
2718 if (checkForNewParameters_l()) {
2719 mixBufferSize = mFrameCount*mFrameSize;
2720 activeSleepTime = activeSleepTimeUs();
2721 idleSleepTime = idleSleepTimeUs();
2722 standbyDelay = microseconds(activeSleepTime*2);
2723 }
2724
2725 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002726 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2727 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002728 // wait until we have something to do...
2729 if (!mStandby) {
Glenn Kasten90bebef2012-01-27 15:24:38 -08002730 ALOGV("Audio hardware entering standby, mixer %p", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002731 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002732 mStandby = true;
2733 mBytesWritten = 0;
2734 }
2735
2736 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2737 // we're about to wait, flush the binder command buffer
2738 IPCThreadState::self()->flushCommands();
2739
2740 if (exitPending()) break;
2741
Eric Laurentfeb0db62011-07-22 09:04:31 -07002742 releaseWakeLock_l();
Glenn Kasten90bebef2012-01-27 15:24:38 -08002743 ALOGV("DirectOutputThread %p TID %d going to sleep", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002744 mWaitWorkCV.wait(mLock);
Glenn Kasten90bebef2012-01-27 15:24:38 -08002745 ALOGV("DirectOutputThread %p TID %d waking up in active mode", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002746 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002747
Glenn Kastenf1d45922012-01-13 15:54:24 -08002748 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002749 char value[PROPERTY_VALUE_MAX];
2750 property_get("ro.audio.silent", value, "0");
2751 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002752 ALOGD("Silence is golden");
Glenn Kasten6637baa2012-01-09 09:40:36 -08002753 setMasterMute_l(true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002754 }
2755 }
2756
2757 standbyTime = systemTime() + standbyDelay;
2758 sleepTime = idleSleepTime;
2759 continue;
2760 }
2761 }
2762
2763 effectChains = mEffectChains;
2764
2765 // find out which tracks need to be processed
2766 if (mActiveTracks.size() != 0) {
2767 sp<Track> t = mActiveTracks[0].promote();
2768 if (t == 0) continue;
2769
2770 Track* const track = t.get();
2771 audio_track_cblk_t* cblk = track->cblk();
2772
2773 // The first time a track is added we wait
2774 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002775 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002776 !track->isPaused() && !track->isTerminated())
2777 {
Steve Block3856b092011-10-20 11:56:00 +01002778 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002779
2780 if (track->mFillingUpStatus == Track::FS_FILLED) {
2781 track->mFillingUpStatus = Track::FS_ACTIVE;
2782 mLeftVolFloat = mRightVolFloat = 0;
2783 mLeftVolShort = mRightVolShort = 0;
2784 if (track->mState == TrackBase::RESUMING) {
2785 track->mState = TrackBase::ACTIVE;
2786 rampVolume = true;
2787 }
2788 } else if (cblk->server != 0) {
2789 // If the track is stopped before the first frame was mixed,
2790 // do not apply ramp
2791 rampVolume = true;
2792 }
2793 // compute volume for this track
2794 float left, right;
2795 if (track->isMuted() || mMasterMute || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002796 mStreamTypes[track->streamType()].mute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002797 left = right = 0;
2798 if (track->isPausing()) {
2799 track->setPaused();
2800 }
2801 } else {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002802 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002803 float v = mMasterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002804 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002805 float v_clamped = v * (vlr & 0xFFFF);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002806 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2807 left = v_clamped/MAX_GAIN;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002808 v_clamped = v * (vlr >> 16);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002809 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2810 right = v_clamped/MAX_GAIN;
2811 }
2812
2813 if (left != mLeftVolFloat || right != mRightVolFloat) {
2814 mLeftVolFloat = left;
2815 mRightVolFloat = right;
2816
2817 // If audio HAL implements volume control,
2818 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002819 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002820 left = 1.0f;
2821 right = 1.0f;
2822 }
2823
2824 // Convert volumes from float to 8.24
2825 uint32_t vl = (uint32_t)(left * (1 << 24));
2826 uint32_t vr = (uint32_t)(right * (1 << 24));
2827
2828 // Delegate volume control to effect in track effect chain if needed
2829 // only one effect chain can be present on DirectOutputThread, so if
2830 // there is one, the track is connected to it
2831 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002832 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002833 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834 rampVolume = false;
2835 }
2836 }
2837
2838 // Convert volumes from 8.24 to 4.12 format
2839 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2840 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2841 leftVol = (uint16_t)v_clamped;
2842 v_clamped = (vr + (1 << 11)) >> 12;
2843 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2844 rightVol = (uint16_t)v_clamped;
2845 } else {
2846 leftVol = mLeftVolShort;
2847 rightVol = mRightVolShort;
2848 rampVolume = false;
2849 }
2850
2851 // reset retry count
2852 track->mRetryCount = kMaxTrackRetriesDirect;
2853 activeTrack = t;
2854 mixerStatus = MIXER_TRACKS_READY;
2855 } else {
Steve Block3856b092011-10-20 11:56:00 +01002856 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002857 if (track->isStopped()) {
2858 track->reset();
2859 }
2860 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2861 // We have consumed all the buffers of this track.
2862 // Remove it from the list of active tracks.
2863 trackToRemove = track;
2864 } else {
2865 // No buffers for this track. Give it a few chances to
2866 // fill a buffer, then remove it from active list.
2867 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002868 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002869 trackToRemove = track;
2870 } else {
2871 mixerStatus = MIXER_TRACKS_ENABLED;
2872 }
2873 }
2874 }
2875 }
2876
2877 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002878 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002879 mActiveTracks.remove(trackToRemove);
2880 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002881 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002882 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002883 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002884 }
2885 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002886 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002887 }
2888 }
2889
Eric Laurentde070132010-07-13 04:45:46 -07002890 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002891 }
2892
Glenn Kastenf6b16782011-12-15 09:51:17 -08002893 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002894 AudioBufferProvider::Buffer buffer;
2895 size_t frameCount = mFrameCount;
Glenn Kastena1117922012-01-26 10:53:32 -08002896 int8_t *curBuf = (int8_t *)mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002897 // output audio to hardware
2898 while (frameCount) {
2899 buffer.frameCount = frameCount;
John Grossman4ff14ba2012-02-08 16:37:41 -08002900 activeTrack->getNextBuffer(&buffer,
2901 AudioBufferProvider::kInvalidPTS);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002902 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002903 memset(curBuf, 0, frameCount * mFrameSize);
2904 break;
2905 }
2906 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2907 frameCount -= buffer.frameCount;
2908 curBuf += buffer.frameCount * mFrameSize;
2909 activeTrack->releaseBuffer(&buffer);
2910 }
2911 sleepTime = 0;
2912 standbyTime = systemTime() + standbyDelay;
2913 } else {
2914 if (sleepTime == 0) {
2915 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2916 sleepTime = activeSleepTime;
2917 } else {
2918 sleepTime = idleSleepTime;
2919 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002920 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002921 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2922 sleepTime = 0;
2923 }
2924 }
2925
2926 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002927 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002928 }
2929 // sleepTime == 0 means we must write to audio hardware
2930 if (sleepTime == 0) {
2931 if (mixerStatus == MIXER_TRACKS_READY) {
2932 applyVolume(leftVol, rightVol, rampVolume);
2933 }
2934 for (size_t i = 0; i < effectChains.size(); i ++) {
2935 effectChains[i]->process_l();
2936 }
Eric Laurentde070132010-07-13 04:45:46 -07002937 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002938
2939 mLastWriteTime = systemTime();
2940 mInWrite = true;
2941 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002942 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002943 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2944 mNumWrites++;
2945 mInWrite = false;
2946 mStandby = false;
2947 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002948 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002949 usleep(sleepTime);
2950 }
2951
2952 // finally let go of removed track, without the lock held
2953 // since we can't guarantee the destructors won't acquire that
2954 // same lock.
2955 trackToRemove.clear();
2956 activeTrack.clear();
2957
2958 // Effect chains will be actually deleted here if they were removed from
2959 // mEffectChains list during mixing or effects processing
2960 effectChains.clear();
2961 }
2962
2963 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002964 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002965 }
2966
Eric Laurentfeb0db62011-07-22 09:04:31 -07002967 releaseWakeLock();
2968
Steve Block3856b092011-10-20 11:56:00 +01002969 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002970 return false;
2971}
2972
2973// getTrackName_l() must be called with ThreadBase::mLock held
2974int AudioFlinger::DirectOutputThread::getTrackName_l()
2975{
2976 return 0;
2977}
2978
2979// deleteTrackName_l() must be called with ThreadBase::mLock held
2980void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2981{
2982}
2983
2984// checkForNewParameters_l() must be called with ThreadBase::mLock held
2985bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2986{
2987 bool reconfig = false;
2988
2989 while (!mNewParameters.isEmpty()) {
2990 status_t status = NO_ERROR;
2991 String8 keyValuePair = mNewParameters[0];
2992 AudioParameter param = AudioParameter(keyValuePair);
2993 int value;
2994
2995 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2996 // do not accept frame count changes if tracks are open as the track buffer
2997 // size depends on frame count and correct behavior would not be garantied
2998 // if frame count is changed after track creation
2999 if (!mTracks.isEmpty()) {
3000 status = INVALID_OPERATION;
3001 } else {
3002 reconfig = true;
3003 }
3004 }
3005 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003006 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003007 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003008 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003009 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003010 mStandby = true;
3011 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07003012 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003013 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003014 }
3015 if (status == NO_ERROR && reconfig) {
3016 readOutputParameters();
3017 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3018 }
3019 }
3020
3021 mNewParameters.removeAt(0);
3022
3023 mParamStatus = status;
3024 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003025 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3026 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003027 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003028 }
3029 return reconfig;
3030}
3031
3032uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
3033{
3034 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003035 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003036 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003037 } else {
3038 time = 10000;
3039 }
3040 return time;
3041}
3042
3043uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
3044{
3045 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003046 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003047 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003048 } else {
3049 time = 10000;
3050 }
3051 return time;
3052}
3053
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003054uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
3055{
3056 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003057 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003058 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3059 } else {
3060 time = 10000;
3061 }
3062 return time;
3063}
3064
3065
Mathias Agopian65ab4712010-07-14 17:59:35 -07003066// ----------------------------------------------------------------------------
3067
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003068AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003069 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003070 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3071 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003072{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003073 addOutputTrack(mainThread);
3074}
3075
3076AudioFlinger::DuplicatingThread::~DuplicatingThread()
3077{
3078 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3079 mOutputTracks[i]->destroy();
3080 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003081}
3082
3083bool AudioFlinger::DuplicatingThread::threadLoop()
3084{
3085 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08003086 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003087 nsecs_t standbyTime = systemTime();
3088 size_t mixBufferSize = mFrameCount*mFrameSize;
3089 SortedVector< sp<OutputTrack> > outputTracks;
3090 uint32_t writeFrames = 0;
3091 uint32_t activeSleepTime = activeSleepTimeUs();
3092 uint32_t idleSleepTime = idleSleepTimeUs();
3093 uint32_t sleepTime = idleSleepTime;
3094 Vector< sp<EffectChain> > effectChains;
3095
Eric Laurentfeb0db62011-07-22 09:04:31 -07003096 acquireWakeLock();
3097
Mathias Agopian65ab4712010-07-14 17:59:35 -07003098 while (!exitPending())
3099 {
3100 processConfigEvents();
3101
3102 mixerStatus = MIXER_IDLE;
3103 { // scope for the mLock
3104
3105 Mutex::Autolock _l(mLock);
3106
3107 if (checkForNewParameters_l()) {
3108 mixBufferSize = mFrameCount*mFrameSize;
3109 updateWaitTime();
3110 activeSleepTime = activeSleepTimeUs();
3111 idleSleepTime = idleSleepTimeUs();
3112 }
3113
3114 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3115
3116 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3117 outputTracks.add(mOutputTracks[i]);
3118 }
3119
3120 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08003121 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3122 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003123 if (!mStandby) {
3124 for (size_t i = 0; i < outputTracks.size(); i++) {
3125 outputTracks[i]->stop();
3126 }
3127 mStandby = true;
3128 mBytesWritten = 0;
3129 }
3130
3131 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3132 // we're about to wait, flush the binder command buffer
3133 IPCThreadState::self()->flushCommands();
3134 outputTracks.clear();
3135
3136 if (exitPending()) break;
3137
Eric Laurentfeb0db62011-07-22 09:04:31 -07003138 releaseWakeLock_l();
Glenn Kasten90bebef2012-01-27 15:24:38 -08003139 ALOGV("DuplicatingThread %p TID %d going to sleep", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003140 mWaitWorkCV.wait(mLock);
Glenn Kasten90bebef2012-01-27 15:24:38 -08003141 ALOGV("DuplicatingThread %p TID %d waking up", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003142 acquireWakeLock_l();
3143
Eric Laurent27741442012-01-17 19:20:12 -08003144 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08003145 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003146 char value[PROPERTY_VALUE_MAX];
3147 property_get("ro.audio.silent", value, "0");
3148 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00003149 ALOGD("Silence is golden");
Glenn Kasten6637baa2012-01-09 09:40:36 -08003150 setMasterMute_l(true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003151 }
3152 }
3153
John Grossman4ff14ba2012-02-08 16:37:41 -08003154 standbyTime = systemTime() + mStandbyTimeInNsecs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003155 sleepTime = idleSleepTime;
3156 continue;
3157 }
3158 }
3159
3160 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3161
3162 // prevent any changes in effect chain list and in each effect chain
3163 // during mixing and effect process as the audio buffers could be deleted
3164 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003165 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003166 }
3167
Glenn Kastenf6b16782011-12-15 09:51:17 -08003168 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003169 // mix buffers...
3170 if (outputsReady(outputTracks)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08003171 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003172 } else {
3173 memset(mMixBuffer, 0, mixBufferSize);
3174 }
3175 sleepTime = 0;
3176 writeFrames = mFrameCount;
3177 } else {
3178 if (sleepTime == 0) {
3179 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3180 sleepTime = activeSleepTime;
3181 } else {
3182 sleepTime = idleSleepTime;
3183 }
3184 } else if (mBytesWritten != 0) {
3185 // flush remaining overflow buffers in output tracks
3186 for (size_t i = 0; i < outputTracks.size(); i++) {
3187 if (outputTracks[i]->isActive()) {
3188 sleepTime = 0;
3189 writeFrames = 0;
3190 memset(mMixBuffer, 0, mixBufferSize);
3191 break;
3192 }
3193 }
3194 }
3195 }
3196
3197 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003198 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003199 }
3200 // sleepTime == 0 means we must write to audio hardware
3201 if (sleepTime == 0) {
3202 for (size_t i = 0; i < effectChains.size(); i ++) {
3203 effectChains[i]->process_l();
3204 }
3205 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003206 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003207
John Grossman4ff14ba2012-02-08 16:37:41 -08003208 standbyTime = systemTime() + mStandbyTimeInNsecs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003209 for (size_t i = 0; i < outputTracks.size(); i++) {
3210 outputTracks[i]->write(mMixBuffer, writeFrames);
3211 }
3212 mStandby = false;
3213 mBytesWritten += mixBufferSize;
3214 } else {
3215 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003216 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003217 usleep(sleepTime);
3218 }
3219
3220 // finally let go of all our tracks, without the lock held
3221 // since we can't guarantee the destructors won't acquire that
3222 // same lock.
3223 tracksToRemove.clear();
3224 outputTracks.clear();
3225
3226 // Effect chains will be actually deleted here if they were removed from
3227 // mEffectChains list during mixing or effects processing
3228 effectChains.clear();
3229 }
3230
Eric Laurentfeb0db62011-07-22 09:04:31 -07003231 releaseWakeLock();
3232
Mathias Agopian65ab4712010-07-14 17:59:35 -07003233 return false;
3234}
3235
3236void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3237{
Glenn Kasten99e53b82012-01-19 08:59:58 -08003238 // FIXME explain this formula
Mathias Agopian65ab4712010-07-14 17:59:35 -07003239 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003240 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003241 this,
3242 mSampleRate,
3243 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003244 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003245 frameCount);
3246 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003247 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003248 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003249 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003250 updateWaitTime();
3251 }
3252}
3253
3254void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3255{
3256 Mutex::Autolock _l(mLock);
3257 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003258 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003259 mOutputTracks[i]->destroy();
3260 mOutputTracks.removeAt(i);
3261 updateWaitTime();
3262 return;
3263 }
3264 }
Steve Block3856b092011-10-20 11:56:00 +01003265 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003266}
3267
3268void AudioFlinger::DuplicatingThread::updateWaitTime()
3269{
3270 mWaitTimeMs = UINT_MAX;
3271 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3272 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003273 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003274 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3275 if (waitTimeMs < mWaitTimeMs) {
3276 mWaitTimeMs = waitTimeMs;
3277 }
3278 }
3279 }
3280}
3281
3282
3283bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3284{
3285 for (size_t i = 0; i < outputTracks.size(); i++) {
3286 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3287 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003288 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003289 return false;
3290 }
3291 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3292 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003293 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003294 return false;
3295 }
3296 }
3297 return true;
3298}
3299
3300uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3301{
3302 return (mWaitTimeMs * 1000) / 2;
3303}
3304
3305// ----------------------------------------------------------------------------
3306
3307// TrackBase constructor must be called with AudioFlinger::mLock held
3308AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003309 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003310 const sp<Client>& client,
3311 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003312 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003313 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003314 int frameCount,
3315 uint32_t flags,
3316 const sp<IMemory>& sharedBuffer,
3317 int sessionId)
3318 : RefBase(),
3319 mThread(thread),
3320 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003321 mCblk(NULL),
3322 // mBuffer
3323 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003324 mFrameCount(0),
3325 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003326 mFormat(format),
3327 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3328 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003329 // mChannelCount
3330 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003331{
Steve Block3856b092011-10-20 11:56:00 +01003332 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003333
Steve Blockb8a80522011-12-20 16:23:08 +00003334 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003335 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003336 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003337 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3338 if (sharedBuffer == 0) {
3339 size += bufferSize;
3340 }
3341
3342 if (client != NULL) {
3343 mCblkMemory = client->heap()->allocate(size);
3344 if (mCblkMemory != 0) {
3345 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003346 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003347 new(mCblk) audio_track_cblk_t();
3348 // clear all buffers
3349 mCblk->frameCount = frameCount;
3350 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003351 mChannelCount = channelCount;
3352 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003353 if (sharedBuffer == 0) {
3354 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3355 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3356 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003357 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003358 mCblk->flags = CBLK_UNDERRUN_ON;
3359 } else {
3360 mBuffer = sharedBuffer->pointer();
3361 }
3362 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3363 }
3364 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003365 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003366 client->heap()->dump("AudioTrack");
3367 return;
3368 }
3369 } else {
3370 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003371 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003372 new(mCblk) audio_track_cblk_t();
3373 // clear all buffers
3374 mCblk->frameCount = frameCount;
3375 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003376 mChannelCount = channelCount;
3377 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003378 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3379 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3380 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003381 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003382 mCblk->flags = CBLK_UNDERRUN_ON;
3383 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003384 }
3385}
3386
3387AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3388{
Glenn Kastena0d68332012-01-27 16:47:15 -08003389 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003390 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003391 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003392 } else {
3393 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003394 }
3395 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003396 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003397 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003398 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003399 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003400 // If the client's reference count drops to zero, the associated destructor
3401 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3402 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003403 mClient.clear();
3404 }
3405}
3406
3407void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3408{
Glenn Kastene0feee32011-12-13 11:53:26 -08003409 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003410 mFrameCount = buffer->frameCount;
3411 step();
3412 buffer->frameCount = 0;
3413}
3414
3415bool AudioFlinger::ThreadBase::TrackBase::step() {
3416 bool result;
3417 audio_track_cblk_t* cblk = this->cblk();
3418
3419 result = cblk->stepServer(mFrameCount);
3420 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003421 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003422 mFlags |= STEPSERVER_FAILED;
3423 }
3424 return result;
3425}
3426
3427void AudioFlinger::ThreadBase::TrackBase::reset() {
3428 audio_track_cblk_t* cblk = this->cblk();
3429
3430 cblk->user = 0;
3431 cblk->server = 0;
3432 cblk->userBase = 0;
3433 cblk->serverBase = 0;
3434 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003435 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003436}
3437
Mathias Agopian65ab4712010-07-14 17:59:35 -07003438int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3439 return (int)mCblk->sampleRate;
3440}
3441
Mathias Agopian65ab4712010-07-14 17:59:35 -07003442void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3443 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003444 size_t frameSize = cblk->frameSize;
3445 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3446 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003447
3448 // Check validity of returned pointer in case the track control block would have been corrupted.
3449 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003450 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003451 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 -07003452 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003453 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003454 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003455 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003456 }
3457
3458 return bufferStart;
3459}
3460
3461// ----------------------------------------------------------------------------
3462
3463// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3464AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003465 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003466 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003467 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003468 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003469 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003470 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003471 int frameCount,
3472 const sp<IMemory>& sharedBuffer,
3473 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003474 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003475 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3476 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003477{
3478 if (mCblk != NULL) {
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003479 if (thread != NULL) {
3480 mName = thread->getTrackName_l();
3481 mMainBuffer = thread->mixBuffer();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003482 }
Glenn Kasten23d82a92012-02-03 11:10:00 -08003483 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003484 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003485 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003486 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003487 mStreamType = streamType;
3488 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3489 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003490 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003491 }
3492}
3493
3494AudioFlinger::PlaybackThread::Track::~Track()
3495{
Steve Block3856b092011-10-20 11:56:00 +01003496 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003497 sp<ThreadBase> thread = mThread.promote();
3498 if (thread != 0) {
3499 Mutex::Autolock _l(thread->mLock);
3500 mState = TERMINATED;
3501 }
3502}
3503
3504void AudioFlinger::PlaybackThread::Track::destroy()
3505{
3506 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3507 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08003508 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003509 // we must acquire a strong reference on this Track before locking mLock
3510 // here so that the destructor is called only when exiting this function.
3511 // On the other hand, as long as Track::destroy() is only called by
3512 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3513 // this Track with its member mTrack.
3514 sp<Track> keep(this);
3515 { // scope for mLock
3516 sp<ThreadBase> thread = mThread.promote();
3517 if (thread != 0) {
3518 if (!isOutputTrack()) {
3519 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08003520 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003521
3522 // to track the speaker usage
3523 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003524 }
3525 AudioSystem::releaseOutput(thread->id());
3526 }
3527 Mutex::Autolock _l(thread->mLock);
3528 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3529 playbackThread->destroyTrack_l(this);
3530 }
3531 }
3532}
3533
3534void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3535{
Glenn Kasten83d86532012-01-17 14:39:34 -08003536 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003537 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 -07003538 mName - AudioMixer::TRACK0,
Glenn Kasten44deb052012-02-05 18:09:08 -08003539 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003540 mStreamType,
3541 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003542 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003543 mSessionId,
3544 mFrameCount,
3545 mState,
3546 mMute,
3547 mFillingUpStatus,
3548 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003549 vlr & 0xFFFF,
3550 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003551 mCblk->server,
3552 mCblk->user,
3553 (int)mMainBuffer,
3554 (int)mAuxBuffer);
3555}
3556
John Grossman4ff14ba2012-02-08 16:37:41 -08003557status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
3558 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003559{
3560 audio_track_cblk_t* cblk = this->cblk();
3561 uint32_t framesReady;
3562 uint32_t framesReq = buffer->frameCount;
3563
3564 // Check if last stepServer failed, try to step now
3565 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3566 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003567 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003568 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3569 }
3570
3571 framesReady = cblk->framesReady();
3572
Glenn Kastenf6b16782011-12-15 09:51:17 -08003573 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003574 uint32_t s = cblk->server;
3575 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3576
3577 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3578 if (framesReq > framesReady) {
3579 framesReq = framesReady;
3580 }
3581 if (s + framesReq > bufferEnd) {
3582 framesReq = bufferEnd - s;
3583 }
3584
3585 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003586 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003587
3588 buffer->frameCount = framesReq;
3589 return NO_ERROR;
3590 }
3591
3592getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003593 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003594 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003595 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003596 return NOT_ENOUGH_DATA;
3597}
3598
John Grossman4ff14ba2012-02-08 16:37:41 -08003599uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const{
3600 return mCblk->framesReady();
3601}
3602
Mathias Agopian65ab4712010-07-14 17:59:35 -07003603bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003604 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003605
John Grossman4ff14ba2012-02-08 16:37:41 -08003606 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003607 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3608 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003609 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003610 return true;
3611 }
3612 return false;
3613}
3614
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003615status_t AudioFlinger::PlaybackThread::Track::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003616{
3617 status_t status = NO_ERROR;
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003618 ALOGV("start(%d), calling pid %d session %d tid %d",
3619 mName, IPCThreadState::self()->getCallingPid(), mSessionId, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003620 sp<ThreadBase> thread = mThread.promote();
3621 if (thread != 0) {
3622 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003623 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003624 // here the track could be either new, or restarted
3625 // in both cases "unstop" the track
3626 if (mState == PAUSED) {
3627 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003628 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003629 } else {
3630 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003631 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003632 }
3633
3634 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3635 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003636 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003637 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003638
3639 // to track the speaker usage
3640 if (status == NO_ERROR) {
3641 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3642 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003643 }
3644 if (status == NO_ERROR) {
3645 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3646 playbackThread->addTrack_l(this);
3647 } else {
3648 mState = state;
3649 }
3650 } else {
3651 status = BAD_VALUE;
3652 }
3653 return status;
3654}
3655
3656void AudioFlinger::PlaybackThread::Track::stop()
3657{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003658 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003659 sp<ThreadBase> thread = mThread.promote();
3660 if (thread != 0) {
3661 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003662 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003663 if (mState > STOPPED) {
3664 mState = STOPPED;
3665 // If the track is not active (PAUSED and buffers full), flush buffers
3666 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3667 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3668 reset();
3669 }
Steve Block3856b092011-10-20 11:56:00 +01003670 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003671 }
3672 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3673 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003674 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003675 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003676
3677 // to track the speaker usage
3678 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003679 }
3680 }
3681}
3682
3683void AudioFlinger::PlaybackThread::Track::pause()
3684{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003685 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003686 sp<ThreadBase> thread = mThread.promote();
3687 if (thread != 0) {
3688 Mutex::Autolock _l(thread->mLock);
3689 if (mState == ACTIVE || mState == RESUMING) {
3690 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003691 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003692 if (!isOutputTrack()) {
3693 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003694 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003695 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003696
3697 // to track the speaker usage
3698 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003699 }
3700 }
3701 }
3702}
3703
3704void AudioFlinger::PlaybackThread::Track::flush()
3705{
Steve Block3856b092011-10-20 11:56:00 +01003706 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003707 sp<ThreadBase> thread = mThread.promote();
3708 if (thread != 0) {
3709 Mutex::Autolock _l(thread->mLock);
3710 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3711 return;
3712 }
3713 // No point remaining in PAUSED state after a flush => go to
3714 // STOPPED state
3715 mState = STOPPED;
3716
Eric Laurent38ccae22011-03-28 18:37:07 -07003717 // do not reset the track if it is still in the process of being stopped or paused.
3718 // this will be done by prepareTracks_l() when the track is stopped.
3719 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3720 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3721 reset();
3722 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003723 }
3724}
3725
3726void AudioFlinger::PlaybackThread::Track::reset()
3727{
3728 // Do not reset twice to avoid discarding data written just after a flush and before
3729 // the audioflinger thread detects the track is stopped.
3730 if (!mResetDone) {
3731 TrackBase::reset();
3732 // Force underrun condition to avoid false underrun callback until first data is
3733 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003734 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3735 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003736 mFillingUpStatus = FS_FILLING;
3737 mResetDone = true;
3738 }
3739}
3740
3741void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3742{
3743 mMute = muted;
3744}
3745
Mathias Agopian65ab4712010-07-14 17:59:35 -07003746status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3747{
3748 status_t status = DEAD_OBJECT;
3749 sp<ThreadBase> thread = mThread.promote();
3750 if (thread != 0) {
3751 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3752 status = playbackThread->attachAuxEffect(this, EffectId);
3753 }
3754 return status;
3755}
3756
3757void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3758{
3759 mAuxEffectId = EffectId;
3760 mAuxBuffer = buffer;
3761}
3762
John Grossman4ff14ba2012-02-08 16:37:41 -08003763// timed audio tracks
3764
3765sp<AudioFlinger::PlaybackThread::TimedTrack>
3766AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003767 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003768 const sp<Client>& client,
3769 audio_stream_type_t streamType,
3770 uint32_t sampleRate,
3771 audio_format_t format,
3772 uint32_t channelMask,
3773 int frameCount,
3774 const sp<IMemory>& sharedBuffer,
3775 int sessionId) {
3776 if (!client->reserveTimedTrack())
3777 return NULL;
3778
3779 sp<TimedTrack> track = new TimedTrack(
3780 thread, client, streamType, sampleRate, format, channelMask, frameCount,
3781 sharedBuffer, sessionId);
3782
3783 if (track == NULL) {
3784 client->releaseTimedTrack();
3785 return NULL;
3786 }
3787
3788 return track;
3789}
3790
3791AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003792 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003793 const sp<Client>& client,
3794 audio_stream_type_t streamType,
3795 uint32_t sampleRate,
3796 audio_format_t format,
3797 uint32_t channelMask,
3798 int frameCount,
3799 const sp<IMemory>& sharedBuffer,
3800 int sessionId)
3801 : Track(thread, client, streamType, sampleRate, format, channelMask,
3802 frameCount, sharedBuffer, sessionId),
3803 mTimedSilenceBuffer(NULL),
3804 mTimedSilenceBufferSize(0),
3805 mTimedAudioOutputOnTime(false),
3806 mMediaTimeTransformValid(false)
3807{
3808 LocalClock lc;
3809 mLocalTimeFreq = lc.getLocalFreq();
3810
3811 mLocalTimeToSampleTransform.a_zero = 0;
3812 mLocalTimeToSampleTransform.b_zero = 0;
3813 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3814 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3815 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3816 &mLocalTimeToSampleTransform.a_to_b_denom);
3817}
3818
3819AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3820 mClient->releaseTimedTrack();
3821 delete [] mTimedSilenceBuffer;
3822}
3823
3824status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3825 size_t size, sp<IMemory>* buffer) {
3826
3827 Mutex::Autolock _l(mTimedBufferQueueLock);
3828
3829 trimTimedBufferQueue_l();
3830
3831 // lazily initialize the shared memory heap for timed buffers
3832 if (mTimedMemoryDealer == NULL) {
3833 const int kTimedBufferHeapSize = 512 << 10;
3834
3835 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3836 "AudioFlingerTimed");
3837 if (mTimedMemoryDealer == NULL)
3838 return NO_MEMORY;
3839 }
3840
3841 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3842 if (newBuffer == NULL) {
3843 newBuffer = mTimedMemoryDealer->allocate(size);
3844 if (newBuffer == NULL)
3845 return NO_MEMORY;
3846 }
3847
3848 *buffer = newBuffer;
3849 return NO_ERROR;
3850}
3851
3852// caller must hold mTimedBufferQueueLock
3853void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
3854 int64_t mediaTimeNow;
3855 {
3856 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3857 if (!mMediaTimeTransformValid)
3858 return;
3859
3860 int64_t targetTimeNow;
3861 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
3862 ? mCCHelper.getCommonTime(&targetTimeNow)
3863 : mCCHelper.getLocalTime(&targetTimeNow);
3864
3865 if (OK != res)
3866 return;
3867
3868 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
3869 &mediaTimeNow)) {
3870 return;
3871 }
3872 }
3873
3874 size_t trimIndex;
3875 for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
3876 if (mTimedBufferQueue[trimIndex].pts() > mediaTimeNow)
3877 break;
3878 }
3879
3880 if (trimIndex) {
3881 mTimedBufferQueue.removeItemsAt(0, trimIndex);
3882 }
3883}
3884
3885status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
3886 const sp<IMemory>& buffer, int64_t pts) {
3887
3888 {
3889 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3890 if (!mMediaTimeTransformValid)
3891 return INVALID_OPERATION;
3892 }
3893
3894 Mutex::Autolock _l(mTimedBufferQueueLock);
3895
3896 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
3897
3898 return NO_ERROR;
3899}
3900
3901status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
3902 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
3903
3904 ALOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
3905 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
3906 target);
3907
3908 if (!(target == TimedAudioTrack::LOCAL_TIME ||
3909 target == TimedAudioTrack::COMMON_TIME)) {
3910 return BAD_VALUE;
3911 }
3912
3913 Mutex::Autolock lock(mMediaTimeTransformLock);
3914 mMediaTimeTransform = xform;
3915 mMediaTimeTransformTarget = target;
3916 mMediaTimeTransformValid = true;
3917
3918 return NO_ERROR;
3919}
3920
3921#define min(a, b) ((a) < (b) ? (a) : (b))
3922
3923// implementation of getNextBuffer for tracks whose buffers have timestamps
3924status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
3925 AudioBufferProvider::Buffer* buffer, int64_t pts)
3926{
3927 if (pts == AudioBufferProvider::kInvalidPTS) {
3928 buffer->raw = 0;
3929 buffer->frameCount = 0;
3930 return INVALID_OPERATION;
3931 }
3932
John Grossman4ff14ba2012-02-08 16:37:41 -08003933 Mutex::Autolock _l(mTimedBufferQueueLock);
3934
3935 while (true) {
3936
3937 // if we have no timed buffers, then fail
3938 if (mTimedBufferQueue.isEmpty()) {
3939 buffer->raw = 0;
3940 buffer->frameCount = 0;
3941 return NOT_ENOUGH_DATA;
3942 }
3943
3944 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
3945
3946 // calculate the PTS of the head of the timed buffer queue expressed in
3947 // local time
3948 int64_t headLocalPTS;
3949 {
3950 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3951
3952 assert(mMediaTimeTransformValid);
3953
3954 if (mMediaTimeTransform.a_to_b_denom == 0) {
3955 // the transform represents a pause, so yield silence
3956 timedYieldSilence(buffer->frameCount, buffer);
3957 return NO_ERROR;
3958 }
3959
3960 int64_t transformedPTS;
3961 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
3962 &transformedPTS)) {
3963 // the transform failed. this shouldn't happen, but if it does
3964 // then just drop this buffer
3965 ALOGW("timedGetNextBuffer transform failed");
3966 buffer->raw = 0;
3967 buffer->frameCount = 0;
3968 mTimedBufferQueue.removeAt(0);
3969 return NO_ERROR;
3970 }
3971
3972 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
3973 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
3974 &headLocalPTS)) {
3975 buffer->raw = 0;
3976 buffer->frameCount = 0;
3977 return INVALID_OPERATION;
3978 }
3979 } else {
3980 headLocalPTS = transformedPTS;
3981 }
3982 }
3983
3984 // adjust the head buffer's PTS to reflect the portion of the head buffer
3985 // that has already been consumed
3986 int64_t effectivePTS = headLocalPTS +
3987 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
3988
3989 // Calculate the delta in samples between the head of the input buffer
3990 // queue and the start of the next output buffer that will be written.
3991 // If the transformation fails because of over or underflow, it means
3992 // that the sample's position in the output stream is so far out of
3993 // whack that it should just be dropped.
3994 int64_t sampleDelta;
3995 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
3996 ALOGV("*** head buffer is too far from PTS: dropped buffer");
3997 mTimedBufferQueue.removeAt(0);
3998 continue;
3999 }
4000 if (!mLocalTimeToSampleTransform.doForwardTransform(
4001 (effectivePTS - pts) << 32, &sampleDelta)) {
4002 ALOGV("*** too late during sample rate transform: dropped buffer");
4003 mTimedBufferQueue.removeAt(0);
4004 continue;
4005 }
4006
4007 ALOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
4008 __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
4009 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
4010 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
4011
4012 // if the delta between the ideal placement for the next input sample and
4013 // the current output position is within this threshold, then we will
4014 // concatenate the next input samples to the previous output
4015 const int64_t kSampleContinuityThreshold =
4016 (static_cast<int64_t>(sampleRate()) << 32) / 10;
4017
4018 // if this is the first buffer of audio that we're emitting from this track
4019 // then it should be almost exactly on time.
4020 const int64_t kSampleStartupThreshold = 1LL << 32;
4021
4022 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
4023 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
4024 // the next input is close enough to being on time, so concatenate it
4025 // with the last output
4026 timedYieldSamples(buffer);
4027
4028 ALOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4029 return NO_ERROR;
4030 } else if (sampleDelta > 0) {
4031 // the gap between the current output position and the proper start of
4032 // the next input sample is too big, so fill it with silence
4033 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4034
4035 timedYieldSilence(framesUntilNextInput, buffer);
4036 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4037 return NO_ERROR;
4038 } else {
4039 // the next input sample is late
4040 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4041 size_t onTimeSamplePosition =
4042 head.position() + lateFrames * mCblk->frameSize;
4043
4044 if (onTimeSamplePosition > head.buffer()->size()) {
4045 // all the remaining samples in the head are too late, so
4046 // drop it and move on
4047 ALOGV("*** too late: dropped buffer");
4048 mTimedBufferQueue.removeAt(0);
4049 continue;
4050 } else {
4051 // skip over the late samples
4052 head.setPosition(onTimeSamplePosition);
4053
4054 // yield the available samples
4055 timedYieldSamples(buffer);
4056
4057 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4058 return NO_ERROR;
4059 }
4060 }
4061 }
4062}
4063
4064// Yield samples from the timed buffer queue head up to the given output
4065// buffer's capacity.
4066//
4067// Caller must hold mTimedBufferQueueLock
4068void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples(
4069 AudioBufferProvider::Buffer* buffer) {
4070
4071 const TimedBuffer& head = mTimedBufferQueue[0];
4072
4073 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4074 head.position());
4075
4076 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4077 mCblk->frameSize);
4078 size_t framesRequested = buffer->frameCount;
4079 buffer->frameCount = min(framesLeftInHead, framesRequested);
4080
4081 mTimedAudioOutputOnTime = true;
4082}
4083
4084// Yield samples of silence up to the given output buffer's capacity
4085//
4086// Caller must hold mTimedBufferQueueLock
4087void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence(
4088 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4089
4090 // lazily allocate a buffer filled with silence
4091 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4092 delete [] mTimedSilenceBuffer;
4093 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4094 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4095 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4096 }
4097
4098 buffer->raw = mTimedSilenceBuffer;
4099 size_t framesRequested = buffer->frameCount;
4100 buffer->frameCount = min(numFrames, framesRequested);
4101
4102 mTimedAudioOutputOnTime = false;
4103}
4104
4105void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4106 AudioBufferProvider::Buffer* buffer) {
4107
4108 Mutex::Autolock _l(mTimedBufferQueueLock);
4109
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004110 // If the buffer which was just released is part of the buffer at the head
4111 // of the queue, be sure to update the amt of the buffer which has been
4112 // consumed. If the buffer being returned is not part of the head of the
4113 // queue, its either because the buffer is part of the silence buffer, or
4114 // because the head of the timed queue was trimmed after the mixer called
4115 // getNextBuffer but before the mixer called releaseBuffer.
4116 if ((buffer->raw != mTimedSilenceBuffer) && mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004117 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004118
4119 void* start = head.buffer()->pointer();
Glenn Kastenf063b492012-02-17 16:24:10 -08004120 void* end = (char *) head.buffer()->pointer() + head.buffer()->size();
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004121
4122 if ((buffer->raw >= start) && (buffer->raw <= end)) {
4123 head.setPosition(head.position() +
4124 (buffer->frameCount * mCblk->frameSize));
4125 if (static_cast<size_t>(head.position()) >= head.buffer()->size()) {
4126 mTimedBufferQueue.removeAt(0);
4127 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004128 }
4129 }
4130
4131 buffer->raw = 0;
4132 buffer->frameCount = 0;
4133}
4134
4135uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4136 Mutex::Autolock _l(mTimedBufferQueueLock);
4137
4138 uint32_t frames = 0;
4139 for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4140 const TimedBuffer& tb = mTimedBufferQueue[i];
4141 frames += (tb.buffer()->size() - tb.position()) / mCblk->frameSize;
4142 }
4143
4144 return frames;
4145}
4146
4147AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4148 : mPTS(0), mPosition(0) {}
4149
4150AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4151 const sp<IMemory>& buffer, int64_t pts)
4152 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4153
Mathias Agopian65ab4712010-07-14 17:59:35 -07004154// ----------------------------------------------------------------------------
4155
4156// RecordTrack constructor must be called with AudioFlinger::mLock held
4157AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004158 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004159 const sp<Client>& client,
4160 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004161 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004162 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004163 int frameCount,
4164 uint32_t flags,
4165 int sessionId)
4166 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004167 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004168 mOverflow(false)
4169{
4170 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01004171 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07004172 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004173 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07004174 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004175 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004176 } else {
4177 mCblk->frameSize = sizeof(int8_t);
4178 }
4179 }
4180}
4181
4182AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4183{
4184 sp<ThreadBase> thread = mThread.promote();
4185 if (thread != 0) {
4186 AudioSystem::releaseInput(thread->id());
4187 }
4188}
4189
John Grossman4ff14ba2012-02-08 16:37:41 -08004190status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004191{
4192 audio_track_cblk_t* cblk = this->cblk();
4193 uint32_t framesAvail;
4194 uint32_t framesReq = buffer->frameCount;
4195
4196 // Check if last stepServer failed, try to step now
4197 if (mFlags & TrackBase::STEPSERVER_FAILED) {
4198 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004199 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004200 mFlags &= ~TrackBase::STEPSERVER_FAILED;
4201 }
4202
4203 framesAvail = cblk->framesAvailable_l();
4204
Glenn Kastenf6b16782011-12-15 09:51:17 -08004205 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004206 uint32_t s = cblk->server;
4207 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4208
4209 if (framesReq > framesAvail) {
4210 framesReq = framesAvail;
4211 }
4212 if (s + framesReq > bufferEnd) {
4213 framesReq = bufferEnd - s;
4214 }
4215
4216 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004217 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004218
4219 buffer->frameCount = framesReq;
4220 return NO_ERROR;
4221 }
4222
4223getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004224 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004225 buffer->frameCount = 0;
4226 return NOT_ENOUGH_DATA;
4227}
4228
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004229status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004230{
4231 sp<ThreadBase> thread = mThread.promote();
4232 if (thread != 0) {
4233 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004234 return recordThread->start(this, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004235 } else {
4236 return BAD_VALUE;
4237 }
4238}
4239
4240void AudioFlinger::RecordThread::RecordTrack::stop()
4241{
4242 sp<ThreadBase> thread = mThread.promote();
4243 if (thread != 0) {
4244 RecordThread *recordThread = (RecordThread *)thread.get();
4245 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004246 TrackBase::reset();
4247 // Force overerrun condition to avoid false overrun callback until first data is
4248 // read from buffer
4249 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004250 }
4251}
4252
4253void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4254{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004255 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004256 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004257 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004258 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004259 mSessionId,
4260 mFrameCount,
4261 mState,
4262 mCblk->sampleRate,
4263 mCblk->server,
4264 mCblk->user);
4265}
4266
4267
4268// ----------------------------------------------------------------------------
4269
4270AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004271 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004272 DuplicatingThread *sourceThread,
4273 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004274 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004275 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004276 int frameCount)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004277 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004278 mActive(false), mSourceThread(sourceThread)
4279{
4280
Mathias Agopian65ab4712010-07-14 17:59:35 -07004281 if (mCblk != NULL) {
4282 mCblk->flags |= CBLK_DIRECTION_OUT;
4283 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004284 mOutBuffer.frameCount = 0;
4285 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01004286 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004287 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4288 mCblk, mBuffer, mCblk->buffers,
4289 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004290 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004291 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004292 }
4293}
4294
4295AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4296{
4297 clearBufferQueue();
4298}
4299
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004300status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004301{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004302 status_t status = Track::start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004303 if (status != NO_ERROR) {
4304 return status;
4305 }
4306
4307 mActive = true;
4308 mRetryCount = 127;
4309 return status;
4310}
4311
4312void AudioFlinger::PlaybackThread::OutputTrack::stop()
4313{
4314 Track::stop();
4315 clearBufferQueue();
4316 mOutBuffer.frameCount = 0;
4317 mActive = false;
4318}
4319
4320bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4321{
4322 Buffer *pInBuffer;
4323 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004324 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004325 bool outputBufferFull = false;
4326 inBuffer.frameCount = frames;
4327 inBuffer.i16 = data;
4328
4329 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4330
4331 if (!mActive && frames != 0) {
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004332 start(0);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004333 sp<ThreadBase> thread = mThread.promote();
4334 if (thread != 0) {
4335 MixerThread *mixerThread = (MixerThread *)thread.get();
4336 if (mCblk->frameCount > frames){
4337 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4338 uint32_t startFrames = (mCblk->frameCount - frames);
4339 pInBuffer = new Buffer;
4340 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4341 pInBuffer->frameCount = startFrames;
4342 pInBuffer->i16 = pInBuffer->mBuffer;
4343 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4344 mBufferQueue.add(pInBuffer);
4345 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004346 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004347 }
4348 }
4349 }
4350 }
4351
4352 while (waitTimeLeftMs) {
4353 // First write pending buffers, then new data
4354 if (mBufferQueue.size()) {
4355 pInBuffer = mBufferQueue.itemAt(0);
4356 } else {
4357 pInBuffer = &inBuffer;
4358 }
4359
4360 if (pInBuffer->frameCount == 0) {
4361 break;
4362 }
4363
4364 if (mOutBuffer.frameCount == 0) {
4365 mOutBuffer.frameCount = pInBuffer->frameCount;
4366 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08004367 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01004368 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004369 outputBufferFull = true;
4370 break;
4371 }
4372 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4373 if (waitTimeLeftMs >= waitTimeMs) {
4374 waitTimeLeftMs -= waitTimeMs;
4375 } else {
4376 waitTimeLeftMs = 0;
4377 }
4378 }
4379
4380 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4381 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4382 mCblk->stepUser(outFrames);
4383 pInBuffer->frameCount -= outFrames;
4384 pInBuffer->i16 += outFrames * channelCount;
4385 mOutBuffer.frameCount -= outFrames;
4386 mOutBuffer.i16 += outFrames * channelCount;
4387
4388 if (pInBuffer->frameCount == 0) {
4389 if (mBufferQueue.size()) {
4390 mBufferQueue.removeAt(0);
4391 delete [] pInBuffer->mBuffer;
4392 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01004393 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004394 } else {
4395 break;
4396 }
4397 }
4398 }
4399
4400 // If we could not write all frames, allocate a buffer and queue it for next time.
4401 if (inBuffer.frameCount) {
4402 sp<ThreadBase> thread = mThread.promote();
4403 if (thread != 0 && !thread->standby()) {
4404 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4405 pInBuffer = new Buffer;
4406 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4407 pInBuffer->frameCount = inBuffer.frameCount;
4408 pInBuffer->i16 = pInBuffer->mBuffer;
4409 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4410 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01004411 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004412 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004413 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004414 }
4415 }
4416 }
4417
4418 // Calling write() with a 0 length buffer, means that no more data will be written:
4419 // If no more buffers are pending, fill output track buffer to make sure it is started
4420 // by output mixer.
4421 if (frames == 0 && mBufferQueue.size() == 0) {
4422 if (mCblk->user < mCblk->frameCount) {
4423 frames = mCblk->frameCount - mCblk->user;
4424 pInBuffer = new Buffer;
4425 pInBuffer->mBuffer = new int16_t[frames * channelCount];
4426 pInBuffer->frameCount = frames;
4427 pInBuffer->i16 = pInBuffer->mBuffer;
4428 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4429 mBufferQueue.add(pInBuffer);
4430 } else if (mActive) {
4431 stop();
4432 }
4433 }
4434
4435 return outputBufferFull;
4436}
4437
4438status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4439{
4440 int active;
4441 status_t result;
4442 audio_track_cblk_t* cblk = mCblk;
4443 uint32_t framesReq = buffer->frameCount;
4444
Steve Block3856b092011-10-20 11:56:00 +01004445// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004446 buffer->frameCount = 0;
4447
4448 uint32_t framesAvail = cblk->framesAvailable();
4449
4450
4451 if (framesAvail == 0) {
4452 Mutex::Autolock _l(cblk->lock);
4453 goto start_loop_here;
4454 while (framesAvail == 0) {
4455 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004456 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004457 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004458 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004459 }
4460 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4461 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004462 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004463 }
4464 // read the server count again
4465 start_loop_here:
4466 framesAvail = cblk->framesAvailable_l();
4467 }
4468 }
4469
4470// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004471// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004472// }
4473
4474 if (framesReq > framesAvail) {
4475 framesReq = framesAvail;
4476 }
4477
4478 uint32_t u = cblk->user;
4479 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4480
4481 if (u + framesReq > bufferEnd) {
4482 framesReq = bufferEnd - u;
4483 }
4484
4485 buffer->frameCount = framesReq;
4486 buffer->raw = (void *)cblk->buffer(u);
4487 return NO_ERROR;
4488}
4489
4490
4491void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4492{
4493 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004494
4495 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004496 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004497 delete [] pBuffer->mBuffer;
4498 delete pBuffer;
4499 }
4500 mBufferQueue.clear();
4501}
4502
4503// ----------------------------------------------------------------------------
4504
4505AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4506 : RefBase(),
4507 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08004508 // 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 -07004509 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08004510 mPid(pid),
4511 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004512{
4513 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4514}
4515
4516// Client destructor must be called with AudioFlinger::mLock held
4517AudioFlinger::Client::~Client()
4518{
4519 mAudioFlinger->removeClient_l(mPid);
4520}
4521
Glenn Kasten435dbe62012-01-30 10:15:48 -08004522sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004523{
4524 return mMemoryDealer;
4525}
4526
John Grossman4ff14ba2012-02-08 16:37:41 -08004527// Reserve one of the limited slots for a timed audio track associated
4528// with this client
4529bool AudioFlinger::Client::reserveTimedTrack()
4530{
4531 const int kMaxTimedTracksPerClient = 4;
4532
4533 Mutex::Autolock _l(mTimedTrackLock);
4534
4535 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4536 ALOGW("can not create timed track - pid %d has exceeded the limit",
4537 mPid);
4538 return false;
4539 }
4540
4541 mTimedTrackCount++;
4542 return true;
4543}
4544
4545// Release a slot for a timed audio track
4546void AudioFlinger::Client::releaseTimedTrack()
4547{
4548 Mutex::Autolock _l(mTimedTrackLock);
4549 mTimedTrackCount--;
4550}
4551
Mathias Agopian65ab4712010-07-14 17:59:35 -07004552// ----------------------------------------------------------------------------
4553
4554AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4555 const sp<IAudioFlingerClient>& client,
4556 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004557 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004558{
4559}
4560
4561AudioFlinger::NotificationClient::~NotificationClient()
4562{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004563}
4564
4565void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4566{
4567 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08004568 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004569}
4570
4571// ----------------------------------------------------------------------------
4572
4573AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4574 : BnAudioTrack(),
4575 mTrack(track)
4576{
4577}
4578
4579AudioFlinger::TrackHandle::~TrackHandle() {
4580 // just stop the track on deletion, associated resources
4581 // will be freed from the main thread once all pending buffers have
4582 // been played. Unless it's not in the active track list, in which
4583 // case we free everything now...
4584 mTrack->destroy();
4585}
4586
Glenn Kasten90716c52012-01-26 13:40:12 -08004587sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4588 return mTrack->getCblk();
4589}
4590
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004591status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4592 return mTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004593}
4594
4595void AudioFlinger::TrackHandle::stop() {
4596 mTrack->stop();
4597}
4598
4599void AudioFlinger::TrackHandle::flush() {
4600 mTrack->flush();
4601}
4602
4603void AudioFlinger::TrackHandle::mute(bool e) {
4604 mTrack->mute(e);
4605}
4606
4607void AudioFlinger::TrackHandle::pause() {
4608 mTrack->pause();
4609}
4610
Mathias Agopian65ab4712010-07-14 17:59:35 -07004611status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4612{
4613 return mTrack->attachAuxEffect(EffectId);
4614}
4615
John Grossman4ff14ba2012-02-08 16:37:41 -08004616status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4617 sp<IMemory>* buffer) {
4618 if (!mTrack->isTimedTrack())
4619 return INVALID_OPERATION;
4620
4621 PlaybackThread::TimedTrack* tt =
4622 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4623 return tt->allocateTimedBuffer(size, buffer);
4624}
4625
4626status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4627 int64_t pts) {
4628 if (!mTrack->isTimedTrack())
4629 return INVALID_OPERATION;
4630
4631 PlaybackThread::TimedTrack* tt =
4632 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4633 return tt->queueTimedBuffer(buffer, pts);
4634}
4635
4636status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4637 const LinearTransform& xform, int target) {
4638
4639 if (!mTrack->isTimedTrack())
4640 return INVALID_OPERATION;
4641
4642 PlaybackThread::TimedTrack* tt =
4643 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4644 return tt->setMediaTimeTransform(
4645 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4646}
4647
Mathias Agopian65ab4712010-07-14 17:59:35 -07004648status_t AudioFlinger::TrackHandle::onTransact(
4649 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4650{
4651 return BnAudioTrack::onTransact(code, data, reply, flags);
4652}
4653
4654// ----------------------------------------------------------------------------
4655
4656sp<IAudioRecord> AudioFlinger::openRecord(
4657 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004658 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004659 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004660 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004661 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004662 int frameCount,
4663 uint32_t flags,
4664 int *sessionId,
4665 status_t *status)
4666{
4667 sp<RecordThread::RecordTrack> recordTrack;
4668 sp<RecordHandle> recordHandle;
4669 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004670 status_t lStatus;
4671 RecordThread *thread;
4672 size_t inFrameCount;
4673 int lSessionId;
4674
4675 // check calling permissions
4676 if (!recordingAllowed()) {
4677 lStatus = PERMISSION_DENIED;
4678 goto Exit;
4679 }
4680
4681 // add client to list
4682 { // scope for mLock
4683 Mutex::Autolock _l(mLock);
4684 thread = checkRecordThread_l(input);
4685 if (thread == NULL) {
4686 lStatus = BAD_VALUE;
4687 goto Exit;
4688 }
4689
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004690 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004691
4692 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004693 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004694 lSessionId = *sessionId;
4695 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004696 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004697 if (sessionId != NULL) {
4698 *sessionId = lSessionId;
4699 }
4700 }
4701 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004702 recordTrack = thread->createRecordTrack_l(client,
4703 sampleRate,
4704 format,
4705 channelMask,
4706 frameCount,
4707 flags,
4708 lSessionId,
4709 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004710 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004711 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004712 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4713 // destructor is called by the TrackBase destructor with mLock held
4714 client.clear();
4715 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004716 goto Exit;
4717 }
4718
4719 // return to handle to client
4720 recordHandle = new RecordHandle(recordTrack);
4721 lStatus = NO_ERROR;
4722
4723Exit:
4724 if (status) {
4725 *status = lStatus;
4726 }
4727 return recordHandle;
4728}
4729
4730// ----------------------------------------------------------------------------
4731
4732AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4733 : BnAudioRecord(),
4734 mRecordTrack(recordTrack)
4735{
4736}
4737
4738AudioFlinger::RecordHandle::~RecordHandle() {
4739 stop();
4740}
4741
Glenn Kasten90716c52012-01-26 13:40:12 -08004742sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4743 return mRecordTrack->getCblk();
4744}
4745
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004746status_t AudioFlinger::RecordHandle::start(pid_t tid) {
Steve Block3856b092011-10-20 11:56:00 +01004747 ALOGV("RecordHandle::start()");
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004748 return mRecordTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004749}
4750
4751void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004752 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004753 mRecordTrack->stop();
4754}
4755
Mathias Agopian65ab4712010-07-14 17:59:35 -07004756status_t AudioFlinger::RecordHandle::onTransact(
4757 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4758{
4759 return BnAudioRecord::onTransact(code, data, reply, flags);
4760}
4761
4762// ----------------------------------------------------------------------------
4763
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004764AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4765 AudioStreamIn *input,
4766 uint32_t sampleRate,
4767 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004768 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004769 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004770 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004771 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4772 // mRsmpInIndex and mInputBytes set by readInputParameters()
4773 mReqChannelCount(popcount(channels)),
4774 mReqSampleRate(sampleRate)
4775 // mBytesRead is only meaningful while active, and so is cleared in start()
4776 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004777{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004778 snprintf(mName, kNameLength, "AudioIn_%d", id);
4779
Mathias Agopian65ab4712010-07-14 17:59:35 -07004780 readInputParameters();
4781}
4782
4783
4784AudioFlinger::RecordThread::~RecordThread()
4785{
4786 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004787 delete mResampler;
4788 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004789}
4790
4791void AudioFlinger::RecordThread::onFirstRef()
4792{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004793 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004794}
4795
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004796status_t AudioFlinger::RecordThread::readyToRun()
4797{
4798 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004799 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004800 return status;
4801}
4802
Mathias Agopian65ab4712010-07-14 17:59:35 -07004803bool AudioFlinger::RecordThread::threadLoop()
4804{
4805 AudioBufferProvider::Buffer buffer;
4806 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004807 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004808
Eric Laurent44d98482010-09-30 16:12:31 -07004809 nsecs_t lastWarning = 0;
4810
Eric Laurentfeb0db62011-07-22 09:04:31 -07004811 acquireWakeLock();
4812
Mathias Agopian65ab4712010-07-14 17:59:35 -07004813 // start recording
4814 while (!exitPending()) {
4815
4816 processConfigEvents();
4817
4818 { // scope for mLock
4819 Mutex::Autolock _l(mLock);
4820 checkForNewParameters_l();
4821 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4822 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004823 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004824 mStandby = true;
4825 }
4826
4827 if (exitPending()) break;
4828
Eric Laurentfeb0db62011-07-22 09:04:31 -07004829 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004830 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004831 // go to sleep
4832 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004833 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004834 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004835 continue;
4836 }
4837 if (mActiveTrack != 0) {
4838 if (mActiveTrack->mState == TrackBase::PAUSING) {
4839 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004840 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004841 mStandby = true;
4842 }
4843 mActiveTrack.clear();
4844 mStartStopCond.broadcast();
4845 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4846 if (mReqChannelCount != mActiveTrack->channelCount()) {
4847 mActiveTrack.clear();
4848 mStartStopCond.broadcast();
4849 } else if (mBytesRead != 0) {
4850 // record start succeeds only if first read from audio input
4851 // succeeds
4852 if (mBytesRead > 0) {
4853 mActiveTrack->mState = TrackBase::ACTIVE;
4854 } else {
4855 mActiveTrack.clear();
4856 }
4857 mStartStopCond.broadcast();
4858 }
4859 mStandby = false;
4860 }
4861 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004862 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004863 }
4864
4865 if (mActiveTrack != 0) {
4866 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4867 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004868 unlockEffectChains(effectChains);
4869 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004870 continue;
4871 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004872 for (size_t i = 0; i < effectChains.size(); i ++) {
4873 effectChains[i]->process_l();
4874 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004875
Mathias Agopian65ab4712010-07-14 17:59:35 -07004876 buffer.frameCount = mFrameCount;
John Grossman4ff14ba2012-02-08 16:37:41 -08004877 if (CC_LIKELY(mActiveTrack->getNextBuffer(
4878 &buffer, AudioBufferProvider::kInvalidPTS) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004879 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004880 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004881 // no resampling
4882 while (framesOut) {
4883 size_t framesIn = mFrameCount - mRsmpInIndex;
4884 if (framesIn) {
4885 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4886 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4887 if (framesIn > framesOut)
4888 framesIn = framesOut;
4889 mRsmpInIndex += framesIn;
4890 framesOut -= framesIn;
4891 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004892 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004893 memcpy(dst, src, framesIn * mFrameSize);
4894 } else {
4895 int16_t *src16 = (int16_t *)src;
4896 int16_t *dst16 = (int16_t *)dst;
4897 if (mChannelCount == 1) {
4898 while (framesIn--) {
4899 *dst16++ = *src16;
4900 *dst16++ = *src16++;
4901 }
4902 } else {
4903 while (framesIn--) {
4904 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4905 src16 += 2;
4906 }
4907 }
4908 }
4909 }
4910 if (framesOut && mFrameCount == mRsmpInIndex) {
4911 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004912 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004913 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004914 framesOut = 0;
4915 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004916 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004917 mRsmpInIndex = 0;
4918 }
4919 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004920 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004921 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4922 // Force input into standby so that it tries to
4923 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004924 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004925 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004926 }
4927 mRsmpInIndex = mFrameCount;
4928 framesOut = 0;
4929 buffer.frameCount = 0;
4930 }
4931 }
4932 }
4933 } else {
4934 // resampling
4935
4936 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4937 // alter output frame count as if we were expecting stereo samples
4938 if (mChannelCount == 1 && mReqChannelCount == 1) {
4939 framesOut >>= 1;
4940 }
4941 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4942 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4943 // are 32 bit aligned which should be always true.
4944 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004945 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004946 // the resampler always outputs stereo samples: do post stereo to mono conversion
4947 int16_t *src = (int16_t *)mRsmpOutBuffer;
4948 int16_t *dst = buffer.i16;
4949 while (framesOut--) {
4950 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4951 src += 2;
4952 }
4953 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004954 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004955 }
4956
4957 }
4958 mActiveTrack->releaseBuffer(&buffer);
4959 mActiveTrack->overflow();
4960 }
4961 // client isn't retrieving buffers fast enough
4962 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004963 if (!mActiveTrack->setOverflow()) {
4964 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004965 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004966 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004967 lastWarning = now;
4968 }
4969 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004970 // Release the processor for a while before asking for a new buffer.
4971 // This will give the application more chance to read from the buffer and
4972 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004973 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004974 }
4975 }
Eric Laurentec437d82011-07-26 20:54:46 -07004976 // enable changes in effect chain
4977 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004978 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004979 }
4980
4981 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004982 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004983 }
4984 mActiveTrack.clear();
4985
4986 mStartStopCond.broadcast();
4987
Eric Laurentfeb0db62011-07-22 09:04:31 -07004988 releaseWakeLock();
4989
Steve Block3856b092011-10-20 11:56:00 +01004990 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004991 return false;
4992}
4993
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004994
4995sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4996 const sp<AudioFlinger::Client>& client,
4997 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004998 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004999 int channelMask,
5000 int frameCount,
5001 uint32_t flags,
5002 int sessionId,
5003 status_t *status)
5004{
5005 sp<RecordTrack> track;
5006 status_t lStatus;
5007
5008 lStatus = initCheck();
5009 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005010 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005011 goto Exit;
5012 }
5013
5014 { // scope for mLock
5015 Mutex::Autolock _l(mLock);
5016
5017 track = new RecordTrack(this, client, sampleRate,
5018 format, channelMask, frameCount, flags, sessionId);
5019
Glenn Kasten7378ca52012-01-20 13:44:40 -08005020 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005021 lStatus = NO_MEMORY;
5022 goto Exit;
5023 }
5024
5025 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005026 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5027 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005028 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005029 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5030 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005031 }
5032 lStatus = NO_ERROR;
5033
5034Exit:
5035 if (status) {
5036 *status = lStatus;
5037 }
5038 return track;
5039}
5040
Glenn Kasten6dbc1352012-02-02 10:56:47 -08005041status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005042{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08005043 ALOGV("RecordThread::start tid=%d", tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005044 sp <ThreadBase> strongMe = this;
5045 status_t status = NO_ERROR;
5046 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005047 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005048 if (mActiveTrack != 0) {
5049 if (recordTrack != mActiveTrack.get()) {
5050 status = -EBUSY;
5051 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5052 mActiveTrack->mState = TrackBase::ACTIVE;
5053 }
5054 return status;
5055 }
5056
5057 recordTrack->mState = TrackBase::IDLE;
5058 mActiveTrack = recordTrack;
5059 mLock.unlock();
5060 status_t status = AudioSystem::startInput(mId);
5061 mLock.lock();
5062 if (status != NO_ERROR) {
5063 mActiveTrack.clear();
5064 return status;
5065 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005066 mRsmpInIndex = mFrameCount;
5067 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005068 if (mResampler != NULL) {
5069 mResampler->reset();
5070 }
5071 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005072 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005073 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005074 mWaitWorkCV.signal();
5075 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005076 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005077 mActiveTrack.clear();
5078 status = INVALID_OPERATION;
5079 goto startError;
5080 }
5081 mStartStopCond.wait(mLock);
5082 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005083 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005084 status = BAD_VALUE;
5085 goto startError;
5086 }
Steve Block3856b092011-10-20 11:56:00 +01005087 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005088 return status;
5089 }
5090startError:
5091 AudioSystem::stopInput(mId);
5092 return status;
5093}
5094
5095void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005096 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005097 sp <ThreadBase> strongMe = this;
5098 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005099 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005100 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5101 mActiveTrack->mState = TrackBase::PAUSING;
5102 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005103 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005104 return;
5105 }
5106 mStartStopCond.wait(mLock);
5107 // if we have been restarted, recordTrack == mActiveTrack.get() here
5108 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5109 mLock.unlock();
5110 AudioSystem::stopInput(mId);
5111 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005112 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005113 }
5114 }
5115 }
5116}
5117
5118status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5119{
5120 const size_t SIZE = 256;
5121 char buffer[SIZE];
5122 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005123
5124 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5125 result.append(buffer);
5126
5127 if (mActiveTrack != 0) {
5128 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005129 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005130 mActiveTrack->dump(buffer, SIZE);
5131 result.append(buffer);
5132
5133 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5134 result.append(buffer);
5135 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5136 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005137 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005138 result.append(buffer);
5139 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5140 result.append(buffer);
5141 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5142 result.append(buffer);
5143
5144
5145 } else {
5146 result.append("No record client\n");
5147 }
5148 write(fd, result.string(), result.size());
5149
5150 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005151 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005152
5153 return NO_ERROR;
5154}
5155
John Grossman4ff14ba2012-02-08 16:37:41 -08005156status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005157{
5158 size_t framesReq = buffer->frameCount;
5159 size_t framesReady = mFrameCount - mRsmpInIndex;
5160 int channelCount;
5161
5162 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005163 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005164 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005165 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005166 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5167 // Force input into standby so that it tries to
5168 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005169 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005170 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005171 }
Glenn Kastene0feee32011-12-13 11:53:26 -08005172 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005173 buffer->frameCount = 0;
5174 return NOT_ENOUGH_DATA;
5175 }
5176 mRsmpInIndex = 0;
5177 framesReady = mFrameCount;
5178 }
5179
5180 if (framesReq > framesReady) {
5181 framesReq = framesReady;
5182 }
5183
5184 if (mChannelCount == 1 && mReqChannelCount == 2) {
5185 channelCount = 1;
5186 } else {
5187 channelCount = 2;
5188 }
5189 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5190 buffer->frameCount = framesReq;
5191 return NO_ERROR;
5192}
5193
5194void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5195{
5196 mRsmpInIndex += buffer->frameCount;
5197 buffer->frameCount = 0;
5198}
5199
5200bool AudioFlinger::RecordThread::checkForNewParameters_l()
5201{
5202 bool reconfig = false;
5203
5204 while (!mNewParameters.isEmpty()) {
5205 status_t status = NO_ERROR;
5206 String8 keyValuePair = mNewParameters[0];
5207 AudioParameter param = AudioParameter(keyValuePair);
5208 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08005209 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005210 int reqSamplingRate = mReqSampleRate;
5211 int reqChannelCount = mReqChannelCount;
5212
5213 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5214 reqSamplingRate = value;
5215 reconfig = true;
5216 }
5217 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08005218 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005219 reconfig = true;
5220 }
5221 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005222 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005223 reconfig = true;
5224 }
5225 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5226 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08005227 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005228 // if frame count is changed after track creation
5229 if (mActiveTrack != 0) {
5230 status = INVALID_OPERATION;
5231 } else {
5232 reconfig = true;
5233 }
5234 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005235 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5236 // forward device change to effects that have requested to be
5237 // aware of attached audio device.
5238 for (size_t i = 0; i < mEffectChains.size(); i++) {
5239 mEffectChains[i]->setDevice_l(value);
5240 }
5241 // store input device and output device but do not forward output device to audio HAL.
5242 // Note that status is ignored by the caller for output device
5243 // (see AudioFlinger::setParameters()
5244 if (value & AUDIO_DEVICE_OUT_ALL) {
5245 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5246 status = BAD_VALUE;
5247 } else {
5248 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07005249 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5250 if (mTrack != NULL) {
5251 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005252 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005253 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5254 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5255 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005256 }
5257 mDevice |= (uint32_t)value;
5258 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005259 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005260 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005261 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005262 mInput->stream->common.standby(&mInput->stream->common);
5263 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005264 }
5265 if (reconfig) {
5266 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005267 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005268 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005269 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
5270 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005271 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005272 status = NO_ERROR;
5273 }
5274 if (status == NO_ERROR) {
5275 readInputParameters();
5276 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5277 }
5278 }
5279 }
5280
5281 mNewParameters.removeAt(0);
5282
5283 mParamStatus = status;
5284 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07005285 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5286 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08005287 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005288 }
5289 return reconfig;
5290}
5291
5292String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5293{
Dima Zavinfce7a472011-04-19 22:30:36 -07005294 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005295 String8 out_s8 = String8();
5296
5297 Mutex::Autolock _l(mLock);
5298 if (initCheck() != NO_ERROR) {
5299 return out_s8;
5300 }
Dima Zavinfce7a472011-04-19 22:30:36 -07005301
Dima Zavin799a70e2011-04-18 16:57:27 -07005302 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07005303 out_s8 = String8(s);
5304 free(s);
5305 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005306}
5307
5308void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5309 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08005310 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005311
5312 switch (event) {
5313 case AudioSystem::INPUT_OPENED:
5314 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005315 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005316 desc.samplingRate = mSampleRate;
5317 desc.format = mFormat;
5318 desc.frameCount = mFrameCount;
5319 desc.latency = 0;
5320 param2 = &desc;
5321 break;
5322
5323 case AudioSystem::INPUT_CLOSED:
5324 default:
5325 break;
5326 }
5327 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5328}
5329
5330void AudioFlinger::RecordThread::readInputParameters()
5331{
Glenn Kastene9dd0172012-01-27 18:08:45 -08005332 delete mRsmpInBuffer;
5333 // mRsmpInBuffer is always assigned a new[] below
5334 delete mRsmpOutBuffer;
5335 mRsmpOutBuffer = NULL;
5336 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08005337 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005338
Dima Zavin799a70e2011-04-18 16:57:27 -07005339 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005340 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5341 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07005342 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08005343 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07005344 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005345 mFrameCount = mInputBytes / mFrameSize;
5346 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5347
5348 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
5349 {
5350 int channelCount;
5351 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5352 // stereo to mono post process as the resampler always outputs stereo.
5353 if (mChannelCount == 1 && mReqChannelCount == 2) {
5354 channelCount = 1;
5355 } else {
5356 channelCount = 2;
5357 }
5358 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5359 mResampler->setSampleRate(mSampleRate);
5360 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5361 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5362
5363 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5364 if (mChannelCount == 1 && mReqChannelCount == 1) {
5365 mFrameCount >>= 1;
5366 }
5367
5368 }
5369 mRsmpInIndex = mFrameCount;
5370}
5371
5372unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5373{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005374 Mutex::Autolock _l(mLock);
5375 if (initCheck() != NO_ERROR) {
5376 return 0;
5377 }
5378
Dima Zavin799a70e2011-04-18 16:57:27 -07005379 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005380}
5381
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005382uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5383{
5384 Mutex::Autolock _l(mLock);
5385 uint32_t result = 0;
5386 if (getEffectChain_l(sessionId) != 0) {
5387 result = EFFECT_SESSION;
5388 }
5389
5390 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5391 result |= TRACK_SESSION;
5392 }
5393
5394 return result;
5395}
5396
Eric Laurent59bd0da2011-08-01 09:52:20 -07005397AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5398{
5399 Mutex::Autolock _l(mLock);
5400 return mTrack;
5401}
5402
Glenn Kastenaed850d2012-01-26 09:46:34 -08005403AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005404{
5405 Mutex::Autolock _l(mLock);
5406 return mInput;
5407}
5408
5409AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5410{
5411 Mutex::Autolock _l(mLock);
5412 AudioStreamIn *input = mInput;
5413 mInput = NULL;
5414 return input;
5415}
5416
5417// this method must always be called either with ThreadBase mLock held or inside the thread loop
5418audio_stream_t* AudioFlinger::RecordThread::stream()
5419{
5420 if (mInput == NULL) {
5421 return NULL;
5422 }
5423 return &mInput->stream->common;
5424}
5425
5426
Mathias Agopian65ab4712010-07-14 17:59:35 -07005427// ----------------------------------------------------------------------------
5428
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005429audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005430 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005431 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005432 uint32_t *pChannels,
5433 uint32_t *pLatencyMs,
5434 uint32_t flags)
5435{
5436 status_t status;
5437 PlaybackThread *thread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005438 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005439 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005440 uint32_t channels = pChannels ? *pChannels : 0;
5441 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07005442 audio_stream_out_t *outStream;
5443 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005444
Steve Block3856b092011-10-20 11:56:00 +01005445 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07005446 pDevices ? *pDevices : 0,
5447 samplingRate,
5448 format,
5449 channels,
5450 flags);
5451
5452 if (pDevices == NULL || *pDevices == 0) {
5453 return 0;
5454 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005455
Mathias Agopian65ab4712010-07-14 17:59:35 -07005456 Mutex::Autolock _l(mLock);
5457
Dima Zavin799a70e2011-04-18 16:57:27 -07005458 outHwDev = findSuitableHwDev_l(*pDevices);
5459 if (outHwDev == NULL)
5460 return 0;
5461
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005462 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Glenn Kasten58f30212012-01-12 12:27:51 -08005463 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005464 &channels, &samplingRate, &outStream);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005465 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01005466 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005467 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005468 samplingRate,
5469 format,
5470 channels,
5471 status);
5472
Dima Zavin799a70e2011-04-18 16:57:27 -07005473 if (outStream != NULL) {
5474 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005475 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07005476
Dima Zavinfce7a472011-04-19 22:30:36 -07005477 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5478 (format != AUDIO_FORMAT_PCM_16_BIT) ||
5479 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005480 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005481 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005482 } else {
5483 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005484 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005485 }
5486 mPlaybackThreads.add(id, thread);
5487
Glenn Kastena0d68332012-01-27 16:47:15 -08005488 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5489 if (pFormat != NULL) *pFormat = format;
5490 if (pChannels != NULL) *pChannels = channels;
5491 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005492
5493 // notify client processes of the new output creation
5494 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5495 return id;
5496 }
5497
5498 return 0;
5499}
5500
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005501audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
5502 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005503{
5504 Mutex::Autolock _l(mLock);
5505 MixerThread *thread1 = checkMixerThread_l(output1);
5506 MixerThread *thread2 = checkMixerThread_l(output2);
5507
5508 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005509 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005510 return 0;
5511 }
5512
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005513 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005514 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5515 thread->addOutputTrack(thread2);
5516 mPlaybackThreads.add(id, thread);
5517 // notify client processes of the new output creation
5518 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5519 return id;
5520}
5521
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005522status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005523{
5524 // keep strong reference on the playback thread so that
5525 // it is not destroyed while exit() is executed
5526 sp <PlaybackThread> thread;
5527 {
5528 Mutex::Autolock _l(mLock);
5529 thread = checkPlaybackThread_l(output);
5530 if (thread == NULL) {
5531 return BAD_VALUE;
5532 }
5533
Steve Block3856b092011-10-20 11:56:00 +01005534 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005535
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005536 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005537 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005538 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005539 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5540 dupThread->removeOutputTrack((MixerThread *)thread.get());
5541 }
5542 }
5543 }
Glenn Kastena1117922012-01-26 10:53:32 -08005544 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005545 mPlaybackThreads.removeItem(output);
5546 }
5547 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005548 // The thread entity (active unit of execution) is no longer running here,
5549 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005550
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005551 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005552 AudioStreamOut *out = thread->clearOutput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005553 assert(out != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005554 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005555 out->hwDev->close_output_stream(out->hwDev, out->stream);
5556 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005557 }
5558 return NO_ERROR;
5559}
5560
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005561status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005562{
5563 Mutex::Autolock _l(mLock);
5564 PlaybackThread *thread = checkPlaybackThread_l(output);
5565
5566 if (thread == NULL) {
5567 return BAD_VALUE;
5568 }
5569
Steve Block3856b092011-10-20 11:56:00 +01005570 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005571 thread->suspend();
5572
5573 return NO_ERROR;
5574}
5575
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005576status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005577{
5578 Mutex::Autolock _l(mLock);
5579 PlaybackThread *thread = checkPlaybackThread_l(output);
5580
5581 if (thread == NULL) {
5582 return BAD_VALUE;
5583 }
5584
Steve Block3856b092011-10-20 11:56:00 +01005585 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005586
5587 thread->restore();
5588
5589 return NO_ERROR;
5590}
5591
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005592audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005593 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005594 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005595 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005596 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005597{
5598 status_t status;
5599 RecordThread *thread = NULL;
5600 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005601 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005602 uint32_t channels = pChannels ? *pChannels : 0;
5603 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005604 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005605 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005606 audio_stream_in_t *inStream;
5607 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005608
5609 if (pDevices == NULL || *pDevices == 0) {
5610 return 0;
5611 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005612
Mathias Agopian65ab4712010-07-14 17:59:35 -07005613 Mutex::Autolock _l(mLock);
5614
Dima Zavin799a70e2011-04-18 16:57:27 -07005615 inHwDev = findSuitableHwDev_l(*pDevices);
5616 if (inHwDev == NULL)
5617 return 0;
5618
Glenn Kasten58f30212012-01-12 12:27:51 -08005619 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005620 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005621 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005622 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005623 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005624 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005625 samplingRate,
5626 format,
5627 channels,
5628 acoustics,
5629 status);
5630
5631 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5632 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5633 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005634 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005635 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005636 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005637 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005638 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005639 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005640 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005641 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005642 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005643 }
5644
Dima Zavin799a70e2011-04-18 16:57:27 -07005645 if (inStream != NULL) {
5646 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5647
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005648 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005649 // Start record thread
5650 // RecorThread require both input and output device indication to forward to audio
5651 // pre processing modules
5652 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5653 thread = new RecordThread(this,
5654 input,
5655 reqSamplingRate,
5656 reqChannels,
5657 id,
5658 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005659 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005660 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005661 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5662 if (pFormat != NULL) *pFormat = format;
5663 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005664
Dima Zavin799a70e2011-04-18 16:57:27 -07005665 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005666
5667 // notify client processes of the new input creation
5668 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5669 return id;
5670 }
5671
5672 return 0;
5673}
5674
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005675status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005676{
5677 // keep strong reference on the record thread so that
5678 // it is not destroyed while exit() is executed
5679 sp <RecordThread> thread;
5680 {
5681 Mutex::Autolock _l(mLock);
5682 thread = checkRecordThread_l(input);
5683 if (thread == NULL) {
5684 return BAD_VALUE;
5685 }
5686
Steve Block3856b092011-10-20 11:56:00 +01005687 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08005688 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005689 mRecordThreads.removeItem(input);
5690 }
5691 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005692 // The thread entity (active unit of execution) is no longer running here,
5693 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005694
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005695 AudioStreamIn *in = thread->clearInput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005696 assert(in != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005697 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005698 in->hwDev->close_input_stream(in->hwDev, in->stream);
5699 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005700
5701 return NO_ERROR;
5702}
5703
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005704status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005705{
5706 Mutex::Autolock _l(mLock);
5707 MixerThread *dstThread = checkMixerThread_l(output);
5708 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005709 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005710 return BAD_VALUE;
5711 }
5712
Steve Block3856b092011-10-20 11:56:00 +01005713 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005714 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5715
Eric Laurent9f6530f2011-08-30 10:18:54 -07005716 dstThread->setStreamValid(stream, true);
5717
Mathias Agopian65ab4712010-07-14 17:59:35 -07005718 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5719 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08005720 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005721 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005722 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005723 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005724 }
Eric Laurentde070132010-07-13 04:45:46 -07005725 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005726
5727 return NO_ERROR;
5728}
5729
5730
5731int AudioFlinger::newAudioSessionId()
5732{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005733 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005734}
5735
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005736void AudioFlinger::acquireAudioSessionId(int audioSession)
5737{
5738 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005739 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005740 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005741 size_t num = mAudioSessionRefs.size();
5742 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005743 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5744 if (ref->sessionid == audioSession && ref->pid == caller) {
5745 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005746 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005747 return;
5748 }
5749 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005750 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5751 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005752}
5753
5754void AudioFlinger::releaseAudioSessionId(int audioSession)
5755{
5756 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005757 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005758 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005759 size_t num = mAudioSessionRefs.size();
5760 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005761 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5762 if (ref->sessionid == audioSession && ref->pid == caller) {
5763 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005764 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005765 if (ref->cnt == 0) {
5766 mAudioSessionRefs.removeAt(i);
5767 delete ref;
5768 purgeStaleEffects_l();
5769 }
5770 return;
5771 }
5772 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005773 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005774}
5775
5776void AudioFlinger::purgeStaleEffects_l() {
5777
Steve Block3856b092011-10-20 11:56:00 +01005778 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005779
5780 Vector< sp<EffectChain> > chains;
5781
5782 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5783 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5784 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5785 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005786 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5787 chains.push(ec);
5788 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005789 }
5790 }
5791 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5792 sp<RecordThread> t = mRecordThreads.valueAt(i);
5793 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5794 sp<EffectChain> ec = t->mEffectChains[j];
5795 chains.push(ec);
5796 }
5797 }
5798
5799 for (size_t i = 0; i < chains.size(); i++) {
5800 sp<EffectChain> ec = chains[i];
5801 int sessionid = ec->sessionId();
5802 sp<ThreadBase> t = ec->mThread.promote();
5803 if (t == 0) {
5804 continue;
5805 }
5806 size_t numsessionrefs = mAudioSessionRefs.size();
5807 bool found = false;
5808 for (size_t k = 0; k < numsessionrefs; k++) {
5809 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5810 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005811 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005812 sessionid, ref->pid, ref->cnt);
5813 found = true;
5814 break;
5815 }
5816 }
5817 if (!found) {
5818 // remove all effects from the chain
5819 while (ec->mEffects.size()) {
5820 sp<EffectModule> effect = ec->mEffects[0];
5821 effect->unPin();
5822 Mutex::Autolock _l (t->mLock);
5823 t->removeEffect_l(effect);
5824 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5825 sp<EffectHandle> handle = effect->mHandles[j].promote();
5826 if (handle != 0) {
5827 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005828 if (handle->mHasControl && handle->mEnabled) {
5829 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5830 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005831 }
5832 }
5833 AudioSystem::unregisterEffect(effect->id());
5834 }
5835 }
5836 }
5837 return;
5838}
5839
Mathias Agopian65ab4712010-07-14 17:59:35 -07005840// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005841AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005842{
Glenn Kastena1117922012-01-26 10:53:32 -08005843 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005844}
5845
5846// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005847AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005848{
5849 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08005850 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005851}
5852
5853// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005854AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005855{
Glenn Kastena1117922012-01-26 10:53:32 -08005856 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005857}
5858
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005859uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005860{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005861 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005862}
5863
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005864AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5865{
5866 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5867 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005868 AudioStreamOut *output = thread->getOutput();
5869 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005870 return thread;
5871 }
5872 }
5873 return NULL;
5874}
5875
5876uint32_t AudioFlinger::primaryOutputDevice_l()
5877{
5878 PlaybackThread *thread = primaryPlaybackThread_l();
5879
5880 if (thread == NULL) {
5881 return 0;
5882 }
5883
5884 return thread->device();
5885}
5886
5887
Mathias Agopian65ab4712010-07-14 17:59:35 -07005888// ----------------------------------------------------------------------------
5889// Effect management
5890// ----------------------------------------------------------------------------
5891
5892
Glenn Kastenf587ba52012-01-26 16:25:10 -08005893status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005894{
5895 Mutex::Autolock _l(mLock);
5896 return EffectQueryNumberEffects(numEffects);
5897}
5898
Glenn Kastenf587ba52012-01-26 16:25:10 -08005899status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005900{
5901 Mutex::Autolock _l(mLock);
5902 return EffectQueryEffect(index, descriptor);
5903}
5904
Glenn Kasten5e92a782012-01-30 07:40:52 -08005905status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08005906 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005907{
5908 Mutex::Autolock _l(mLock);
5909 return EffectGetDescriptor(pUuid, descriptor);
5910}
5911
5912
Mathias Agopian65ab4712010-07-14 17:59:35 -07005913sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5914 effect_descriptor_t *pDesc,
5915 const sp<IEffectClient>& effectClient,
5916 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005917 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005918 int sessionId,
5919 status_t *status,
5920 int *id,
5921 int *enabled)
5922{
5923 status_t lStatus = NO_ERROR;
5924 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005925 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005926
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005927 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005928 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005929
5930 if (pDesc == NULL) {
5931 lStatus = BAD_VALUE;
5932 goto Exit;
5933 }
5934
Eric Laurent84e9a102010-09-23 16:10:16 -07005935 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005936 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005937 lStatus = PERMISSION_DENIED;
5938 goto Exit;
5939 }
5940
Dima Zavinfce7a472011-04-19 22:30:36 -07005941 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005942 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08005943 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005944 lStatus = PERMISSION_DENIED;
5945 goto Exit;
5946 }
5947
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005948 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005949 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005950 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005951 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005952 lStatus = BAD_VALUE;
5953 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005954 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005955 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005956 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005957 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005958 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005959 }
5960 }
5961
Mathias Agopian65ab4712010-07-14 17:59:35 -07005962 {
5963 Mutex::Autolock _l(mLock);
5964
Mathias Agopian65ab4712010-07-14 17:59:35 -07005965
5966 if (!EffectIsNullUuid(&pDesc->uuid)) {
5967 // if uuid is specified, request effect descriptor
5968 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5969 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005970 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005971 goto Exit;
5972 }
5973 } else {
5974 // if uuid is not specified, look for an available implementation
5975 // of the required type in effect factory
5976 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005977 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005978 lStatus = BAD_VALUE;
5979 goto Exit;
5980 }
5981 uint32_t numEffects = 0;
5982 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005983 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005984 bool found = false;
5985
5986 lStatus = EffectQueryNumberEffects(&numEffects);
5987 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005988 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005989 goto Exit;
5990 }
5991 for (uint32_t i = 0; i < numEffects; i++) {
5992 lStatus = EffectQueryEffect(i, &desc);
5993 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005994 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005995 continue;
5996 }
5997 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5998 // If matching type found save effect descriptor. If the session is
5999 // 0 and the effect is not auxiliary, continue enumeration in case
6000 // an auxiliary version of this effect type is available
6001 found = true;
6002 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07006003 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006004 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6005 break;
6006 }
6007 }
6008 }
6009 if (!found) {
6010 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00006011 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006012 goto Exit;
6013 }
6014 // For same effect type, chose auxiliary version over insert version if
6015 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07006016 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006017 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
6018 memcpy(&desc, &d, sizeof(effect_descriptor_t));
6019 }
6020 }
6021
6022 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07006023 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006024 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6025 lStatus = INVALID_OPERATION;
6026 goto Exit;
6027 }
6028
Eric Laurent59255e42011-07-27 19:49:51 -07006029 // check recording permission for visualizer
6030 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
6031 !recordingAllowed()) {
6032 lStatus = PERMISSION_DENIED;
6033 goto Exit;
6034 }
6035
Mathias Agopian65ab4712010-07-14 17:59:35 -07006036 // return effect descriptor
6037 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
6038
6039 // If output is not specified try to find a matching audio session ID in one of the
6040 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07006041 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
6042 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006043 // Note: io is never 0 when creating an effect on an input
6044 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006045 // look for the thread where the specified audio session is present
6046 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6047 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006048 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07006049 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07006050 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006051 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006052 if (io == 0) {
6053 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6054 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6055 io = mRecordThreads.keyAt(i);
6056 break;
6057 }
6058 }
6059 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006060 // If no output thread contains the requested session ID, default to
6061 // first output. The effect chain will be moved to the correct output
6062 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006063 if (io == 0 && mPlaybackThreads.size()) {
6064 io = mPlaybackThreads.keyAt(0);
6065 }
Steve Block3856b092011-10-20 11:56:00 +01006066 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006067 }
6068 ThreadBase *thread = checkRecordThread_l(io);
6069 if (thread == NULL) {
6070 thread = checkPlaybackThread_l(io);
6071 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00006072 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006073 lStatus = BAD_VALUE;
6074 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07006075 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006076 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006077
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006078 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006079
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006080 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07006081 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6082 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006083 if (handle != 0 && id != NULL) {
6084 *id = handle->id();
6085 }
6086 }
6087
6088Exit:
6089 if(status) {
6090 *status = lStatus;
6091 }
6092 return handle;
6093}
6094
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006095status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
6096 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07006097{
Steve Block3856b092011-10-20 11:56:00 +01006098 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07006099 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006100 Mutex::Autolock _l(mLock);
6101 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006102 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006103 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006104 }
Eric Laurentde070132010-07-13 04:45:46 -07006105 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6106 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006107 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006108 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006109 }
Eric Laurentde070132010-07-13 04:45:46 -07006110 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6111 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006112 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006113 return BAD_VALUE;
6114 }
6115
6116 Mutex::Autolock _dl(dstThread->mLock);
6117 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07006118 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07006119
Mathias Agopian65ab4712010-07-14 17:59:35 -07006120 return NO_ERROR;
6121}
6122
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006123// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07006124status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07006125 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07006126 AudioFlinger::PlaybackThread *dstThread,
6127 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07006128{
Steve Block3856b092011-10-20 11:56:00 +01006129 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006130 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07006131
Eric Laurent59255e42011-07-27 19:49:51 -07006132 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006133 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006134 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006135 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07006136 return INVALID_OPERATION;
6137 }
6138
Eric Laurent39e94f82010-07-28 01:32:47 -07006139 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07006140 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07006141 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07006142 // removed.
6143 srcThread->removeEffectChain_l(chain);
6144
6145 // transfer all effects one by one so that new effect chain is created on new thread with
6146 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006147 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07006148 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006149 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07006150 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6151 while (effect != 0) {
6152 srcThread->removeEffect_l(effect);
6153 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07006154 // removeEffect_l() has stopped the effect if it was active so it must be restarted
6155 if (effect->state() == EffectModule::ACTIVE ||
6156 effect->state() == EffectModule::STOPPING) {
6157 effect->start();
6158 }
Eric Laurent39e94f82010-07-28 01:32:47 -07006159 // if the move request is not received from audio policy manager, the effect must be
6160 // re-registered with the new strategy and output
6161 if (dstChain == 0) {
6162 dstChain = effect->chain().promote();
6163 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006164 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07006165 srcThread->addEffect_l(effect);
6166 return NO_INIT;
6167 }
6168 strategy = dstChain->strategy();
6169 }
6170 if (reRegister) {
6171 AudioSystem::unregisterEffect(effect->id());
6172 AudioSystem::registerEffect(&effect->desc(),
6173 dstOutput,
6174 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07006175 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07006176 effect->id());
6177 }
Eric Laurentde070132010-07-13 04:45:46 -07006178 effect = chain->getEffectFromId_l(0);
6179 }
6180
6181 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006182}
6183
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006184
Mathias Agopian65ab4712010-07-14 17:59:35 -07006185// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006186sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07006187 const sp<AudioFlinger::Client>& client,
6188 const sp<IEffectClient>& effectClient,
6189 int32_t priority,
6190 int sessionId,
6191 effect_descriptor_t *desc,
6192 int *enabled,
6193 status_t *status
6194 )
6195{
6196 sp<EffectModule> effect;
6197 sp<EffectHandle> handle;
6198 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006199 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07006200 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006201 bool effectCreated = false;
6202 bool effectRegistered = false;
6203
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006204 lStatus = initCheck();
6205 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006206 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006207 goto Exit;
6208 }
6209
6210 // Do not allow effects with session ID 0 on direct output or duplicating threads
6211 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07006212 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006213 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07006214 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006215 lStatus = BAD_VALUE;
6216 goto Exit;
6217 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006218 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08006219 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006220 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006221 desc->name, desc->flags, mType);
6222 lStatus = BAD_VALUE;
6223 goto Exit;
6224 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006225
Steve Block3856b092011-10-20 11:56:00 +01006226 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006227
6228 { // scope for mLock
6229 Mutex::Autolock _l(mLock);
6230
6231 // check for existing effect chain with the requested audio session
6232 chain = getEffectChain_l(sessionId);
6233 if (chain == 0) {
6234 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006235 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006236 chain = new EffectChain(this, sessionId);
6237 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07006238 chain->setStrategy(getStrategyForSession_l(sessionId));
6239 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006240 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07006241 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006242 }
6243
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08006244 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006245
6246 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006247 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006248 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07006249 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006250 if (lStatus != NO_ERROR) {
6251 goto Exit;
6252 }
6253 effectRegistered = true;
6254 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07006255 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006256 lStatus = effect->status();
6257 if (lStatus != NO_ERROR) {
6258 goto Exit;
6259 }
Eric Laurentcab11242010-07-15 12:50:15 -07006260 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006261 if (lStatus != NO_ERROR) {
6262 goto Exit;
6263 }
6264 effectCreated = true;
6265
6266 effect->setDevice(mDevice);
6267 effect->setMode(mAudioFlinger->getMode());
6268 }
6269 // create effect handle and connect it to effect module
6270 handle = new EffectHandle(effect, client, effectClient, priority);
6271 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08006272 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006273 *enabled = (int)effect->isEnabled();
6274 }
6275 }
6276
6277Exit:
6278 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07006279 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006280 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07006281 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006282 }
6283 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07006284 AudioSystem::unregisterEffect(effect->id());
6285 }
6286 if (chainCreated) {
6287 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006288 }
6289 handle.clear();
6290 }
6291
6292 if(status) {
6293 *status = lStatus;
6294 }
6295 return handle;
6296}
6297
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006298sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6299{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006300 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08006301 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006302}
6303
Eric Laurentde070132010-07-13 04:45:46 -07006304// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6305// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006306status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07006307{
6308 // check for existing effect chain with the requested audio session
6309 int sessionId = effect->sessionId();
6310 sp<EffectChain> chain = getEffectChain_l(sessionId);
6311 bool chainCreated = false;
6312
6313 if (chain == 0) {
6314 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006315 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006316 chain = new EffectChain(this, sessionId);
6317 addEffectChain_l(chain);
6318 chain->setStrategy(getStrategyForSession_l(sessionId));
6319 chainCreated = true;
6320 }
Steve Block3856b092011-10-20 11:56:00 +01006321 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006322
6323 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006324 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07006325 this, effect->desc().name, chain.get());
6326 return BAD_VALUE;
6327 }
6328
6329 status_t status = chain->addEffect_l(effect);
6330 if (status != NO_ERROR) {
6331 if (chainCreated) {
6332 removeEffectChain_l(chain);
6333 }
6334 return status;
6335 }
6336
6337 effect->setDevice(mDevice);
6338 effect->setMode(mAudioFlinger->getMode());
6339 return NO_ERROR;
6340}
6341
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006342void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07006343
Steve Block3856b092011-10-20 11:56:00 +01006344 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006345 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07006346 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6347 detachAuxEffect_l(effect->id());
6348 }
6349
6350 sp<EffectChain> chain = effect->chain().promote();
6351 if (chain != 0) {
6352 // remove effect chain if removing last effect
6353 if (chain->removeEffect_l(effect) == 0) {
6354 removeEffectChain_l(chain);
6355 }
6356 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00006357 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006358 }
6359}
6360
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006361void AudioFlinger::ThreadBase::lockEffectChains_l(
6362 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
6363{
6364 effectChains = mEffectChains;
6365 for (size_t i = 0; i < mEffectChains.size(); i++) {
6366 mEffectChains[i]->lock();
6367 }
6368}
6369
6370void AudioFlinger::ThreadBase::unlockEffectChains(
6371 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
6372{
6373 for (size_t i = 0; i < effectChains.size(); i++) {
6374 effectChains[i]->unlock();
6375 }
6376}
6377
6378sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6379{
6380 Mutex::Autolock _l(mLock);
6381 return getEffectChain_l(sessionId);
6382}
6383
6384sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6385{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006386 size_t size = mEffectChains.size();
6387 for (size_t i = 0; i < size; i++) {
6388 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08006389 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006390 }
6391 }
Glenn Kasten090f0192012-01-30 13:00:02 -08006392 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006393}
6394
Glenn Kastenf78aee72012-01-04 11:00:47 -08006395void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006396{
6397 Mutex::Autolock _l(mLock);
6398 size_t size = mEffectChains.size();
6399 for (size_t i = 0; i < size; i++) {
6400 mEffectChains[i]->setMode_l(mode);
6401 }
6402}
6403
6404void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006405 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08006406 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07006407
Mathias Agopian65ab4712010-07-14 17:59:35 -07006408 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006409 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006410 // delete the effect module if removing last handle on it
6411 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006412 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006413 removeEffect_l(effect);
6414 AudioSystem::unregisterEffect(effect->id());
6415 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006416 }
6417}
6418
6419status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6420{
6421 int session = chain->sessionId();
6422 int16_t *buffer = mMixBuffer;
6423 bool ownsBuffer = false;
6424
Steve Block3856b092011-10-20 11:56:00 +01006425 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006426 if (session > 0) {
6427 // Only one effect chain can be present in direct output thread and it uses
6428 // the mix buffer as input
6429 if (mType != DIRECT) {
6430 size_t numSamples = mFrameCount * mChannelCount;
6431 buffer = new int16_t[numSamples];
6432 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01006433 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006434 ownsBuffer = true;
6435 }
6436
6437 // Attach all tracks with same session ID to this chain.
6438 for (size_t i = 0; i < mTracks.size(); ++i) {
6439 sp<Track> track = mTracks[i];
6440 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006441 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006442 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006443 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006444 }
6445 }
6446
6447 // indicate all active tracks in the chain
6448 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6449 sp<Track> track = mActiveTracks[i].promote();
6450 if (track == 0) continue;
6451 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006452 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07006453 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006454 }
6455 }
6456 }
6457
6458 chain->setInBuffer(buffer, ownsBuffer);
6459 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006460 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006461 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006462 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6463 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006464 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006465 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6466 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006467 // Effect chain for other sessions are inserted at beginning of effect
6468 // chains list to be processed before output mix effects. Relative order between other
6469 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006470 size_t size = mEffectChains.size();
6471 size_t i = 0;
6472 for (i = 0; i < size; i++) {
6473 if (mEffectChains[i]->sessionId() < session) break;
6474 }
6475 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006476 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006477
6478 return NO_ERROR;
6479}
6480
6481size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6482{
6483 int session = chain->sessionId();
6484
Steve Block3856b092011-10-20 11:56:00 +01006485 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006486
6487 for (size_t i = 0; i < mEffectChains.size(); i++) {
6488 if (chain == mEffectChains[i]) {
6489 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006490 // detach all active tracks from the chain
6491 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6492 sp<Track> track = mActiveTracks[i].promote();
6493 if (track == 0) continue;
6494 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006495 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006496 chain.get(), session);
6497 chain->decActiveTrackCnt();
6498 }
6499 }
6500
Mathias Agopian65ab4712010-07-14 17:59:35 -07006501 // detach all tracks with same session ID from this chain
6502 for (size_t i = 0; i < mTracks.size(); ++i) {
6503 sp<Track> track = mTracks[i];
6504 if (session == track->sessionId()) {
6505 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006506 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006507 }
6508 }
Eric Laurentde070132010-07-13 04:45:46 -07006509 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006510 }
6511 }
6512 return mEffectChains.size();
6513}
6514
Eric Laurentde070132010-07-13 04:45:46 -07006515status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6516 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006517{
6518 Mutex::Autolock _l(mLock);
6519 return attachAuxEffect_l(track, EffectId);
6520}
6521
Eric Laurentde070132010-07-13 04:45:46 -07006522status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6523 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006524{
6525 status_t status = NO_ERROR;
6526
6527 if (EffectId == 0) {
6528 track->setAuxBuffer(0, NULL);
6529 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006530 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6531 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006532 if (effect != 0) {
6533 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6534 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6535 } else {
6536 status = INVALID_OPERATION;
6537 }
6538 } else {
6539 status = BAD_VALUE;
6540 }
6541 }
6542 return status;
6543}
6544
6545void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6546{
6547 for (size_t i = 0; i < mTracks.size(); ++i) {
6548 sp<Track> track = mTracks[i];
6549 if (track->auxEffectId() == effectId) {
6550 attachAuxEffect_l(track, 0);
6551 }
6552 }
6553}
6554
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006555status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6556{
6557 // only one chain per input thread
6558 if (mEffectChains.size() != 0) {
6559 return INVALID_OPERATION;
6560 }
Steve Block3856b092011-10-20 11:56:00 +01006561 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006562
6563 chain->setInBuffer(NULL);
6564 chain->setOutBuffer(NULL);
6565
Eric Laurent59255e42011-07-27 19:49:51 -07006566 checkSuspendOnAddEffectChain_l(chain);
6567
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006568 mEffectChains.add(chain);
6569
6570 return NO_ERROR;
6571}
6572
6573size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6574{
Steve Block3856b092011-10-20 11:56:00 +01006575 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006576 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006577 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6578 chain.get(), mEffectChains.size(), this);
6579 if (mEffectChains.size() == 1) {
6580 mEffectChains.removeAt(0);
6581 }
6582 return 0;
6583}
6584
Mathias Agopian65ab4712010-07-14 17:59:35 -07006585// ----------------------------------------------------------------------------
6586// EffectModule implementation
6587// ----------------------------------------------------------------------------
6588
6589#undef LOG_TAG
6590#define LOG_TAG "AudioFlinger::EffectModule"
6591
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006592AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006593 const wp<AudioFlinger::EffectChain>& chain,
6594 effect_descriptor_t *desc,
6595 int id,
6596 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006597 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006598 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006599{
Steve Block3856b092011-10-20 11:56:00 +01006600 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006601 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006602 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006603 return;
6604 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006605
6606 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6607
6608 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006609 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006610
6611 if (mStatus != NO_ERROR) {
6612 return;
6613 }
6614 lStatus = init();
6615 if (lStatus < 0) {
6616 mStatus = lStatus;
6617 goto Error;
6618 }
6619
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006620 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6621 mPinned = true;
6622 }
Steve Block3856b092011-10-20 11:56:00 +01006623 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006624 return;
6625Error:
6626 EffectRelease(mEffectInterface);
6627 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006628 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006629}
6630
6631AudioFlinger::EffectModule::~EffectModule()
6632{
Steve Block3856b092011-10-20 11:56:00 +01006633 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006634 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006635 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6636 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6637 sp<ThreadBase> thread = mThread.promote();
6638 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006639 audio_stream_t *stream = thread->stream();
6640 if (stream != NULL) {
6641 stream->remove_audio_effect(stream, mEffectInterface);
6642 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006643 }
6644 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006645 // release effect engine
6646 EffectRelease(mEffectInterface);
6647 }
6648}
6649
Glenn Kasten435dbe62012-01-30 10:15:48 -08006650status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006651{
6652 status_t status;
6653
6654 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006655 int priority = handle->priority();
6656 size_t size = mHandles.size();
6657 sp<EffectHandle> h;
6658 size_t i;
6659 for (i = 0; i < size; i++) {
6660 h = mHandles[i].promote();
6661 if (h == 0) continue;
6662 if (h->priority() <= priority) break;
6663 }
6664 // if inserted in first place, move effect control from previous owner to this handle
6665 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006666 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006667 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006668 enabled = h->enabled();
6669 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006670 }
Eric Laurent59255e42011-07-27 19:49:51 -07006671 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006672 status = NO_ERROR;
6673 } else {
6674 status = ALREADY_EXISTS;
6675 }
Steve Block3856b092011-10-20 11:56:00 +01006676 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006677 mHandles.insertAt(handle, i);
6678 return status;
6679}
6680
6681size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6682{
6683 Mutex::Autolock _l(mLock);
6684 size_t size = mHandles.size();
6685 size_t i;
6686 for (i = 0; i < size; i++) {
6687 if (mHandles[i] == handle) break;
6688 }
6689 if (i == size) {
6690 return size;
6691 }
Steve Block3856b092011-10-20 11:56:00 +01006692 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006693
6694 bool enabled = false;
6695 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006696 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006697 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006698 enabled = hdl->enabled();
6699 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006700 mHandles.removeAt(i);
6701 size = mHandles.size();
6702 // if removed from first place, move effect control from this handle to next in line
6703 if (i == 0 && size != 0) {
6704 sp<EffectHandle> h = mHandles[0].promote();
6705 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006706 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006707 }
6708 }
6709
Eric Laurentec437d82011-07-26 20:54:46 -07006710 // Prevent calls to process() and other functions on effect interface from now on.
6711 // The effect engine will be released by the destructor when the last strong reference on
6712 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006713 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006714 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006715 }
6716
Mathias Agopian65ab4712010-07-14 17:59:35 -07006717 return size;
6718}
6719
Eric Laurent59255e42011-07-27 19:49:51 -07006720sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6721{
6722 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08006723 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07006724}
6725
Glenn Kasten58123c32012-02-03 10:32:24 -08006726void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006727{
Glenn Kasten90bebef2012-01-27 15:24:38 -08006728 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006729 // keep a strong reference on this EffectModule to avoid calling the
6730 // destructor before we exit
6731 sp<EffectModule> keep(this);
6732 {
6733 sp<ThreadBase> thread = mThread.promote();
6734 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006735 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006736 }
6737 }
6738}
6739
6740void AudioFlinger::EffectModule::updateState() {
6741 Mutex::Autolock _l(mLock);
6742
6743 switch (mState) {
6744 case RESTART:
6745 reset_l();
6746 // FALL THROUGH
6747
6748 case STARTING:
6749 // clear auxiliary effect input buffer for next accumulation
6750 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6751 memset(mConfig.inputCfg.buffer.raw,
6752 0,
6753 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6754 }
6755 start_l();
6756 mState = ACTIVE;
6757 break;
6758 case STOPPING:
6759 stop_l();
6760 mDisableWaitCnt = mMaxDisableWaitCnt;
6761 mState = STOPPED;
6762 break;
6763 case STOPPED:
6764 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6765 // turn off sequence.
6766 if (--mDisableWaitCnt == 0) {
6767 reset_l();
6768 mState = IDLE;
6769 }
6770 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006771 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006772 break;
6773 }
6774}
6775
6776void AudioFlinger::EffectModule::process()
6777{
6778 Mutex::Autolock _l(mLock);
6779
Eric Laurentec437d82011-07-26 20:54:46 -07006780 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006781 mConfig.inputCfg.buffer.raw == NULL ||
6782 mConfig.outputCfg.buffer.raw == NULL) {
6783 return;
6784 }
6785
Eric Laurent8f45bd72010-08-31 13:50:07 -07006786 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006787 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6788 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006789 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006790 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006791 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006792 }
6793
6794 // do the actual processing in the effect engine
6795 int ret = (*mEffectInterface)->process(mEffectInterface,
6796 &mConfig.inputCfg.buffer,
6797 &mConfig.outputCfg.buffer);
6798
6799 // force transition to IDLE state when engine is ready
6800 if (mState == STOPPED && ret == -ENODATA) {
6801 mDisableWaitCnt = 1;
6802 }
6803
6804 // clear auxiliary effect input buffer for next accumulation
6805 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006806 memset(mConfig.inputCfg.buffer.raw, 0,
6807 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006808 }
6809 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006810 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6811 // If an insert effect is idle and input buffer is different from output buffer,
6812 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006813 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006814 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006815 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6816 int16_t *in = mConfig.inputCfg.buffer.s16;
6817 int16_t *out = mConfig.outputCfg.buffer.s16;
6818 for (size_t i = 0; i < frameCnt; i++) {
6819 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006820 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006821 }
6822 }
6823}
6824
6825void AudioFlinger::EffectModule::reset_l()
6826{
6827 if (mEffectInterface == NULL) {
6828 return;
6829 }
6830 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6831}
6832
6833status_t AudioFlinger::EffectModule::configure()
6834{
6835 uint32_t channels;
6836 if (mEffectInterface == NULL) {
6837 return NO_INIT;
6838 }
6839
6840 sp<ThreadBase> thread = mThread.promote();
6841 if (thread == 0) {
6842 return DEAD_OBJECT;
6843 }
6844
6845 // TODO: handle configuration of effects replacing track process
6846 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006847 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006848 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006849 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006850 }
6851
6852 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006853 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006854 } else {
6855 mConfig.inputCfg.channels = channels;
6856 }
6857 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006858 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6859 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006860 mConfig.inputCfg.samplingRate = thread->sampleRate();
6861 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6862 mConfig.inputCfg.bufferProvider.cookie = NULL;
6863 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6864 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6865 mConfig.outputCfg.bufferProvider.cookie = NULL;
6866 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6867 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6868 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6869 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006870 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006871 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006872 // - in other sessions:
6873 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6874 // other effect: overwrites output buffer: input buffer == output buffer
6875 // Auxiliary effect:
6876 // accumulates in output buffer: input buffer != output buffer
6877 // Therefore: accumulate <=> input buffer != output buffer
6878 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6879 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6880 } else {
6881 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6882 }
6883 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6884 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6885 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6886 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6887
Steve Block3856b092011-10-20 11:56:00 +01006888 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006889 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6890
Mathias Agopian65ab4712010-07-14 17:59:35 -07006891 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006892 uint32_t size = sizeof(int);
6893 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006894 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006895 sizeof(effect_config_t),
6896 &mConfig,
6897 &size,
6898 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006899 if (status == 0) {
6900 status = cmdStatus;
6901 }
6902
6903 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6904 (1000 * mConfig.outputCfg.buffer.frameCount);
6905
6906 return status;
6907}
6908
6909status_t AudioFlinger::EffectModule::init()
6910{
6911 Mutex::Autolock _l(mLock);
6912 if (mEffectInterface == NULL) {
6913 return NO_INIT;
6914 }
6915 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006916 uint32_t size = sizeof(status_t);
6917 status_t status = (*mEffectInterface)->command(mEffectInterface,
6918 EFFECT_CMD_INIT,
6919 0,
6920 NULL,
6921 &size,
6922 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006923 if (status == 0) {
6924 status = cmdStatus;
6925 }
6926 return status;
6927}
6928
Eric Laurentec35a142011-10-05 17:42:25 -07006929status_t AudioFlinger::EffectModule::start()
6930{
6931 Mutex::Autolock _l(mLock);
6932 return start_l();
6933}
6934
Mathias Agopian65ab4712010-07-14 17:59:35 -07006935status_t AudioFlinger::EffectModule::start_l()
6936{
6937 if (mEffectInterface == NULL) {
6938 return NO_INIT;
6939 }
6940 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006941 uint32_t size = sizeof(status_t);
6942 status_t status = (*mEffectInterface)->command(mEffectInterface,
6943 EFFECT_CMD_ENABLE,
6944 0,
6945 NULL,
6946 &size,
6947 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006948 if (status == 0) {
6949 status = cmdStatus;
6950 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006951 if (status == 0 &&
6952 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6953 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6954 sp<ThreadBase> thread = mThread.promote();
6955 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006956 audio_stream_t *stream = thread->stream();
6957 if (stream != NULL) {
6958 stream->add_audio_effect(stream, mEffectInterface);
6959 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006960 }
6961 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006962 return status;
6963}
6964
Eric Laurentec437d82011-07-26 20:54:46 -07006965status_t AudioFlinger::EffectModule::stop()
6966{
6967 Mutex::Autolock _l(mLock);
6968 return stop_l();
6969}
6970
Mathias Agopian65ab4712010-07-14 17:59:35 -07006971status_t AudioFlinger::EffectModule::stop_l()
6972{
6973 if (mEffectInterface == NULL) {
6974 return NO_INIT;
6975 }
6976 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006977 uint32_t size = sizeof(status_t);
6978 status_t status = (*mEffectInterface)->command(mEffectInterface,
6979 EFFECT_CMD_DISABLE,
6980 0,
6981 NULL,
6982 &size,
6983 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006984 if (status == 0) {
6985 status = cmdStatus;
6986 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006987 if (status == 0 &&
6988 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6989 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6990 sp<ThreadBase> thread = mThread.promote();
6991 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006992 audio_stream_t *stream = thread->stream();
6993 if (stream != NULL) {
6994 stream->remove_audio_effect(stream, mEffectInterface);
6995 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006996 }
6997 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006998 return status;
6999}
7000
Eric Laurent25f43952010-07-28 05:40:18 -07007001status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
7002 uint32_t cmdSize,
7003 void *pCmdData,
7004 uint32_t *replySize,
7005 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007006{
7007 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007008// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007009
Eric Laurentec437d82011-07-26 20:54:46 -07007010 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007011 return NO_INIT;
7012 }
Eric Laurent25f43952010-07-28 05:40:18 -07007013 status_t status = (*mEffectInterface)->command(mEffectInterface,
7014 cmdCode,
7015 cmdSize,
7016 pCmdData,
7017 replySize,
7018 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007019 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07007020 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007021 for (size_t i = 1; i < mHandles.size(); i++) {
7022 sp<EffectHandle> h = mHandles[i].promote();
7023 if (h != 0) {
7024 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
7025 }
7026 }
7027 }
7028 return status;
7029}
7030
7031status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
7032{
Eric Laurentdb7c0792011-08-10 10:37:50 -07007033
Mathias Agopian65ab4712010-07-14 17:59:35 -07007034 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007035 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007036
7037 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007038 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
7039 if (enabled && status != NO_ERROR) {
7040 return status;
7041 }
7042
Mathias Agopian65ab4712010-07-14 17:59:35 -07007043 switch (mState) {
7044 // going from disabled to enabled
7045 case IDLE:
7046 mState = STARTING;
7047 break;
7048 case STOPPED:
7049 mState = RESTART;
7050 break;
7051 case STOPPING:
7052 mState = ACTIVE;
7053 break;
7054
7055 // going from enabled to disabled
7056 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007057 mState = STOPPED;
7058 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007059 case STARTING:
7060 mState = IDLE;
7061 break;
7062 case ACTIVE:
7063 mState = STOPPING;
7064 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007065 case DESTROYED:
7066 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007067 }
7068 for (size_t i = 1; i < mHandles.size(); i++) {
7069 sp<EffectHandle> h = mHandles[i].promote();
7070 if (h != 0) {
7071 h->setEnabled(enabled);
7072 }
7073 }
7074 }
7075 return NO_ERROR;
7076}
7077
Glenn Kastenc59c0042012-02-02 14:06:11 -08007078bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007079{
7080 switch (mState) {
7081 case RESTART:
7082 case STARTING:
7083 case ACTIVE:
7084 return true;
7085 case IDLE:
7086 case STOPPING:
7087 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07007088 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07007089 default:
7090 return false;
7091 }
7092}
7093
Glenn Kastenc59c0042012-02-02 14:06:11 -08007094bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07007095{
7096 switch (mState) {
7097 case RESTART:
7098 case ACTIVE:
7099 case STOPPING:
7100 case STOPPED:
7101 return true;
7102 case IDLE:
7103 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07007104 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007105 default:
7106 return false;
7107 }
7108}
7109
Mathias Agopian65ab4712010-07-14 17:59:35 -07007110status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7111{
7112 Mutex::Autolock _l(mLock);
7113 status_t status = NO_ERROR;
7114
7115 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7116 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07007117 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07007118 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7119 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007120 status_t cmdStatus;
7121 uint32_t volume[2];
7122 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07007123 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007124 volume[0] = *left;
7125 volume[1] = *right;
7126 if (controller) {
7127 pVolume = volume;
7128 }
Eric Laurent25f43952010-07-28 05:40:18 -07007129 status = (*mEffectInterface)->command(mEffectInterface,
7130 EFFECT_CMD_SET_VOLUME,
7131 size,
7132 volume,
7133 &size,
7134 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007135 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7136 *left = volume[0];
7137 *right = volume[1];
7138 }
7139 }
7140 return status;
7141}
7142
7143status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7144{
7145 Mutex::Autolock _l(mLock);
7146 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007147 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7148 // audio pre processing modules on RecordThread can receive both output and
7149 // input device indication in the same call
7150 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7151 if (dev) {
7152 status_t cmdStatus;
7153 uint32_t size = sizeof(status_t);
7154
7155 status = (*mEffectInterface)->command(mEffectInterface,
7156 EFFECT_CMD_SET_DEVICE,
7157 sizeof(uint32_t),
7158 &dev,
7159 &size,
7160 &cmdStatus);
7161 if (status == NO_ERROR) {
7162 status = cmdStatus;
7163 }
7164 }
7165 dev = device & AUDIO_DEVICE_IN_ALL;
7166 if (dev) {
7167 status_t cmdStatus;
7168 uint32_t size = sizeof(status_t);
7169
7170 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7171 EFFECT_CMD_SET_INPUT_DEVICE,
7172 sizeof(uint32_t),
7173 &dev,
7174 &size,
7175 &cmdStatus);
7176 if (status2 == NO_ERROR) {
7177 status2 = cmdStatus;
7178 }
7179 if (status == NO_ERROR) {
7180 status = status2;
7181 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007182 }
7183 }
7184 return status;
7185}
7186
Glenn Kastenf78aee72012-01-04 11:00:47 -08007187status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007188{
7189 Mutex::Autolock _l(mLock);
7190 status_t status = NO_ERROR;
7191 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007192 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007193 uint32_t size = sizeof(status_t);
7194 status = (*mEffectInterface)->command(mEffectInterface,
7195 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08007196 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07007197 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07007198 &size,
7199 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007200 if (status == NO_ERROR) {
7201 status = cmdStatus;
7202 }
7203 }
7204 return status;
7205}
7206
Eric Laurent59255e42011-07-27 19:49:51 -07007207void AudioFlinger::EffectModule::setSuspended(bool suspended)
7208{
7209 Mutex::Autolock _l(mLock);
7210 mSuspended = suspended;
7211}
Glenn Kastena3a85482012-01-04 11:01:11 -08007212
7213bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07007214{
7215 Mutex::Autolock _l(mLock);
7216 return mSuspended;
7217}
7218
Mathias Agopian65ab4712010-07-14 17:59:35 -07007219status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7220{
7221 const size_t SIZE = 256;
7222 char buffer[SIZE];
7223 String8 result;
7224
7225 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7226 result.append(buffer);
7227
7228 bool locked = tryLock(mLock);
7229 // failed to lock - AudioFlinger is probably deadlocked
7230 if (!locked) {
7231 result.append("\t\tCould not lock Fx mutex:\n");
7232 }
7233
7234 result.append("\t\tSession Status State Engine:\n");
7235 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7236 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7237 result.append(buffer);
7238
7239 result.append("\t\tDescriptor:\n");
7240 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7241 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7242 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7243 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7244 result.append(buffer);
7245 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7246 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7247 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7248 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7249 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07007250 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007251 mDescriptor.apiVersion,
7252 mDescriptor.flags);
7253 result.append(buffer);
7254 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7255 mDescriptor.name);
7256 result.append(buffer);
7257 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7258 mDescriptor.implementor);
7259 result.append(buffer);
7260
7261 result.append("\t\t- Input configuration:\n");
7262 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7263 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7264 (uint32_t)mConfig.inputCfg.buffer.raw,
7265 mConfig.inputCfg.buffer.frameCount,
7266 mConfig.inputCfg.samplingRate,
7267 mConfig.inputCfg.channels,
7268 mConfig.inputCfg.format);
7269 result.append(buffer);
7270
7271 result.append("\t\t- Output configuration:\n");
7272 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7273 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7274 (uint32_t)mConfig.outputCfg.buffer.raw,
7275 mConfig.outputCfg.buffer.frameCount,
7276 mConfig.outputCfg.samplingRate,
7277 mConfig.outputCfg.channels,
7278 mConfig.outputCfg.format);
7279 result.append(buffer);
7280
7281 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7282 result.append(buffer);
7283 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7284 for (size_t i = 0; i < mHandles.size(); ++i) {
7285 sp<EffectHandle> handle = mHandles[i].promote();
7286 if (handle != 0) {
7287 handle->dump(buffer, SIZE);
7288 result.append(buffer);
7289 }
7290 }
7291
7292 result.append("\n");
7293
7294 write(fd, result.string(), result.length());
7295
7296 if (locked) {
7297 mLock.unlock();
7298 }
7299
7300 return NO_ERROR;
7301}
7302
7303// ----------------------------------------------------------------------------
7304// EffectHandle implementation
7305// ----------------------------------------------------------------------------
7306
7307#undef LOG_TAG
7308#define LOG_TAG "AudioFlinger::EffectHandle"
7309
7310AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7311 const sp<AudioFlinger::Client>& client,
7312 const sp<IEffectClient>& effectClient,
7313 int32_t priority)
7314 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007315 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007316 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007317{
Steve Block3856b092011-10-20 11:56:00 +01007318 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007319
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007320 if (client == 0) {
7321 return;
7322 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007323 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7324 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7325 if (mCblkMemory != 0) {
7326 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7327
Glenn Kastena0d68332012-01-27 16:47:15 -08007328 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007329 new(mCblk) effect_param_cblk_t();
7330 mBuffer = (uint8_t *)mCblk + bufOffset;
7331 }
7332 } else {
Steve Block29357bc2012-01-06 19:20:56 +00007333 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007334 return;
7335 }
7336}
7337
7338AudioFlinger::EffectHandle::~EffectHandle()
7339{
Steve Block3856b092011-10-20 11:56:00 +01007340 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007341 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01007342 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007343}
7344
7345status_t AudioFlinger::EffectHandle::enable()
7346{
Steve Block3856b092011-10-20 11:56:00 +01007347 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007348 if (!mHasControl) return INVALID_OPERATION;
7349 if (mEffect == 0) return DEAD_OBJECT;
7350
Eric Laurentdb7c0792011-08-10 10:37:50 -07007351 if (mEnabled) {
7352 return NO_ERROR;
7353 }
7354
Eric Laurent59255e42011-07-27 19:49:51 -07007355 mEnabled = true;
7356
7357 sp<ThreadBase> thread = mEffect->thread().promote();
7358 if (thread != 0) {
7359 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7360 }
7361
7362 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7363 if (mEffect->suspended()) {
7364 return NO_ERROR;
7365 }
7366
Eric Laurentdb7c0792011-08-10 10:37:50 -07007367 status_t status = mEffect->setEnabled(true);
7368 if (status != NO_ERROR) {
7369 if (thread != 0) {
7370 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7371 }
7372 mEnabled = false;
7373 }
7374 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007375}
7376
7377status_t AudioFlinger::EffectHandle::disable()
7378{
Steve Block3856b092011-10-20 11:56:00 +01007379 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007380 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07007381 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007382
Eric Laurentdb7c0792011-08-10 10:37:50 -07007383 if (!mEnabled) {
7384 return NO_ERROR;
7385 }
Eric Laurent59255e42011-07-27 19:49:51 -07007386 mEnabled = false;
7387
7388 if (mEffect->suspended()) {
7389 return NO_ERROR;
7390 }
7391
7392 status_t status = mEffect->setEnabled(false);
7393
7394 sp<ThreadBase> thread = mEffect->thread().promote();
7395 if (thread != 0) {
7396 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7397 }
7398
7399 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007400}
7401
7402void AudioFlinger::EffectHandle::disconnect()
7403{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007404 disconnect(true);
7405}
7406
Glenn Kasten58123c32012-02-03 10:32:24 -08007407void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007408{
Glenn Kasten58123c32012-02-03 10:32:24 -08007409 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007410 if (mEffect == 0) {
7411 return;
7412 }
Glenn Kasten58123c32012-02-03 10:32:24 -08007413 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07007414
Eric Laurenta85a74a2011-10-19 11:44:54 -07007415 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007416 sp<ThreadBase> thread = mEffect->thread().promote();
7417 if (thread != 0) {
7418 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7419 }
Eric Laurent59255e42011-07-27 19:49:51 -07007420 }
7421
Mathias Agopian65ab4712010-07-14 17:59:35 -07007422 // release sp on module => module destructor can be called now
7423 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007424 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08007425 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08007426 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007427 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7428 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08007429 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007430 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07007431 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7432 mClient.clear();
7433 }
7434}
7435
Eric Laurent25f43952010-07-28 05:40:18 -07007436status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7437 uint32_t cmdSize,
7438 void *pCmdData,
7439 uint32_t *replySize,
7440 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007441{
Steve Block3856b092011-10-20 11:56:00 +01007442// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07007443// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007444
7445 // only get parameter command is permitted for applications not controlling the effect
7446 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7447 return INVALID_OPERATION;
7448 }
7449 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007450 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007451
7452 // handle commands that are not forwarded transparently to effect engine
7453 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7454 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7455 // no risk to block the whole media server process or mixer threads is we are stuck here
7456 Mutex::Autolock _l(mCblk->lock);
7457 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7458 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7459 mCblk->serverIndex = 0;
7460 mCblk->clientIndex = 0;
7461 return BAD_VALUE;
7462 }
7463 status_t status = NO_ERROR;
7464 while (mCblk->serverIndex < mCblk->clientIndex) {
7465 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007466 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007467 int *p = (int *)(mBuffer + mCblk->serverIndex);
7468 int size = *p++;
7469 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007470 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007471 break;
7472 }
7473 effect_param_t *param = (effect_param_t *)p;
7474 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007475 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007476 mCblk->serverIndex += size;
7477 continue;
7478 }
Eric Laurent25f43952010-07-28 05:40:18 -07007479 uint32_t psize = sizeof(effect_param_t) +
7480 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7481 param->vsize;
7482 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7483 psize,
7484 p,
7485 &rsize,
7486 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007487 // stop at first error encountered
7488 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007489 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007490 *(int *)pReplyData = reply;
7491 break;
7492 } else if (reply != NO_ERROR) {
7493 *(int *)pReplyData = reply;
7494 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007495 }
7496 mCblk->serverIndex += size;
7497 }
7498 mCblk->serverIndex = 0;
7499 mCblk->clientIndex = 0;
7500 return status;
7501 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007502 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007503 return enable();
7504 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007505 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007506 return disable();
7507 }
7508
7509 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7510}
7511
Eric Laurent59255e42011-07-27 19:49:51 -07007512void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007513{
Steve Block3856b092011-10-20 11:56:00 +01007514 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007515
7516 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007517 mEnabled = enabled;
7518
Mathias Agopian65ab4712010-07-14 17:59:35 -07007519 if (signal && mEffectClient != 0) {
7520 mEffectClient->controlStatusChanged(hasControl);
7521 }
7522}
7523
Eric Laurent25f43952010-07-28 05:40:18 -07007524void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7525 uint32_t cmdSize,
7526 void *pCmdData,
7527 uint32_t replySize,
7528 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007529{
7530 if (mEffectClient != 0) {
7531 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7532 }
7533}
7534
7535
7536
7537void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7538{
7539 if (mEffectClient != 0) {
7540 mEffectClient->enableStatusChanged(enabled);
7541 }
7542}
7543
7544status_t AudioFlinger::EffectHandle::onTransact(
7545 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7546{
7547 return BnEffect::onTransact(code, data, reply, flags);
7548}
7549
7550
7551void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7552{
Glenn Kastena0d68332012-01-27 16:47:15 -08007553 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007554
7555 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08007556 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007557 mPriority,
7558 mHasControl,
7559 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007560 mCblk ? mCblk->clientIndex : 0,
7561 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007562 );
7563
7564 if (locked) {
7565 mCblk->lock.unlock();
7566 }
7567}
7568
7569#undef LOG_TAG
7570#define LOG_TAG "AudioFlinger::EffectChain"
7571
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007572AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007573 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007574 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007575 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7576 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007577{
Dima Zavinfce7a472011-04-19 22:30:36 -07007578 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007579 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007580 return;
7581 }
7582 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7583 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007584}
7585
7586AudioFlinger::EffectChain::~EffectChain()
7587{
7588 if (mOwnInBuffer) {
7589 delete mInBuffer;
7590 }
7591
7592}
7593
Eric Laurent59255e42011-07-27 19:49:51 -07007594// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007595sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007596{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007597 size_t size = mEffects.size();
7598
7599 for (size_t i = 0; i < size; i++) {
7600 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007601 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007602 }
7603 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007604 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007605}
7606
Eric Laurent59255e42011-07-27 19:49:51 -07007607// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007608sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007609{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007610 size_t size = mEffects.size();
7611
7612 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007613 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7614 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007615 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007616 }
7617 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007618 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007619}
7620
Eric Laurent59255e42011-07-27 19:49:51 -07007621// getEffectFromType_l() must be called with ThreadBase::mLock held
7622sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7623 const effect_uuid_t *type)
7624{
Eric Laurent59255e42011-07-27 19:49:51 -07007625 size_t size = mEffects.size();
7626
7627 for (size_t i = 0; i < size; i++) {
7628 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007629 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007630 }
7631 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007632 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007633}
7634
Mathias Agopian65ab4712010-07-14 17:59:35 -07007635// Must be called with EffectChain::mLock locked
7636void AudioFlinger::EffectChain::process_l()
7637{
Eric Laurentdac69112010-09-28 14:09:57 -07007638 sp<ThreadBase> thread = mThread.promote();
7639 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007640 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007641 return;
7642 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007643 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7644 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007645 // always process effects unless no more tracks are on the session and the effect tail
7646 // has been rendered
7647 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007648 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007649 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007650
Eric Laurent544fe9b2011-11-11 15:42:52 -08007651 if (!tracksOnSession && mTailBufferCount == 0) {
7652 doProcess = false;
7653 }
7654
7655 if (activeTrackCnt() == 0) {
7656 // if no track is active and the effect tail has not been rendered,
7657 // the input buffer must be cleared here as the mixer process will not do it
7658 if (tracksOnSession || mTailBufferCount > 0) {
7659 size_t numSamples = thread->frameCount() * thread->channelCount();
7660 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7661 if (mTailBufferCount > 0) {
7662 mTailBufferCount--;
7663 }
7664 }
7665 }
Eric Laurentdac69112010-09-28 14:09:57 -07007666 }
7667
Mathias Agopian65ab4712010-07-14 17:59:35 -07007668 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007669 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007670 for (size_t i = 0; i < size; i++) {
7671 mEffects[i]->process();
7672 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007673 }
7674 for (size_t i = 0; i < size; i++) {
7675 mEffects[i]->updateState();
7676 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007677}
7678
Eric Laurentcab11242010-07-15 12:50:15 -07007679// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007680status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007681{
7682 effect_descriptor_t desc = effect->desc();
7683 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7684
7685 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007686 effect->setChain(this);
7687 sp<ThreadBase> thread = mThread.promote();
7688 if (thread == 0) {
7689 return NO_INIT;
7690 }
7691 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007692
7693 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7694 // Auxiliary effects are inserted at the beginning of mEffects vector as
7695 // they are processed first and accumulated in chain input buffer
7696 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007697
Mathias Agopian65ab4712010-07-14 17:59:35 -07007698 // the input buffer for auxiliary effect contains mono samples in
7699 // 32 bit format. This is to avoid saturation in AudoMixer
7700 // accumulation stage. Saturation is done in EffectModule::process() before
7701 // calling the process in effect engine
7702 size_t numSamples = thread->frameCount();
7703 int32_t *buffer = new int32_t[numSamples];
7704 memset(buffer, 0, numSamples * sizeof(int32_t));
7705 effect->setInBuffer((int16_t *)buffer);
7706 // auxiliary effects output samples to chain input buffer for further processing
7707 // by insert effects
7708 effect->setOutBuffer(mInBuffer);
7709 } else {
7710 // Insert effects are inserted at the end of mEffects vector as they are processed
7711 // after track and auxiliary effects.
7712 // Insert effect order as a function of indicated preference:
7713 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7714 // another effect is present
7715 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7716 // last effect claiming first position
7717 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7718 // first effect claiming last position
7719 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7720 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7721 // already present
7722
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007723 size_t size = mEffects.size();
7724 size_t idx_insert = size;
7725 ssize_t idx_insert_first = -1;
7726 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007727
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007728 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007729 effect_descriptor_t d = mEffects[i]->desc();
7730 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7731 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7732 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7733 // check invalid effect chaining combinations
7734 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7735 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007736 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007737 return INVALID_OPERATION;
7738 }
7739 // remember position of first insert effect and by default
7740 // select this as insert position for new effect
7741 if (idx_insert == size) {
7742 idx_insert = i;
7743 }
7744 // remember position of last insert effect claiming
7745 // first position
7746 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7747 idx_insert_first = i;
7748 }
7749 // remember position of first insert effect claiming
7750 // last position
7751 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7752 idx_insert_last == -1) {
7753 idx_insert_last = i;
7754 }
7755 }
7756 }
7757
7758 // modify idx_insert from first position if needed
7759 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7760 if (idx_insert_last != -1) {
7761 idx_insert = idx_insert_last;
7762 } else {
7763 idx_insert = size;
7764 }
7765 } else {
7766 if (idx_insert_first != -1) {
7767 idx_insert = idx_insert_first + 1;
7768 }
7769 }
7770
7771 // always read samples from chain input buffer
7772 effect->setInBuffer(mInBuffer);
7773
7774 // if last effect in the chain, output samples to chain
7775 // output buffer, otherwise to chain input buffer
7776 if (idx_insert == size) {
7777 if (idx_insert != 0) {
7778 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7779 mEffects[idx_insert-1]->configure();
7780 }
7781 effect->setOutBuffer(mOutBuffer);
7782 } else {
7783 effect->setOutBuffer(mInBuffer);
7784 }
7785 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007786
Steve Block3856b092011-10-20 11:56:00 +01007787 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007788 }
7789 effect->configure();
7790 return NO_ERROR;
7791}
7792
Eric Laurentcab11242010-07-15 12:50:15 -07007793// removeEffect_l() must be called with PlaybackThread::mLock held
7794size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007795{
7796 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007797 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007798 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7799
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007800 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007801 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007802 // calling stop here will remove pre-processing effect from the audio HAL.
7803 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7804 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007805 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7806 mEffects[i]->state() == EffectModule::STOPPING) {
7807 mEffects[i]->stop();
7808 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007809 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7810 delete[] effect->inBuffer();
7811 } else {
7812 if (i == size - 1 && i != 0) {
7813 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7814 mEffects[i - 1]->configure();
7815 }
7816 }
7817 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007818 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007819 break;
7820 }
7821 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007822
7823 return mEffects.size();
7824}
7825
Eric Laurentcab11242010-07-15 12:50:15 -07007826// setDevice_l() must be called with PlaybackThread::mLock held
7827void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007828{
7829 size_t size = mEffects.size();
7830 for (size_t i = 0; i < size; i++) {
7831 mEffects[i]->setDevice(device);
7832 }
7833}
7834
Eric Laurentcab11242010-07-15 12:50:15 -07007835// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007836void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
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]->setMode(mode);
7841 }
7842}
7843
Eric Laurentcab11242010-07-15 12:50:15 -07007844// setVolume_l() must be called with PlaybackThread::mLock held
7845bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007846{
7847 uint32_t newLeft = *left;
7848 uint32_t newRight = *right;
7849 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007850 int ctrlIdx = -1;
7851 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007852
Eric Laurentcab11242010-07-15 12:50:15 -07007853 // first update volume controller
7854 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007855 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007856 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7857 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007858 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007859 break;
7860 }
7861 }
7862
7863 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007864 if (hasControl) {
7865 *left = mNewLeftVolume;
7866 *right = mNewRightVolume;
7867 }
7868 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007869 }
7870
7871 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007872 mLeftVolume = newLeft;
7873 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007874
7875 // second get volume update from volume controller
7876 if (ctrlIdx >= 0) {
7877 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007878 mNewLeftVolume = newLeft;
7879 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007880 }
7881 // then indicate volume to all other effects in chain.
7882 // Pass altered volume to effects before volume controller
7883 // and requested volume to effects after controller
7884 uint32_t lVol = newLeft;
7885 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007886
Mathias Agopian65ab4712010-07-14 17:59:35 -07007887 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007888 if ((int)i == ctrlIdx) continue;
7889 // this also works for ctrlIdx == -1 when there is no volume controller
7890 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007891 lVol = *left;
7892 rVol = *right;
7893 }
7894 mEffects[i]->setVolume(&lVol, &rVol, false);
7895 }
7896 *left = newLeft;
7897 *right = newRight;
7898
7899 return hasControl;
7900}
7901
Mathias Agopian65ab4712010-07-14 17:59:35 -07007902status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7903{
7904 const size_t SIZE = 256;
7905 char buffer[SIZE];
7906 String8 result;
7907
7908 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7909 result.append(buffer);
7910
7911 bool locked = tryLock(mLock);
7912 // failed to lock - AudioFlinger is probably deadlocked
7913 if (!locked) {
7914 result.append("\tCould not lock mutex:\n");
7915 }
7916
Eric Laurentcab11242010-07-15 12:50:15 -07007917 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7918 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007919 mEffects.size(),
7920 (uint32_t)mInBuffer,
7921 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007922 mActiveTrackCnt);
7923 result.append(buffer);
7924 write(fd, result.string(), result.size());
7925
7926 for (size_t i = 0; i < mEffects.size(); ++i) {
7927 sp<EffectModule> effect = mEffects[i];
7928 if (effect != 0) {
7929 effect->dump(fd, args);
7930 }
7931 }
7932
7933 if (locked) {
7934 mLock.unlock();
7935 }
7936
7937 return NO_ERROR;
7938}
7939
Eric Laurent59255e42011-07-27 19:49:51 -07007940// must be called with ThreadBase::mLock held
7941void AudioFlinger::EffectChain::setEffectSuspended_l(
7942 const effect_uuid_t *type, bool suspend)
7943{
7944 sp<SuspendedEffectDesc> desc;
7945 // use effect type UUID timelow as key as there is no real risk of identical
7946 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007947 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007948 if (suspend) {
7949 if (index >= 0) {
7950 desc = mSuspendedEffects.valueAt(index);
7951 } else {
7952 desc = new SuspendedEffectDesc();
7953 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7954 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007955 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007956 }
7957 if (desc->mRefCount++ == 0) {
7958 sp<EffectModule> effect = getEffectIfEnabled(type);
7959 if (effect != 0) {
7960 desc->mEffect = effect;
7961 effect->setSuspended(true);
7962 effect->setEnabled(false);
7963 }
7964 }
7965 } else {
7966 if (index < 0) {
7967 return;
7968 }
7969 desc = mSuspendedEffects.valueAt(index);
7970 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007971 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007972 desc->mRefCount = 1;
7973 }
7974 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007975 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007976 if (desc->mEffect != 0) {
7977 sp<EffectModule> effect = desc->mEffect.promote();
7978 if (effect != 0) {
7979 effect->setSuspended(false);
7980 sp<EffectHandle> handle = effect->controlHandle();
7981 if (handle != 0) {
7982 effect->setEnabled(handle->enabled());
7983 }
7984 }
7985 desc->mEffect.clear();
7986 }
7987 mSuspendedEffects.removeItemsAt(index);
7988 }
7989 }
7990}
7991
7992// must be called with ThreadBase::mLock held
7993void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7994{
7995 sp<SuspendedEffectDesc> desc;
7996
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007997 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07007998 if (suspend) {
7999 if (index >= 0) {
8000 desc = mSuspendedEffects.valueAt(index);
8001 } else {
8002 desc = new SuspendedEffectDesc();
8003 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01008004 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07008005 }
8006 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08008007 Vector< sp<EffectModule> > effects;
8008 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07008009 for (size_t i = 0; i < effects.size(); i++) {
8010 setEffectSuspended_l(&effects[i]->desc().type, true);
8011 }
8012 }
8013 } else {
8014 if (index < 0) {
8015 return;
8016 }
8017 desc = mSuspendedEffects.valueAt(index);
8018 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008019 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008020 desc->mRefCount = 1;
8021 }
8022 if (--desc->mRefCount == 0) {
8023 Vector<const effect_uuid_t *> types;
8024 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
8025 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
8026 continue;
8027 }
8028 types.add(&mSuspendedEffects.valueAt(i)->mType);
8029 }
8030 for (size_t i = 0; i < types.size(); i++) {
8031 setEffectSuspended_l(types[i], false);
8032 }
Steve Block3856b092011-10-20 11:56:00 +01008033 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008034 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
8035 }
8036 }
8037}
8038
Eric Laurent6bffdb82011-09-23 08:40:41 -07008039
8040// The volume effect is used for automated tests only
8041#ifndef OPENSL_ES_H_
8042static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
8043 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
8044const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
8045#endif //OPENSL_ES_H_
8046
Eric Laurentdb7c0792011-08-10 10:37:50 -07008047bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
8048{
8049 // auxiliary effects and visualizer are never suspended on output mix
8050 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8051 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07008052 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8053 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008054 return false;
8055 }
8056 return true;
8057}
8058
Glenn Kastend0539712012-01-30 12:56:03 -08008059void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07008060{
Glenn Kastend0539712012-01-30 12:56:03 -08008061 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07008062 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08008063 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8064 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07008065 }
Eric Laurent59255e42011-07-27 19:49:51 -07008066 }
Eric Laurent59255e42011-07-27 19:49:51 -07008067}
8068
8069sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8070 const effect_uuid_t *type)
8071{
Glenn Kasten090f0192012-01-30 13:00:02 -08008072 sp<EffectModule> effect = getEffectFromType_l(type);
8073 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008074}
8075
8076void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8077 bool enabled)
8078{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008079 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008080 if (enabled) {
8081 if (index < 0) {
8082 // if the effect is not suspend check if all effects are suspended
8083 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8084 if (index < 0) {
8085 return;
8086 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07008087 if (!isEffectEligibleForSuspend(effect->desc())) {
8088 return;
8089 }
Eric Laurent59255e42011-07-27 19:49:51 -07008090 setEffectSuspended_l(&effect->desc().type, enabled);
8091 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07008092 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008093 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07008094 return;
8095 }
Eric Laurent59255e42011-07-27 19:49:51 -07008096 }
Steve Block3856b092011-10-20 11:56:00 +01008097 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07008098 effect->desc().type.timeLow);
8099 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8100 // if effect is requested to suspended but was not yet enabled, supend it now.
8101 if (desc->mEffect == 0) {
8102 desc->mEffect = effect;
8103 effect->setEnabled(false);
8104 effect->setSuspended(true);
8105 }
8106 } else {
8107 if (index < 0) {
8108 return;
8109 }
Steve Block3856b092011-10-20 11:56:00 +01008110 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07008111 effect->desc().type.timeLow);
8112 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8113 desc->mEffect.clear();
8114 effect->setSuspended(false);
8115 }
8116}
8117
Mathias Agopian65ab4712010-07-14 17:59:35 -07008118#undef LOG_TAG
8119#define LOG_TAG "AudioFlinger"
8120
8121// ----------------------------------------------------------------------------
8122
8123status_t AudioFlinger::onTransact(
8124 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8125{
8126 return BnAudioFlinger::onTransact(code, data, reply, flags);
8127}
8128
Mathias Agopian65ab4712010-07-14 17:59:35 -07008129}; // namespace android