blob: 103e18bd13fc2d1f633c788f584c4043b1120dbd [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070034#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035
Dima Zavinfce7a472011-04-19 22:30:36 -070036#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080038#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039
Gloria Wang9ee159b2011-02-24 14:51:45 -080040#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080041#include <media/IMediaDeathNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042
43#include <private/media/AudioTrackShared.h>
44#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070045
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070047#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080051#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
Mathias Agopian65ab4712010-07-14 17:59:35 -070053#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070054#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070055#include <audio_effects/effect_ns.h>
56#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Glenn Kasten3b21c502011-12-15 09:52:39 -080058#include <audio_utils/primitives.h>
59
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070060#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070061#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070062// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
63
John Grossman4ff14ba2012-02-08 16:37:41 -080064#include <common_time/cc_helper.h>
65#include <common_time/local_clock.h>
66
Mathias Agopian65ab4712010-07-14 17:59:35 -070067// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070068
Eric Laurentde070132010-07-13 04:45:46 -070069
Mathias Agopian65ab4712010-07-14 17:59:35 -070070namespace android {
71
Glenn Kastenec1d6b52011-12-12 09:04:45 -080072static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
73static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070074
Mathias Agopian65ab4712010-07-14 17:59:35 -070075static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -080076static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070077
78// retry counts for buffer fill timeout
79// 50 * ~20msecs = 1 second
80static const int8_t kMaxTrackRetries = 50;
81static const int8_t kMaxTrackStartupRetries = 50;
82// allow less retry attempts on direct output thread.
83// direct outputs can be a scarce resource in audio hardware and should
84// be released as quickly as possible.
85static const int8_t kMaxTrackRetriesDirect = 2;
86
87static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -080088static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
Glenn Kasten7dede872011-12-13 11:04:14 -080090// don't warn about blocked writes or record buffer overflows more often than this
91static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -070092
Eric Laurent7c7f10b2011-06-17 21:29:58 -070093// RecordThread loop sleep time upon application overrun or audio HAL read error
94static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070095
Glenn Kasten7dede872011-12-13 11:04:14 -080096// maximum time to wait for setParameters to complete
97static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -070098
Eric Laurent7cafbb32011-11-22 18:50:29 -080099// minimum sleep time for the mixer thread loop when tracks are active but in underrun
100static const uint32_t kMinThreadSleepTimeUs = 5000;
101// maximum divider applied to the active sleep time in the mixer thread loop
102static const uint32_t kMaxThreadSleepTimeShift = 2;
103
John Grossman4ff14ba2012-02-08 16:37:41 -0800104nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800105
Mathias Agopian65ab4712010-07-14 17:59:35 -0700106// ----------------------------------------------------------------------------
107
Gloria Wang9ee159b2011-02-24 14:51:45 -0800108// To collect the amplifier usage
109static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800110 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
111 if (service == NULL) {
112 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800113 return;
114 }
115
116 service->addBatteryData(params);
117}
118
Dima Zavin799a70e2011-04-18 16:57:27 -0700119static int load_audio_interface(const char *if_name, const hw_module_t **mod,
120 audio_hw_device_t **dev)
121{
122 int rc;
123
124 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
125 if (rc)
126 goto out;
127
128 rc = audio_hw_device_open(*mod, dev);
Steve Block29357bc2012-01-06 19:20:56 +0000129 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin799a70e2011-04-18 16:57:27 -0700130 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
131 if (rc)
132 goto out;
133
134 return 0;
135
136out:
137 *mod = NULL;
138 *dev = NULL;
139 return rc;
140}
141
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800142static const char * const audio_interfaces[] = {
Dima Zavin799a70e2011-04-18 16:57:27 -0700143 "primary",
144 "a2dp",
145 "usb",
146};
147#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
148
Mathias Agopian65ab4712010-07-14 17:59:35 -0700149// ----------------------------------------------------------------------------
150
151AudioFlinger::AudioFlinger()
152 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800153 mPrimaryHardwareDev(NULL),
154 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
155 mMasterVolume(1.0f),
156 mMasterVolumeSupportLvl(MVS_NONE),
157 mMasterMute(false),
158 mNextUniqueId(1),
159 mMode(AUDIO_MODE_INVALID),
160 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700161{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700162}
163
164void AudioFlinger::onFirstRef()
165{
Dima Zavin799a70e2011-04-18 16:57:27 -0700166 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700167
Eric Laurent93575202011-01-18 18:39:02 -0800168 Mutex::Autolock _l(mLock);
169
Dima Zavin799a70e2011-04-18 16:57:27 -0700170 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800171 char val_str[PROPERTY_VALUE_MAX] = { 0 };
172 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
173 uint32_t int_val;
174 if (1 == sscanf(val_str, "%u", &int_val)) {
175 mStandbyTimeInNsecs = milliseconds(int_val);
176 ALOGI("Using %u mSec as standby time.", int_val);
177 } else {
178 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
179 ALOGI("Using default %u mSec as standby time.",
180 (uint32_t)(mStandbyTimeInNsecs / 1000000));
181 }
182 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700183
Dima Zavin799a70e2011-04-18 16:57:27 -0700184 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
185 const hw_module_t *mod;
186 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700187
Dima Zavin799a70e2011-04-18 16:57:27 -0700188 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
189 if (rc)
190 continue;
191
Steve Blockdf64d152012-01-04 20:05:49 +0000192 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Dima Zavin799a70e2011-04-18 16:57:27 -0700193 mod->name, mod->id);
194 mAudioHwDevs.push(dev);
195
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800196 if (mPrimaryHardwareDev == NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700197 mPrimaryHardwareDev = dev;
Steve Blockdf64d152012-01-04 20:05:49 +0000198 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700199 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700200 }
201 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700202
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800203 if (mPrimaryHardwareDev == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000204 ALOGE("Primary audio interface not found");
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800205 // proceed, all later accesses to mPrimaryHardwareDev verify it's safe with initCheck()
Dima Zavin799a70e2011-04-18 16:57:27 -0700206 }
207
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800208 // Currently (mPrimaryHardwareDev == NULL) == (mAudioHwDevs.size() == 0), but the way the
209 // primary HW dev is selected can change so these conditions might not always be equivalent.
210 // When that happens, re-visit all the code that assumes this.
211
212 AutoMutex lock(mHardwareLock);
213
John Grossman4ff14ba2012-02-08 16:37:41 -0800214 // Determine the level of master volume support the primary audio HAL has,
215 // and set the initial master volume at the same time.
216 float initialVolume = 1.0;
217 mMasterVolumeSupportLvl = MVS_NONE;
218 if (0 == mPrimaryHardwareDev->init_check(mPrimaryHardwareDev)) {
219 audio_hw_device_t *dev = mPrimaryHardwareDev;
220
221 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
222 if ((NULL != dev->get_master_volume) &&
223 (NO_ERROR == dev->get_master_volume(dev, &initialVolume))) {
224 mMasterVolumeSupportLvl = MVS_FULL;
225 } else {
226 mMasterVolumeSupportLvl = MVS_SETONLY;
227 initialVolume = 1.0;
228 }
229
230 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
231 if ((NULL == dev->set_master_volume) ||
232 (NO_ERROR != dev->set_master_volume(dev, initialVolume))) {
233 mMasterVolumeSupportLvl = MVS_NONE;
234 }
235 mHardwareStatus = AUDIO_HW_INIT;
236 }
237
238 // Set the mode for each audio HAL, and try to set the initial volume (if
239 // supported) for all of the non-primary audio HALs.
Dima Zavin799a70e2011-04-18 16:57:27 -0700240 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
241 audio_hw_device_t *dev = mAudioHwDevs[i];
242
243 mHardwareStatus = AUDIO_HW_INIT;
244 rc = dev->init_check(dev);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800245 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700246 if (rc == 0) {
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800247 mMode = AUDIO_MODE_NORMAL; // assigned multiple times with same value
Dima Zavin799a70e2011-04-18 16:57:27 -0700248 mHardwareStatus = AUDIO_HW_SET_MODE;
249 dev->set_mode(dev, mMode);
John Grossman4ff14ba2012-02-08 16:37:41 -0800250
251 if ((dev != mPrimaryHardwareDev) &&
252 (NULL != dev->set_master_volume)) {
253 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
254 dev->set_master_volume(dev, initialVolume);
255 }
256
257 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavin799a70e2011-04-18 16:57:27 -0700258 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700259 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800260
261 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
262 ? initialVolume
263 : 1.0;
264 mMasterVolume = initialVolume;
265 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700266}
267
268AudioFlinger::~AudioFlinger()
269{
Dima Zavin799a70e2011-04-18 16:57:27 -0700270
Mathias Agopian65ab4712010-07-14 17:59:35 -0700271 while (!mRecordThreads.isEmpty()) {
272 // closeInput() will remove first entry from mRecordThreads
273 closeInput(mRecordThreads.keyAt(0));
274 }
275 while (!mPlaybackThreads.isEmpty()) {
276 // closeOutput() will remove first entry from mPlaybackThreads
277 closeOutput(mPlaybackThreads.keyAt(0));
278 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700279
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800280 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
281 // no mHardwareLock needed, as there are no other references to this
282 audio_hw_device_close(mAudioHwDevs[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700283 }
284}
285
Dima Zavin799a70e2011-04-18 16:57:27 -0700286audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
287{
288 /* first matching HW device is returned */
289 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
290 audio_hw_device_t *dev = mAudioHwDevs[i];
291 if ((dev->get_supported_devices(dev) & devices) == devices)
292 return dev;
293 }
294 return NULL;
295}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700296
297status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
298{
299 const size_t SIZE = 256;
300 char buffer[SIZE];
301 String8 result;
302
303 result.append("Clients:\n");
304 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800305 sp<Client> client = mClients.valueAt(i).promote();
306 if (client != 0) {
307 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
308 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700309 }
310 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700311
312 result.append("Global session refs:\n");
313 result.append(" session pid cnt\n");
314 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
315 AudioSessionRef *r = mAudioSessionRefs[i];
316 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
317 result.append(buffer);
318 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700319 write(fd, result.string(), result.size());
320 return NO_ERROR;
321}
322
323
324status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
325{
326 const size_t SIZE = 256;
327 char buffer[SIZE];
328 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800329 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700330
John Grossman4ff14ba2012-02-08 16:37:41 -0800331 snprintf(buffer, SIZE, "Hardware status: %d\n"
332 "Standby Time mSec: %u\n",
333 hardwareStatus,
334 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700335 result.append(buffer);
336 write(fd, result.string(), result.size());
337 return NO_ERROR;
338}
339
340status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
341{
342 const size_t SIZE = 256;
343 char buffer[SIZE];
344 String8 result;
345 snprintf(buffer, SIZE, "Permission Denial: "
346 "can't dump AudioFlinger from pid=%d, uid=%d\n",
347 IPCThreadState::self()->getCallingPid(),
348 IPCThreadState::self()->getCallingUid());
349 result.append(buffer);
350 write(fd, result.string(), result.size());
351 return NO_ERROR;
352}
353
354static bool tryLock(Mutex& mutex)
355{
356 bool locked = false;
357 for (int i = 0; i < kDumpLockRetries; ++i) {
358 if (mutex.tryLock() == NO_ERROR) {
359 locked = true;
360 break;
361 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800362 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700363 }
364 return locked;
365}
366
367status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
368{
Glenn Kasten44deb052012-02-05 18:09:08 -0800369 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700370 dumpPermissionDenial(fd, args);
371 } else {
372 // get state of hardware lock
373 bool hardwareLocked = tryLock(mHardwareLock);
374 if (!hardwareLocked) {
375 String8 result(kHardwareLockedString);
376 write(fd, result.string(), result.size());
377 } else {
378 mHardwareLock.unlock();
379 }
380
381 bool locked = tryLock(mLock);
382
383 // failed to lock - AudioFlinger is probably deadlocked
384 if (!locked) {
385 String8 result(kDeadlockedString);
386 write(fd, result.string(), result.size());
387 }
388
389 dumpClients(fd, args);
390 dumpInternals(fd, args);
391
392 // dump playback threads
393 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
394 mPlaybackThreads.valueAt(i)->dump(fd, args);
395 }
396
397 // dump record threads
398 for (size_t i = 0; i < mRecordThreads.size(); i++) {
399 mRecordThreads.valueAt(i)->dump(fd, args);
400 }
401
Dima Zavin799a70e2011-04-18 16:57:27 -0700402 // dump all hardware devs
403 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
404 audio_hw_device_t *dev = mAudioHwDevs[i];
405 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700406 }
407 if (locked) mLock.unlock();
408 }
409 return NO_ERROR;
410}
411
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800412sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
413{
414 // If pid is already in the mClients wp<> map, then use that entry
415 // (for which promote() is always != 0), otherwise create a new entry and Client.
416 sp<Client> client = mClients.valueFor(pid).promote();
417 if (client == 0) {
418 client = new Client(this, pid);
419 mClients.add(pid, client);
420 }
421
422 return client;
423}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700424
425// IAudioFlinger interface
426
427
428sp<IAudioTrack> AudioFlinger::createTrack(
429 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800430 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700431 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800432 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700433 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700434 int frameCount,
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{
825 status_t result;
826
Glenn Kasten23d82a92012-02-03 11:10:00 -0800827 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700828 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
829 // check calling permissions
830 if (!settingsAllowed()) {
831 return PERMISSION_DENIED;
832 }
833
Mathias Agopian65ab4712010-07-14 17:59:35 -0700834 // ioHandle == 0 means the parameters are global to the audio hardware interface
835 if (ioHandle == 0) {
836 AutoMutex lock(mHardwareLock);
837 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700838 status_t final_result = NO_ERROR;
839 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
840 audio_hw_device_t *dev = mAudioHwDevs[i];
841 result = dev->set_parameters(dev, keyValuePairs.string());
842 final_result = result ?: final_result;
843 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700844 mHardwareStatus = AUDIO_HW_IDLE;
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++) {
907 audio_hw_device_t *dev = mAudioHwDevs[i];
908 char *s = dev->get_parameters(dev, keys.string());
John Grossmanef7740b2012-02-09 11:28:36 -0800909 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700910 free(s);
911 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700912 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700913 }
914
915 Mutex::Autolock _l(mLock);
916
917 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
918 if (playbackThread != NULL) {
919 return playbackThread->getParameters(keys);
920 }
921 RecordThread *recordThread = checkRecordThread_l(ioHandle);
922 if (recordThread != NULL) {
923 return recordThread->getParameters(keys);
924 }
925 return String8("");
926}
927
Glenn Kastenf587ba52012-01-26 16:25:10 -0800928size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700929{
Eric Laurenta1884f92011-08-23 08:25:03 -0700930 status_t ret = initCheck();
931 if (ret != NO_ERROR) {
932 return 0;
933 }
934
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800935 AutoMutex lock(mHardwareLock);
936 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
937 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
938 mHardwareStatus = AUDIO_HW_IDLE;
939 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700940}
941
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800942unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700943{
944 if (ioHandle == 0) {
945 return 0;
946 }
947
948 Mutex::Autolock _l(mLock);
949
950 RecordThread *recordThread = checkRecordThread_l(ioHandle);
951 if (recordThread != NULL) {
952 return recordThread->getInputFramesLost();
953 }
954 return 0;
955}
956
957status_t AudioFlinger::setVoiceVolume(float value)
958{
Eric Laurenta1884f92011-08-23 08:25:03 -0700959 status_t ret = initCheck();
960 if (ret != NO_ERROR) {
961 return ret;
962 }
963
Mathias Agopian65ab4712010-07-14 17:59:35 -0700964 // check calling permissions
965 if (!settingsAllowed()) {
966 return PERMISSION_DENIED;
967 }
968
969 AutoMutex lock(mHardwareLock);
970 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700971 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700972 mHardwareStatus = AUDIO_HW_IDLE;
973
974 return ret;
975}
976
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800977status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
978 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700979{
980 status_t status;
981
982 Mutex::Autolock _l(mLock);
983
984 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
985 if (playbackThread != NULL) {
986 return playbackThread->getRenderPosition(halFrames, dspFrames);
987 }
988
989 return BAD_VALUE;
990}
991
992void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
993{
994
995 Mutex::Autolock _l(mLock);
996
Glenn Kastenbb001922012-02-03 11:10:26 -0800997 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700998 if (mNotificationClients.indexOfKey(pid) < 0) {
999 sp<NotificationClient> notificationClient = new NotificationClient(this,
1000 client,
1001 pid);
Steve Block3856b092011-10-20 11:56:00 +01001002 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001003
1004 mNotificationClients.add(pid, notificationClient);
1005
1006 sp<IBinder> binder = client->asBinder();
1007 binder->linkToDeath(notificationClient);
1008
1009 // the config change is always sent from playback or record threads to avoid deadlock
1010 // with AudioSystem::gLock
1011 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1012 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1013 }
1014
1015 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1016 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1017 }
1018 }
1019}
1020
1021void AudioFlinger::removeNotificationClient(pid_t pid)
1022{
1023 Mutex::Autolock _l(mLock);
1024
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001025 ssize_t index = mNotificationClients.indexOfKey(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001026 if (index >= 0) {
1027 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block3856b092011-10-20 11:56:00 +01001028 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001029 mNotificationClients.removeItem(pid);
1030 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001031
Steve Block3856b092011-10-20 11:56:00 +01001032 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001033 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001034 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001035 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001036 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +01001037 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001038 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +01001039 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001040 mAudioSessionRefs.removeAt(i);
1041 delete ref;
1042 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001043 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001044 } else {
1045 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001046 }
1047 }
1048 if (removed) {
1049 purgeStaleEffects_l();
1050 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001051}
1052
1053// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001054void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001055{
1056 size_t size = mNotificationClients.size();
1057 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001058 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1059 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001060 }
1061}
1062
1063// removeClient_l() must be called with AudioFlinger::mLock held
1064void AudioFlinger::removeClient_l(pid_t pid)
1065{
Steve Block3856b092011-10-20 11:56:00 +01001066 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001067 mClients.removeItem(pid);
1068}
1069
1070
1071// ----------------------------------------------------------------------------
1072
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001073AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1074 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001075 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001076 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001077 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
1078 // mChannelMask
1079 mChannelCount(0),
1080 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1081 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001082 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001083 mDevice(device),
1084 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001085{
1086}
1087
1088AudioFlinger::ThreadBase::~ThreadBase()
1089{
1090 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001091 // do not lock the mutex in destructor
1092 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001093 if (mPowerManager != 0) {
1094 sp<IBinder> binder = mPowerManager->asBinder();
1095 binder->unlinkToDeath(mDeathRecipient);
1096 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001097}
1098
1099void AudioFlinger::ThreadBase::exit()
1100{
Steve Block3856b092011-10-20 11:56:00 +01001101 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001102 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001103 // This lock prevents the following race in thread (uniprocessor for illustration):
1104 // if (!exitPending()) {
1105 // // context switch from here to exit()
1106 // // exit() calls requestExit(), what exitPending() observes
1107 // // exit() calls signal(), which is dropped since no waiters
1108 // // context switch back from exit() to here
1109 // mWaitWorkCV.wait(...);
1110 // // now thread is hung
1111 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001112 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001113 requestExit();
1114 mWaitWorkCV.signal();
1115 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001116 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1117 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001118 requestExitAndWait();
1119}
1120
Mathias Agopian65ab4712010-07-14 17:59:35 -07001121status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1122{
1123 status_t status;
1124
Steve Block3856b092011-10-20 11:56:00 +01001125 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001126 Mutex::Autolock _l(mLock);
1127
1128 mNewParameters.add(keyValuePairs);
1129 mWaitWorkCV.signal();
1130 // wait condition with timeout in case the thread loop has exited
1131 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001132 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001133 status = mParamStatus;
1134 mWaitWorkCV.signal();
1135 } else {
1136 status = TIMED_OUT;
1137 }
1138 return status;
1139}
1140
1141void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1142{
1143 Mutex::Autolock _l(mLock);
1144 sendConfigEvent_l(event, param);
1145}
1146
1147// sendConfigEvent_l() must be called with ThreadBase::mLock held
1148void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1149{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001150 ConfigEvent configEvent;
1151 configEvent.mEvent = event;
1152 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001153 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001154 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001155 mWaitWorkCV.signal();
1156}
1157
1158void AudioFlinger::ThreadBase::processConfigEvents()
1159{
1160 mLock.lock();
1161 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001162 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001163 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001164 mConfigEvents.removeAt(0);
1165 // release mLock before locking AudioFlinger mLock: lock order is always
1166 // AudioFlinger then ThreadBase to avoid cross deadlock
1167 mLock.unlock();
1168 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001169 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001170 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001171 mLock.lock();
1172 }
1173 mLock.unlock();
1174}
1175
1176status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1177{
1178 const size_t SIZE = 256;
1179 char buffer[SIZE];
1180 String8 result;
1181
1182 bool locked = tryLock(mLock);
1183 if (!locked) {
1184 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1185 write(fd, buffer, strlen(buffer));
1186 }
1187
1188 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1189 result.append(buffer);
1190 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1191 result.append(buffer);
1192 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1193 result.append(buffer);
1194 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1195 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001196 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1197 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001198 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1199 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001200 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001201 result.append(buffer);
1202
1203 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1204 result.append(buffer);
1205 result.append(" Index Command");
1206 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1207 snprintf(buffer, SIZE, "\n %02d ", i);
1208 result.append(buffer);
1209 result.append(mNewParameters[i]);
1210 }
1211
1212 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1213 result.append(buffer);
1214 snprintf(buffer, SIZE, " Index event param\n");
1215 result.append(buffer);
1216 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001217 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001218 result.append(buffer);
1219 }
1220 result.append("\n");
1221
1222 write(fd, result.string(), result.size());
1223
1224 if (locked) {
1225 mLock.unlock();
1226 }
1227 return NO_ERROR;
1228}
1229
Eric Laurent1d2bff02011-07-24 17:49:51 -07001230status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1231{
1232 const size_t SIZE = 256;
1233 char buffer[SIZE];
1234 String8 result;
1235
1236 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1237 write(fd, buffer, strlen(buffer));
1238
1239 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1240 sp<EffectChain> chain = mEffectChains[i];
1241 if (chain != 0) {
1242 chain->dump(fd, args);
1243 }
1244 }
1245 return NO_ERROR;
1246}
1247
Eric Laurentfeb0db62011-07-22 09:04:31 -07001248void AudioFlinger::ThreadBase::acquireWakeLock()
1249{
1250 Mutex::Autolock _l(mLock);
1251 acquireWakeLock_l();
1252}
1253
1254void AudioFlinger::ThreadBase::acquireWakeLock_l()
1255{
1256 if (mPowerManager == 0) {
1257 // use checkService() to avoid blocking if power service is not up yet
1258 sp<IBinder> binder =
1259 defaultServiceManager()->checkService(String16("power"));
1260 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001261 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001262 } else {
1263 mPowerManager = interface_cast<IPowerManager>(binder);
1264 binder->linkToDeath(mDeathRecipient);
1265 }
1266 }
1267 if (mPowerManager != 0) {
1268 sp<IBinder> binder = new BBinder();
1269 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1270 binder,
1271 String16(mName));
1272 if (status == NO_ERROR) {
1273 mWakeLockToken = binder;
1274 }
Steve Block3856b092011-10-20 11:56:00 +01001275 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001276 }
1277}
1278
1279void AudioFlinger::ThreadBase::releaseWakeLock()
1280{
1281 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001282 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001283}
1284
1285void AudioFlinger::ThreadBase::releaseWakeLock_l()
1286{
1287 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001288 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001289 if (mPowerManager != 0) {
1290 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1291 }
1292 mWakeLockToken.clear();
1293 }
1294}
1295
1296void AudioFlinger::ThreadBase::clearPowerManager()
1297{
1298 Mutex::Autolock _l(mLock);
1299 releaseWakeLock_l();
1300 mPowerManager.clear();
1301}
1302
1303void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1304{
1305 sp<ThreadBase> thread = mThread.promote();
1306 if (thread != 0) {
1307 thread->clearPowerManager();
1308 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001309 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001310}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001311
Eric Laurent59255e42011-07-27 19:49:51 -07001312void AudioFlinger::ThreadBase::setEffectSuspended(
1313 const effect_uuid_t *type, bool suspend, int sessionId)
1314{
1315 Mutex::Autolock _l(mLock);
1316 setEffectSuspended_l(type, suspend, sessionId);
1317}
1318
1319void AudioFlinger::ThreadBase::setEffectSuspended_l(
1320 const effect_uuid_t *type, bool suspend, int sessionId)
1321{
Glenn Kasten090f0192012-01-30 13:00:02 -08001322 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001323 if (chain != 0) {
1324 if (type != NULL) {
1325 chain->setEffectSuspended_l(type, suspend);
1326 } else {
1327 chain->setEffectSuspendedAll_l(suspend);
1328 }
1329 }
1330
1331 updateSuspendedSessions_l(type, suspend, sessionId);
1332}
1333
1334void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1335{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001336 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001337 if (index < 0) {
1338 return;
1339 }
1340
1341 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1342 mSuspendedSessions.editValueAt(index);
1343
1344 for (size_t i = 0; i < sessionEffects.size(); i++) {
1345 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1346 for (int j = 0; j < desc->mRefCount; j++) {
1347 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1348 chain->setEffectSuspendedAll_l(true);
1349 } else {
Steve Block3856b092011-10-20 11:56:00 +01001350 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001351 desc->mType.timeLow);
1352 chain->setEffectSuspended_l(&desc->mType, true);
1353 }
1354 }
1355 }
1356}
1357
Eric Laurent59255e42011-07-27 19:49:51 -07001358void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1359 bool suspend,
1360 int sessionId)
1361{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001362 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001363
1364 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1365
1366 if (suspend) {
1367 if (index >= 0) {
1368 sessionEffects = mSuspendedSessions.editValueAt(index);
1369 } else {
1370 mSuspendedSessions.add(sessionId, sessionEffects);
1371 }
1372 } else {
1373 if (index < 0) {
1374 return;
1375 }
1376 sessionEffects = mSuspendedSessions.editValueAt(index);
1377 }
1378
1379
1380 int key = EffectChain::kKeyForSuspendAll;
1381 if (type != NULL) {
1382 key = type->timeLow;
1383 }
1384 index = sessionEffects.indexOfKey(key);
1385
1386 sp <SuspendedSessionDesc> desc;
1387 if (suspend) {
1388 if (index >= 0) {
1389 desc = sessionEffects.valueAt(index);
1390 } else {
1391 desc = new SuspendedSessionDesc();
1392 if (type != NULL) {
1393 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1394 }
1395 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001396 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001397 }
1398 desc->mRefCount++;
1399 } else {
1400 if (index < 0) {
1401 return;
1402 }
1403 desc = sessionEffects.valueAt(index);
1404 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001405 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001406 sessionEffects.removeItemsAt(index);
1407 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001408 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001409 sessionId);
1410 mSuspendedSessions.removeItem(sessionId);
1411 }
1412 }
1413 }
1414 if (!sessionEffects.isEmpty()) {
1415 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1416 }
1417}
1418
1419void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1420 bool enabled,
1421 int sessionId)
1422{
1423 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001424 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1425}
Eric Laurent59255e42011-07-27 19:49:51 -07001426
Eric Laurenta85a74a2011-10-19 11:44:54 -07001427void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1428 bool enabled,
1429 int sessionId)
1430{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001431 if (mType != RECORD) {
1432 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1433 // another session. This gives the priority to well behaved effect control panels
1434 // and applications not using global effects.
1435 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1436 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1437 }
1438 }
Eric Laurent59255e42011-07-27 19:49:51 -07001439
1440 sp<EffectChain> chain = getEffectChain_l(sessionId);
1441 if (chain != 0) {
1442 chain->checkSuspendOnEffectEnabled(effect, enabled);
1443 }
1444}
1445
Mathias Agopian65ab4712010-07-14 17:59:35 -07001446// ----------------------------------------------------------------------------
1447
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001448AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1449 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001450 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001451 uint32_t device,
1452 type_t type)
1453 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001454 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1455 // Assumes constructor is called by AudioFlinger with it's mLock held,
1456 // but it would be safer to explicitly pass initial masterMute as parameter
1457 mMasterMute(audioFlinger->masterMute_l()),
1458 // mStreamTypes[] initialized in constructor body
1459 mOutput(output),
1460 // Assumes constructor is called by AudioFlinger with it's mLock held,
1461 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001462 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001463 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001464{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001465 snprintf(mName, kNameLength, "AudioOut_%d", id);
1466
Mathias Agopian65ab4712010-07-14 17:59:35 -07001467 readOutputParameters();
1468
Glenn Kasten263709e2012-01-06 08:40:01 -08001469 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001470 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1471 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1472 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001473 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1474 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001475 // initialized by stream_type_t default constructor
1476 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001477 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001478 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1479 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001480}
1481
1482AudioFlinger::PlaybackThread::~PlaybackThread()
1483{
1484 delete [] mMixBuffer;
1485}
1486
1487status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1488{
1489 dumpInternals(fd, args);
1490 dumpTracks(fd, args);
1491 dumpEffectChains(fd, args);
1492 return NO_ERROR;
1493}
1494
1495status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1496{
1497 const size_t SIZE = 256;
1498 char buffer[SIZE];
1499 String8 result;
1500
1501 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1502 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001503 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 -07001504 for (size_t i = 0; i < mTracks.size(); ++i) {
1505 sp<Track> track = mTracks[i];
1506 if (track != 0) {
1507 track->dump(buffer, SIZE);
1508 result.append(buffer);
1509 }
1510 }
1511
1512 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1513 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001514 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 -07001515 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001516 sp<Track> track = mActiveTracks[i].promote();
1517 if (track != 0) {
1518 track->dump(buffer, SIZE);
1519 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001520 }
1521 }
1522 write(fd, result.string(), result.size());
1523 return NO_ERROR;
1524}
1525
Mathias Agopian65ab4712010-07-14 17:59:35 -07001526status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1527{
1528 const size_t SIZE = 256;
1529 char buffer[SIZE];
1530 String8 result;
1531
1532 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1533 result.append(buffer);
1534 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1535 result.append(buffer);
1536 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1537 result.append(buffer);
1538 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1539 result.append(buffer);
1540 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1541 result.append(buffer);
1542 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1543 result.append(buffer);
1544 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1545 result.append(buffer);
1546 write(fd, result.string(), result.size());
1547
1548 dumpBase(fd, args);
1549
1550 return NO_ERROR;
1551}
1552
1553// Thread virtuals
1554status_t AudioFlinger::PlaybackThread::readyToRun()
1555{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001556 status_t status = initCheck();
1557 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001558 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001559 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001560 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001561 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001562 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001563}
1564
1565void AudioFlinger::PlaybackThread::onFirstRef()
1566{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001567 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568}
1569
1570// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1571sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1572 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001573 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001574 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001575 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001576 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001577 int frameCount,
1578 const sp<IMemory>& sharedBuffer,
1579 int sessionId,
John Grossman4ff14ba2012-02-08 16:37:41 -08001580 bool isTimed,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001581 status_t *status)
1582{
1583 sp<Track> track;
1584 status_t lStatus;
1585
1586 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001587 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1588 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001589 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001590 "for output %p with format %d",
1591 sampleRate, format, channelMask, mOutput, mFormat);
1592 lStatus = BAD_VALUE;
1593 goto Exit;
1594 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001595 }
1596 } else {
1597 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1598 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001599 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600 lStatus = BAD_VALUE;
1601 goto Exit;
1602 }
1603 }
1604
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001605 lStatus = initCheck();
1606 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001607 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001608 goto Exit;
1609 }
1610
1611 { // scope for mLock
1612 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001613
1614 // all tracks in same audio session must share the same routing strategy otherwise
1615 // conflicts will happen when tracks are moved from one output to another by audio policy
1616 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001617 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001618 for (size_t i = 0; i < mTracks.size(); ++i) {
1619 sp<Track> t = mTracks[i];
1620 if (t != 0) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001621 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001622 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001623 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001624 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001625 lStatus = BAD_VALUE;
1626 goto Exit;
1627 }
1628 }
1629 }
1630
John Grossman4ff14ba2012-02-08 16:37:41 -08001631 if (!isTimed) {
1632 track = new Track(this, client, streamType, sampleRate, format,
1633 channelMask, frameCount, sharedBuffer, sessionId);
1634 } else {
1635 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1636 channelMask, frameCount, sharedBuffer, sessionId);
1637 }
1638 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001639 lStatus = NO_MEMORY;
1640 goto Exit;
1641 }
1642 mTracks.add(track);
1643
1644 sp<EffectChain> chain = getEffectChain_l(sessionId);
1645 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001646 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001647 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001648 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001649 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001650 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001651
1652 // invalidate track immediately if the stream type was moved to another thread since
1653 // createTrack() was called by the client process.
1654 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001655 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001656 this, streamType);
1657 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1658 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001659 }
1660 lStatus = NO_ERROR;
1661
1662Exit:
1663 if(status) {
1664 *status = lStatus;
1665 }
1666 return track;
1667}
1668
1669uint32_t AudioFlinger::PlaybackThread::latency() const
1670{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001671 Mutex::Autolock _l(mLock);
1672 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001673 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001674 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001675 return 0;
1676 }
1677}
1678
Glenn Kasten6637baa2012-01-09 09:40:36 -08001679void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001680{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001681 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001682 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001683}
1684
Glenn Kasten6637baa2012-01-09 09:40:36 -08001685void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001686{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001687 Mutex::Autolock _l(mLock);
1688 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001689}
1690
Glenn Kasten6637baa2012-01-09 09:40:36 -08001691void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001692{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001693 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001694 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695}
1696
Glenn Kasten6637baa2012-01-09 09:40:36 -08001697void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
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].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001701}
1702
Glenn Kastenfff6d712012-01-12 16:38:12 -08001703float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
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 return mStreamTypes[stream].volume;
1707}
1708
Mathias Agopian65ab4712010-07-14 17:59:35 -07001709// addTrack_l() must be called with ThreadBase::mLock held
1710status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1711{
1712 status_t status = ALREADY_EXISTS;
1713
1714 // set retry count for buffer fill
1715 track->mRetryCount = kMaxTrackStartupRetries;
1716 if (mActiveTracks.indexOf(track) < 0) {
1717 // the track is newly added, make sure it fills up all its
1718 // buffers before playing. This is to ensure the client will
1719 // effectively get the latency it requested.
1720 track->mFillingUpStatus = Track::FS_FILLING;
1721 track->mResetDone = false;
1722 mActiveTracks.add(track);
1723 if (track->mainBuffer() != mMixBuffer) {
1724 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1725 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001726 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001727 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001728 }
1729 }
1730
1731 status = NO_ERROR;
1732 }
1733
Steve Block3856b092011-10-20 11:56:00 +01001734 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001735 mWaitWorkCV.broadcast();
1736
1737 return status;
1738}
1739
1740// destroyTrack_l() must be called with ThreadBase::mLock held
1741void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1742{
1743 track->mState = TrackBase::TERMINATED;
1744 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001745 removeTrack_l(track);
1746 }
1747}
1748
1749void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1750{
1751 mTracks.remove(track);
1752 deleteTrackName_l(track->name());
1753 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1754 if (chain != 0) {
1755 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001756 }
1757}
1758
1759String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1760{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001761 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001762 char *s;
1763
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001764 Mutex::Autolock _l(mLock);
1765 if (initCheck() != NO_ERROR) {
1766 return out_s8;
1767 }
1768
Dima Zavin799a70e2011-04-18 16:57:27 -07001769 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001770 out_s8 = String8(s);
1771 free(s);
1772 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001773}
1774
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001775// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001776void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1777 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001778 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001779
Steve Block3856b092011-10-20 11:56:00 +01001780 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001781
1782 switch (event) {
1783 case AudioSystem::OUTPUT_OPENED:
1784 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001785 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001786 desc.samplingRate = mSampleRate;
1787 desc.format = mFormat;
1788 desc.frameCount = mFrameCount;
1789 desc.latency = latency();
1790 param2 = &desc;
1791 break;
1792
1793 case AudioSystem::STREAM_CONFIG_CHANGED:
1794 param2 = &param;
1795 case AudioSystem::OUTPUT_CLOSED:
1796 default:
1797 break;
1798 }
1799 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1800}
1801
1802void AudioFlinger::PlaybackThread::readOutputParameters()
1803{
Dima Zavin799a70e2011-04-18 16:57:27 -07001804 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001805 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1806 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001807 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001808 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001809 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001810
1811 // FIXME - Current mixer implementation only supports stereo output: Always
1812 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001813 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001814 mMixBuffer = new int16_t[mFrameCount * 2];
1815 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1816
Eric Laurentde070132010-07-13 04:45:46 -07001817 // force reconfiguration of effect chains and engines to take new buffer size and audio
1818 // parameters into account
1819 // Note that mLock is not held when readOutputParameters() is called from the constructor
1820 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1821 // matter.
1822 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1823 Vector< sp<EffectChain> > effectChains = mEffectChains;
1824 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001825 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001826 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001827}
1828
1829status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1830{
Glenn Kastena0d68332012-01-27 16:47:15 -08001831 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001832 return BAD_VALUE;
1833 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001834 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001835 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001836 return INVALID_OPERATION;
1837 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001838 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001839
Dima Zavin799a70e2011-04-18 16:57:27 -07001840 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001841}
1842
Eric Laurent39e94f82010-07-28 01:32:47 -07001843uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001844{
1845 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001846 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001847 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001848 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001849 }
1850
1851 for (size_t i = 0; i < mTracks.size(); ++i) {
1852 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001853 if (sessionId == track->sessionId() &&
1854 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001855 result |= TRACK_SESSION;
1856 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001857 }
1858 }
1859
Eric Laurent39e94f82010-07-28 01:32:47 -07001860 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861}
1862
Eric Laurentde070132010-07-13 04:45:46 -07001863uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1864{
Dima Zavinfce7a472011-04-19 22:30:36 -07001865 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001866 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001867 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1868 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001869 }
1870 for (size_t i = 0; i < mTracks.size(); i++) {
1871 sp<Track> track = mTracks[i];
1872 if (sessionId == track->sessionId() &&
1873 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001874 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07001875 }
1876 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001877 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001878}
1879
Mathias Agopian65ab4712010-07-14 17:59:35 -07001880
Glenn Kastenaed850d2012-01-26 09:46:34 -08001881AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001882{
1883 Mutex::Autolock _l(mLock);
1884 return mOutput;
1885}
1886
1887AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1888{
1889 Mutex::Autolock _l(mLock);
1890 AudioStreamOut *output = mOutput;
1891 mOutput = NULL;
1892 return output;
1893}
1894
1895// this method must always be called either with ThreadBase mLock held or inside the thread loop
1896audio_stream_t* AudioFlinger::PlaybackThread::stream()
1897{
1898 if (mOutput == NULL) {
1899 return NULL;
1900 }
1901 return &mOutput->stream->common;
1902}
1903
Eric Laurent162b40b2011-12-05 09:47:19 -08001904uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1905{
1906 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1907 // decoding and transfer time. So sleeping for half of the latency would likely cause
1908 // underruns
1909 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1910 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1911 } else {
1912 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1913 }
1914}
1915
Mathias Agopian65ab4712010-07-14 17:59:35 -07001916// ----------------------------------------------------------------------------
1917
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001918AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001919 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001920 : PlaybackThread(audioFlinger, output, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001921 mAudioMixer(new AudioMixer(mFrameCount, mSampleRate)),
1922 mPrevMixerStatus(MIXER_IDLE)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001923{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001924 // FIXME - Current mixer implementation only supports stereo output
1925 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001926 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001927 }
1928}
1929
1930AudioFlinger::MixerThread::~MixerThread()
1931{
1932 delete mAudioMixer;
1933}
1934
1935bool AudioFlinger::MixerThread::threadLoop()
1936{
1937 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08001938 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001939 nsecs_t standbyTime = systemTime();
1940 size_t mixBufferSize = mFrameCount * mFrameSize;
1941 // FIXME: Relaxed timing because of a certain device that can't meet latency
1942 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001943 // increase threshold again due to low power audio mode. The way this warning threshold is
1944 // calculated and its usefulness should be reconsidered anyway.
1945 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001946 nsecs_t lastWarning = 0;
1947 bool longStandbyExit = false;
1948 uint32_t activeSleepTime = activeSleepTimeUs();
1949 uint32_t idleSleepTime = idleSleepTimeUs();
1950 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001951 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001952 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001953#ifdef DEBUG_CPU_USAGE
1954 ThreadCpuUsage cpu;
1955 const CentralTendencyStatistics& stats = cpu.statistics();
1956#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001957
Eric Laurentfeb0db62011-07-22 09:04:31 -07001958 acquireWakeLock();
1959
Mathias Agopian65ab4712010-07-14 17:59:35 -07001960 while (!exitPending())
1961 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001962#ifdef DEBUG_CPU_USAGE
1963 cpu.sampleAndEnable();
1964 unsigned n = stats.n();
1965 // cpu.elapsed() is expensive, so don't call it every loop
1966 if ((n & 127) == 1) {
1967 long long elapsed = cpu.elapsed();
1968 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1969 double perLoop = elapsed / (double) n;
1970 double perLoop100 = perLoop * 0.01;
1971 double mean = stats.mean();
1972 double stddev = stats.stddev();
1973 double minimum = stats.minimum();
1974 double maximum = stats.maximum();
1975 cpu.resetStatistics();
Steve Blockdf64d152012-01-04 20:05:49 +00001976 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 -07001977 elapsed * .000000001, n, perLoop * .000001,
1978 mean * .001,
1979 stddev * .001,
1980 minimum * .001,
1981 maximum * .001,
1982 mean / perLoop100,
1983 stddev / perLoop100,
1984 minimum / perLoop100,
1985 maximum / perLoop100);
1986 }
1987 }
1988#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001989 processConfigEvents();
1990
1991 mixerStatus = MIXER_IDLE;
1992 { // scope for mLock
1993
1994 Mutex::Autolock _l(mLock);
1995
1996 if (checkForNewParameters_l()) {
1997 mixBufferSize = mFrameCount * mFrameSize;
1998 // FIXME: Relaxed timing because of a certain device that can't meet latency
1999 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07002000 // increase threshold again due to low power audio mode. The way this warning
2001 // threshold is calculated and its usefulness should be reconsidered anyway.
2002 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002003 activeSleepTime = activeSleepTimeUs();
2004 idleSleepTime = idleSleepTimeUs();
2005 }
2006
2007 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2008
2009 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002010 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2011 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002012 if (!mStandby) {
Glenn Kasten90bebef2012-01-27 15:24:38 -08002013 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07002014 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002015 mStandby = true;
2016 mBytesWritten = 0;
2017 }
2018
2019 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2020 // we're about to wait, flush the binder command buffer
2021 IPCThreadState::self()->flushCommands();
2022
2023 if (exitPending()) break;
2024
Eric Laurentfeb0db62011-07-22 09:04:31 -07002025 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002026 // wait until we have something to do...
Glenn Kasten90bebef2012-01-27 15:24:38 -08002027 ALOGV("MixerThread %p TID %d going to sleep", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002028 mWaitWorkCV.wait(mLock);
Glenn Kasten90bebef2012-01-27 15:24:38 -08002029 ALOGV("MixerThread %p TID %d waking up", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002030 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002031
Eric Laurent27741442012-01-17 19:20:12 -08002032 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08002033 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002034 char value[PROPERTY_VALUE_MAX];
2035 property_get("ro.audio.silent", value, "0");
2036 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002037 ALOGD("Silence is golden");
Glenn Kasten6637baa2012-01-09 09:40:36 -08002038 setMasterMute_l(true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002039 }
2040 }
2041
John Grossman4ff14ba2012-02-08 16:37:41 -08002042 standbyTime = systemTime() + mStandbyTimeInNsecs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002043 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08002044 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002045 continue;
2046 }
2047 }
2048
2049 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
2050
2051 // prevent any changes in effect chain list and in each effect chain
2052 // during mixing and effect process as the audio buffers could be deleted
2053 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002054 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002055 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002056
Glenn Kastenf6b16782011-12-15 09:51:17 -08002057 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08002058 // obtain the presentation timestamp of the next output buffer
2059 int64_t pts;
2060 status_t status = INVALID_OPERATION;
2061
2062 if (NULL != mOutput->stream->get_next_write_timestamp) {
2063 status = mOutput->stream->get_next_write_timestamp(
2064 mOutput->stream, &pts);
2065 }
2066
2067 if (status != NO_ERROR) {
2068 pts = AudioBufferProvider::kInvalidPTS;
2069 }
2070
Mathias Agopian65ab4712010-07-14 17:59:35 -07002071 // mix buffers...
John Grossman4ff14ba2012-02-08 16:37:41 -08002072 mAudioMixer->process(pts);
Eric Laurent21e4b6e2012-01-23 18:56:59 -08002073 // increase sleep time progressively when application underrun condition clears.
2074 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2075 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2076 // such that we would underrun the audio HAL.
2077 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08002078 sleepTimeShift--;
2079 }
Eric Laurent21e4b6e2012-01-23 18:56:59 -08002080 sleepTime = 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08002081 standbyTime = systemTime() + mStandbyTimeInNsecs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002082 //TODO: delay standby when effects have a tail
2083 } else {
2084 // If no tracks are ready, sleep once for the duration of an output
2085 // buffer size, then write 0s to the output
2086 if (sleepTime == 0) {
2087 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08002088 sleepTime = activeSleepTime >> sleepTimeShift;
2089 if (sleepTime < kMinThreadSleepTimeUs) {
2090 sleepTime = kMinThreadSleepTimeUs;
2091 }
2092 // reduce sleep time in case of consecutive application underruns to avoid
2093 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2094 // duration we would end up writing less data than needed by the audio HAL if
2095 // the condition persists.
2096 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2097 sleepTimeShift++;
2098 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002099 } else {
2100 sleepTime = idleSleepTime;
2101 }
2102 } else if (mBytesWritten != 0 ||
2103 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2104 memset (mMixBuffer, 0, mixBufferSize);
2105 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01002106 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002107 }
2108 // TODO add standby time extension fct of effect tail
2109 }
2110
2111 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002112 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002113 }
2114 // sleepTime == 0 means we must write to audio hardware
2115 if (sleepTime == 0) {
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002116 for (size_t i = 0; i < effectChains.size(); i ++) {
2117 effectChains[i]->process_l();
2118 }
2119 // enable changes in effect chain
2120 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002121 mLastWriteTime = systemTime();
2122 mInWrite = true;
2123 mBytesWritten += mixBufferSize;
2124
Dima Zavin799a70e2011-04-18 16:57:27 -07002125 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002126 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2127 mNumWrites++;
2128 mInWrite = false;
2129 nsecs_t now = systemTime();
2130 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002131 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002132 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002133 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002134 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002135 ns2ms(delta), mNumDelayedWrites, this);
2136 lastWarning = now;
2137 }
2138 if (mStandby) {
2139 longStandbyExit = true;
2140 }
2141 }
2142 mStandby = false;
2143 } else {
2144 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002145 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002146 usleep(sleepTime);
2147 }
2148
2149 // finally let go of all our tracks, without the lock held
2150 // since we can't guarantee the destructors won't acquire that
2151 // same lock.
2152 tracksToRemove.clear();
2153
2154 // Effect chains will be actually deleted here if they were removed from
2155 // mEffectChains list during mixing or effects processing
2156 effectChains.clear();
2157 }
2158
2159 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002160 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002161 }
2162
Eric Laurentfeb0db62011-07-22 09:04:31 -07002163 releaseWakeLock();
2164
Steve Block3856b092011-10-20 11:56:00 +01002165 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002166 return false;
2167}
2168
2169// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002170AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2171 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002172{
2173
Glenn Kasten29c23c32012-01-26 13:37:52 -08002174 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002175 // find out which tracks need to be processed
2176 size_t count = activeTracks.size();
2177 size_t mixedTracks = 0;
2178 size_t tracksWithEffect = 0;
2179
2180 float masterVolume = mMasterVolume;
2181 bool masterMute = mMasterMute;
2182
Eric Laurent571d49c2010-08-11 05:20:11 -07002183 if (masterMute) {
2184 masterVolume = 0;
2185 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002186 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002187 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002188 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002189 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002190 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002191 masterVolume = (float)((v + (1 << 23)) >> 24);
2192 chain.clear();
2193 }
2194
2195 for (size_t i=0 ; i<count ; i++) {
2196 sp<Track> t = activeTracks[i].promote();
2197 if (t == 0) continue;
2198
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002199 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002200 Track* const track = t.get();
2201 audio_track_cblk_t* cblk = track->cblk();
2202
2203 // The first time a track is added we wait
2204 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002205 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002206 // make sure that we have enough frames to mix one full buffer.
2207 // enforce this condition only once to enable draining the buffer in case the client
2208 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002209 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002210 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002211 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002212 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002213 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002214 if (t->sampleRate() == (int)mSampleRate) {
2215 minFrames = mFrameCount;
2216 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002217 // +1 for rounding and +1 for additional sample needed for interpolation
2218 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2219 // add frames already consumed but not yet released by the resampler
2220 // because cblk->framesReady() will include these frames
2221 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2222 // the minimum track buffer size is normally twice the number of frames necessary
2223 // to fill one buffer and the resampler should not leave more than one buffer worth
2224 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002225 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002226 }
2227 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002228 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002229 !track->isPaused() && !track->isTerminated())
2230 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002231 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002232
2233 mixedTracks++;
2234
2235 // track->mainBuffer() != mMixBuffer means there is an effect chain
2236 // connected to the track
2237 chain.clear();
2238 if (track->mainBuffer() != mMixBuffer) {
2239 chain = getEffectChain_l(track->sessionId());
2240 // Delegate volume control to effect in track effect chain if needed
2241 if (chain != 0) {
2242 tracksWithEffect++;
2243 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002244 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002245 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002246 }
2247 }
2248
2249
2250 int param = AudioMixer::VOLUME;
2251 if (track->mFillingUpStatus == Track::FS_FILLED) {
2252 // no ramp for the first volume setting
2253 track->mFillingUpStatus = Track::FS_ACTIVE;
2254 if (track->mState == TrackBase::RESUMING) {
2255 track->mState = TrackBase::ACTIVE;
2256 param = AudioMixer::RAMP_VOLUME;
2257 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002258 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002259 } else if (cblk->server != 0) {
2260 // If the track is stopped before the first frame was mixed,
2261 // do not apply ramp
2262 param = AudioMixer::RAMP_VOLUME;
2263 }
2264
2265 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002266 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002267 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002268 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002269 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002270 if (track->isPausing()) {
2271 track->setPaused();
2272 }
2273 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002274
Mathias Agopian65ab4712010-07-14 17:59:35 -07002275 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002276 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002277 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002278 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002279 vl = vlr & 0xFFFF;
2280 vr = vlr >> 16;
2281 // track volumes come from shared memory, so can't be trusted and must be clamped
2282 if (vl > MAX_GAIN_INT) {
2283 ALOGV("Track left volume out of range: %04X", vl);
2284 vl = MAX_GAIN_INT;
2285 }
2286 if (vr > MAX_GAIN_INT) {
2287 ALOGV("Track right volume out of range: %04X", vr);
2288 vr = MAX_GAIN_INT;
2289 }
2290 // now apply the master volume and stream type volume
2291 vl = (uint32_t)(v * vl) << 12;
2292 vr = (uint32_t)(v * vr) << 12;
2293 // assuming master volume and stream type volume each go up to 1.0,
2294 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002295
Glenn Kasten05632a52012-01-03 14:22:33 -08002296 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2297 // send level comes from shared memory and so may be corrupt
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002298 if (sendLevel >= MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002299 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002300 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002301 }
2302 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002303 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002304 // Delegate volume control to effect in track effect chain if needed
2305 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2306 // Do not ramp volume if volume is controlled by effect
2307 param = AudioMixer::VOLUME;
2308 track->mHasVolumeController = true;
2309 } else {
2310 // force no volume ramp when volume controller was just disabled or removed
2311 // from effect chain to avoid volume spike
2312 if (track->mHasVolumeController) {
2313 param = AudioMixer::VOLUME;
2314 }
2315 track->mHasVolumeController = false;
2316 }
2317
2318 // Convert volumes from 8.24 to 4.12 format
2319 int16_t left, right, aux;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002320 // This additional clamping is needed in case chain->setVolume_l() overshot
Eric Laurente0aed6d2010-09-10 17:44:44 -07002321 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2322 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2323 left = int16_t(v_clamped);
2324 v_clamped = (vr + (1 << 11)) >> 12;
2325 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2326 right = int16_t(v_clamped);
2327
2328 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2329 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002330
Mathias Agopian65ab4712010-07-14 17:59:35 -07002331 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002332 mAudioMixer->setBufferProvider(name, track);
2333 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002334
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002335 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2336 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2337 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002338 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002339 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002340 AudioMixer::TRACK,
2341 AudioMixer::FORMAT, (void *)track->format());
2342 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002343 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002344 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002345 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002346 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002347 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002348 AudioMixer::RESAMPLE,
2349 AudioMixer::SAMPLE_RATE,
2350 (void *)(cblk->sampleRate));
2351 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002352 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002353 AudioMixer::TRACK,
2354 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2355 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002356 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002357 AudioMixer::TRACK,
2358 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2359
2360 // reset retry count
2361 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002362 // If one track is ready, set the mixer ready if:
2363 // - the mixer was not ready during previous round OR
2364 // - no other track is not ready
2365 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2366 mixerStatus != MIXER_TRACKS_ENABLED) {
2367 mixerStatus = MIXER_TRACKS_READY;
2368 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002369 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002370 //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 -07002371 if (track->isStopped()) {
2372 track->reset();
2373 }
2374 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2375 // We have consumed all the buffers of this track.
2376 // Remove it from the list of active tracks.
2377 tracksToRemove->add(track);
2378 } else {
2379 // No buffers for this track. Give it a few chances to
2380 // fill a buffer, then remove it from active list.
2381 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002382 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002383 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002384 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002385 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002386 // If one track is not ready, mark the mixer also not ready if:
2387 // - the mixer was ready during previous round OR
2388 // - no other track is ready
2389 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2390 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002391 mixerStatus = MIXER_TRACKS_ENABLED;
2392 }
2393 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002394 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002395 }
2396 }
2397
2398 // remove all the tracks that need to be...
2399 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002400 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002401 for (size_t i=0 ; i<count ; i++) {
2402 const sp<Track>& track = tracksToRemove->itemAt(i);
2403 mActiveTracks.remove(track);
2404 if (track->mainBuffer() != mMixBuffer) {
2405 chain = getEffectChain_l(track->sessionId());
2406 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002407 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002408 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002409 }
2410 }
2411 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002412 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002413 }
2414 }
2415 }
2416
2417 // mix buffer must be cleared if all tracks are connected to an
2418 // effect chain as in this case the mixer will not write to
2419 // mix buffer and track effects will accumulate into it
2420 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2421 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2422 }
2423
Eric Laurent27741442012-01-17 19:20:12 -08002424 mPrevMixerStatus = mixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002425 return mixerStatus;
2426}
2427
Glenn Kastenfff6d712012-01-12 16:38:12 -08002428void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002429{
Steve Block3856b092011-10-20 11:56:00 +01002430 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002431 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002432 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002433
Mathias Agopian65ab4712010-07-14 17:59:35 -07002434 size_t size = mTracks.size();
2435 for (size_t i = 0; i < size; i++) {
2436 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08002437 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002438 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002439 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002440 }
2441 }
2442}
2443
Glenn Kastenfff6d712012-01-12 16:38:12 -08002444void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002445{
Steve Block3856b092011-10-20 11:56:00 +01002446 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002447 this, streamType, valid);
2448 Mutex::Autolock _l(mLock);
2449
2450 mStreamTypes[streamType].valid = valid;
2451}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002452
2453// getTrackName_l() must be called with ThreadBase::mLock held
2454int AudioFlinger::MixerThread::getTrackName_l()
2455{
2456 return mAudioMixer->getTrackName();
2457}
2458
2459// deleteTrackName_l() must be called with ThreadBase::mLock held
2460void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2461{
Steve Block3856b092011-10-20 11:56:00 +01002462 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002463 mAudioMixer->deleteTrackName(name);
2464}
2465
2466// checkForNewParameters_l() must be called with ThreadBase::mLock held
2467bool AudioFlinger::MixerThread::checkForNewParameters_l()
2468{
2469 bool reconfig = false;
2470
2471 while (!mNewParameters.isEmpty()) {
2472 status_t status = NO_ERROR;
2473 String8 keyValuePair = mNewParameters[0];
2474 AudioParameter param = AudioParameter(keyValuePair);
2475 int value;
2476
2477 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2478 reconfig = true;
2479 }
2480 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002481 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002482 status = BAD_VALUE;
2483 } else {
2484 reconfig = true;
2485 }
2486 }
2487 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002488 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002489 status = BAD_VALUE;
2490 } else {
2491 reconfig = true;
2492 }
2493 }
2494 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2495 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002496 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002497 // if frame count is changed after track creation
2498 if (!mTracks.isEmpty()) {
2499 status = INVALID_OPERATION;
2500 } else {
2501 reconfig = true;
2502 }
2503 }
2504 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002505 // when changing the audio output device, call addBatteryData to notify
2506 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002507 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002508 uint32_t params = 0;
2509 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002510 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002511 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2512 }
2513
2514 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002515 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002516 // check if any other device (except speaker) is on
2517 if (value & deviceWithoutSpeaker ) {
2518 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2519 }
2520
2521 if (params != 0) {
2522 addBatteryData(params);
2523 }
2524 }
2525
Mathias Agopian65ab4712010-07-14 17:59:35 -07002526 // forward device change to effects that have requested to be
2527 // aware of attached audio device.
2528 mDevice = (uint32_t)value;
2529 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002530 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002531 }
2532 }
2533
2534 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002535 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002536 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002537 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002538 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002539 mStandby = true;
2540 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002541 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002542 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002543 }
2544 if (status == NO_ERROR && reconfig) {
2545 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002546 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2547 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002548 readOutputParameters();
2549 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2550 for (size_t i = 0; i < mTracks.size() ; i++) {
2551 int name = getTrackName_l();
2552 if (name < 0) break;
2553 mTracks[i]->mName = name;
2554 // limit track sample rate to 2 x new output sample rate
2555 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2556 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2557 }
2558 }
2559 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2560 }
2561 }
2562
2563 mNewParameters.removeAt(0);
2564
2565 mParamStatus = status;
2566 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002567 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2568 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002569 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002570 }
2571 return reconfig;
2572}
2573
2574status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2575{
2576 const size_t SIZE = 256;
2577 char buffer[SIZE];
2578 String8 result;
2579
2580 PlaybackThread::dumpInternals(fd, args);
2581
2582 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2583 result.append(buffer);
2584 write(fd, result.string(), result.size());
2585 return NO_ERROR;
2586}
2587
Mathias Agopian65ab4712010-07-14 17:59:35 -07002588uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2589{
Eric Laurent60e18242010-07-29 06:50:24 -07002590 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002591}
2592
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002593uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2594{
2595 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2596}
2597
Mathias Agopian65ab4712010-07-14 17:59:35 -07002598// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002599AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2600 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002601 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002602 // mLeftVolFloat, mRightVolFloat
2603 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002604{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002605}
2606
2607AudioFlinger::DirectOutputThread::~DirectOutputThread()
2608{
2609}
2610
Mathias Agopian65ab4712010-07-14 17:59:35 -07002611void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2612{
2613 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002614 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002615 return;
2616 }
2617
2618 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002619 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002620 size_t count = mFrameCount * mChannelCount;
2621 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2622 int16_t *dst = mMixBuffer + count-1;
2623 while(count--) {
2624 *dst-- = (int16_t)(*src--^0x80) << 8;
2625 }
2626 }
2627
2628 size_t frameCount = mFrameCount;
2629 int16_t *out = mMixBuffer;
2630 if (ramp) {
2631 if (mChannelCount == 1) {
2632 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2633 int32_t vlInc = d / (int32_t)frameCount;
2634 int32_t vl = ((int32_t)mLeftVolShort << 16);
2635 do {
2636 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2637 out++;
2638 vl += vlInc;
2639 } while (--frameCount);
2640
2641 } else {
2642 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2643 int32_t vlInc = d / (int32_t)frameCount;
2644 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2645 int32_t vrInc = d / (int32_t)frameCount;
2646 int32_t vl = ((int32_t)mLeftVolShort << 16);
2647 int32_t vr = ((int32_t)mRightVolShort << 16);
2648 do {
2649 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2650 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2651 out += 2;
2652 vl += vlInc;
2653 vr += vrInc;
2654 } while (--frameCount);
2655 }
2656 } else {
2657 if (mChannelCount == 1) {
2658 do {
2659 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2660 out++;
2661 } while (--frameCount);
2662 } else {
2663 do {
2664 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2665 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2666 out += 2;
2667 } while (--frameCount);
2668 }
2669 }
2670
2671 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002672 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002673 size_t count = mFrameCount * mChannelCount;
2674 int16_t *src = mMixBuffer;
2675 uint8_t *dst = (uint8_t *)mMixBuffer;
2676 while(count--) {
2677 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2678 }
2679 }
2680
2681 mLeftVolShort = leftVol;
2682 mRightVolShort = rightVol;
2683}
2684
2685bool AudioFlinger::DirectOutputThread::threadLoop()
2686{
Glenn Kasten29c23c32012-01-26 13:37:52 -08002687 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002688 sp<Track> trackToRemove;
2689 sp<Track> activeTrack;
2690 nsecs_t standbyTime = systemTime();
2691 int8_t *curBuf;
2692 size_t mixBufferSize = mFrameCount*mFrameSize;
2693 uint32_t activeSleepTime = activeSleepTimeUs();
2694 uint32_t idleSleepTime = idleSleepTimeUs();
2695 uint32_t sleepTime = idleSleepTime;
2696 // use shorter standby delay as on normal output to release
2697 // hardware resources as soon as possible
2698 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2699
Eric Laurentfeb0db62011-07-22 09:04:31 -07002700 acquireWakeLock();
2701
Mathias Agopian65ab4712010-07-14 17:59:35 -07002702 while (!exitPending())
2703 {
2704 bool rampVolume;
2705 uint16_t leftVol;
2706 uint16_t rightVol;
2707 Vector< sp<EffectChain> > effectChains;
2708
2709 processConfigEvents();
2710
2711 mixerStatus = MIXER_IDLE;
2712
2713 { // scope for the mLock
2714
2715 Mutex::Autolock _l(mLock);
2716
2717 if (checkForNewParameters_l()) {
2718 mixBufferSize = mFrameCount*mFrameSize;
2719 activeSleepTime = activeSleepTimeUs();
2720 idleSleepTime = idleSleepTimeUs();
2721 standbyDelay = microseconds(activeSleepTime*2);
2722 }
2723
2724 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002725 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2726 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002727 // wait until we have something to do...
2728 if (!mStandby) {
Glenn Kasten90bebef2012-01-27 15:24:38 -08002729 ALOGV("Audio hardware entering standby, mixer %p", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002730 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002731 mStandby = true;
2732 mBytesWritten = 0;
2733 }
2734
2735 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2736 // we're about to wait, flush the binder command buffer
2737 IPCThreadState::self()->flushCommands();
2738
2739 if (exitPending()) break;
2740
Eric Laurentfeb0db62011-07-22 09:04:31 -07002741 releaseWakeLock_l();
Glenn Kasten90bebef2012-01-27 15:24:38 -08002742 ALOGV("DirectOutputThread %p TID %d going to sleep", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002743 mWaitWorkCV.wait(mLock);
Glenn Kasten90bebef2012-01-27 15:24:38 -08002744 ALOGV("DirectOutputThread %p TID %d waking up in active mode", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002745 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002746
Glenn Kastenf1d45922012-01-13 15:54:24 -08002747 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002748 char value[PROPERTY_VALUE_MAX];
2749 property_get("ro.audio.silent", value, "0");
2750 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002751 ALOGD("Silence is golden");
Glenn Kasten6637baa2012-01-09 09:40:36 -08002752 setMasterMute_l(true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002753 }
2754 }
2755
2756 standbyTime = systemTime() + standbyDelay;
2757 sleepTime = idleSleepTime;
2758 continue;
2759 }
2760 }
2761
2762 effectChains = mEffectChains;
2763
2764 // find out which tracks need to be processed
2765 if (mActiveTracks.size() != 0) {
2766 sp<Track> t = mActiveTracks[0].promote();
2767 if (t == 0) continue;
2768
2769 Track* const track = t.get();
2770 audio_track_cblk_t* cblk = track->cblk();
2771
2772 // The first time a track is added we wait
2773 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002774 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002775 !track->isPaused() && !track->isTerminated())
2776 {
Steve Block3856b092011-10-20 11:56:00 +01002777 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002778
2779 if (track->mFillingUpStatus == Track::FS_FILLED) {
2780 track->mFillingUpStatus = Track::FS_ACTIVE;
2781 mLeftVolFloat = mRightVolFloat = 0;
2782 mLeftVolShort = mRightVolShort = 0;
2783 if (track->mState == TrackBase::RESUMING) {
2784 track->mState = TrackBase::ACTIVE;
2785 rampVolume = true;
2786 }
2787 } else if (cblk->server != 0) {
2788 // If the track is stopped before the first frame was mixed,
2789 // do not apply ramp
2790 rampVolume = true;
2791 }
2792 // compute volume for this track
2793 float left, right;
2794 if (track->isMuted() || mMasterMute || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002795 mStreamTypes[track->streamType()].mute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002796 left = right = 0;
2797 if (track->isPausing()) {
2798 track->setPaused();
2799 }
2800 } else {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002801 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002802 float v = mMasterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002803 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002804 float v_clamped = v * (vlr & 0xFFFF);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002805 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2806 left = v_clamped/MAX_GAIN;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002807 v_clamped = v * (vlr >> 16);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002808 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2809 right = v_clamped/MAX_GAIN;
2810 }
2811
2812 if (left != mLeftVolFloat || right != mRightVolFloat) {
2813 mLeftVolFloat = left;
2814 mRightVolFloat = right;
2815
2816 // If audio HAL implements volume control,
2817 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002818 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002819 left = 1.0f;
2820 right = 1.0f;
2821 }
2822
2823 // Convert volumes from float to 8.24
2824 uint32_t vl = (uint32_t)(left * (1 << 24));
2825 uint32_t vr = (uint32_t)(right * (1 << 24));
2826
2827 // Delegate volume control to effect in track effect chain if needed
2828 // only one effect chain can be present on DirectOutputThread, so if
2829 // there is one, the track is connected to it
2830 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002831 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002832 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002833 rampVolume = false;
2834 }
2835 }
2836
2837 // Convert volumes from 8.24 to 4.12 format
2838 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2839 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2840 leftVol = (uint16_t)v_clamped;
2841 v_clamped = (vr + (1 << 11)) >> 12;
2842 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2843 rightVol = (uint16_t)v_clamped;
2844 } else {
2845 leftVol = mLeftVolShort;
2846 rightVol = mRightVolShort;
2847 rampVolume = false;
2848 }
2849
2850 // reset retry count
2851 track->mRetryCount = kMaxTrackRetriesDirect;
2852 activeTrack = t;
2853 mixerStatus = MIXER_TRACKS_READY;
2854 } else {
Steve Block3856b092011-10-20 11:56:00 +01002855 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002856 if (track->isStopped()) {
2857 track->reset();
2858 }
2859 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2860 // We have consumed all the buffers of this track.
2861 // Remove it from the list of active tracks.
2862 trackToRemove = track;
2863 } else {
2864 // No buffers for this track. Give it a few chances to
2865 // fill a buffer, then remove it from active list.
2866 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002867 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002868 trackToRemove = track;
2869 } else {
2870 mixerStatus = MIXER_TRACKS_ENABLED;
2871 }
2872 }
2873 }
2874 }
2875
2876 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002877 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002878 mActiveTracks.remove(trackToRemove);
2879 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002880 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002881 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002882 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002883 }
2884 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002885 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002886 }
2887 }
2888
Eric Laurentde070132010-07-13 04:45:46 -07002889 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002890 }
2891
Glenn Kastenf6b16782011-12-15 09:51:17 -08002892 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002893 AudioBufferProvider::Buffer buffer;
2894 size_t frameCount = mFrameCount;
2895 curBuf = (int8_t *)mMixBuffer;
2896 // output audio to hardware
2897 while (frameCount) {
2898 buffer.frameCount = frameCount;
John Grossman4ff14ba2012-02-08 16:37:41 -08002899 activeTrack->getNextBuffer(&buffer,
2900 AudioBufferProvider::kInvalidPTS);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002901 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002902 memset(curBuf, 0, frameCount * mFrameSize);
2903 break;
2904 }
2905 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2906 frameCount -= buffer.frameCount;
2907 curBuf += buffer.frameCount * mFrameSize;
2908 activeTrack->releaseBuffer(&buffer);
2909 }
2910 sleepTime = 0;
2911 standbyTime = systemTime() + standbyDelay;
2912 } else {
2913 if (sleepTime == 0) {
2914 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2915 sleepTime = activeSleepTime;
2916 } else {
2917 sleepTime = idleSleepTime;
2918 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002919 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002920 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2921 sleepTime = 0;
2922 }
2923 }
2924
2925 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002926 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002927 }
2928 // sleepTime == 0 means we must write to audio hardware
2929 if (sleepTime == 0) {
2930 if (mixerStatus == MIXER_TRACKS_READY) {
2931 applyVolume(leftVol, rightVol, rampVolume);
2932 }
2933 for (size_t i = 0; i < effectChains.size(); i ++) {
2934 effectChains[i]->process_l();
2935 }
Eric Laurentde070132010-07-13 04:45:46 -07002936 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002937
2938 mLastWriteTime = systemTime();
2939 mInWrite = true;
2940 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002941 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002942 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2943 mNumWrites++;
2944 mInWrite = false;
2945 mStandby = false;
2946 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002947 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002948 usleep(sleepTime);
2949 }
2950
2951 // finally let go of removed track, without the lock held
2952 // since we can't guarantee the destructors won't acquire that
2953 // same lock.
2954 trackToRemove.clear();
2955 activeTrack.clear();
2956
2957 // Effect chains will be actually deleted here if they were removed from
2958 // mEffectChains list during mixing or effects processing
2959 effectChains.clear();
2960 }
2961
2962 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002963 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002964 }
2965
Eric Laurentfeb0db62011-07-22 09:04:31 -07002966 releaseWakeLock();
2967
Steve Block3856b092011-10-20 11:56:00 +01002968 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002969 return false;
2970}
2971
2972// getTrackName_l() must be called with ThreadBase::mLock held
2973int AudioFlinger::DirectOutputThread::getTrackName_l()
2974{
2975 return 0;
2976}
2977
2978// deleteTrackName_l() must be called with ThreadBase::mLock held
2979void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2980{
2981}
2982
2983// checkForNewParameters_l() must be called with ThreadBase::mLock held
2984bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2985{
2986 bool reconfig = false;
2987
2988 while (!mNewParameters.isEmpty()) {
2989 status_t status = NO_ERROR;
2990 String8 keyValuePair = mNewParameters[0];
2991 AudioParameter param = AudioParameter(keyValuePair);
2992 int value;
2993
2994 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2995 // do not accept frame count changes if tracks are open as the track buffer
2996 // size depends on frame count and correct behavior would not be garantied
2997 // if frame count is changed after track creation
2998 if (!mTracks.isEmpty()) {
2999 status = INVALID_OPERATION;
3000 } else {
3001 reconfig = true;
3002 }
3003 }
3004 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003005 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003006 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003007 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003008 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003009 mStandby = true;
3010 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07003011 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003012 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003013 }
3014 if (status == NO_ERROR && reconfig) {
3015 readOutputParameters();
3016 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3017 }
3018 }
3019
3020 mNewParameters.removeAt(0);
3021
3022 mParamStatus = status;
3023 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003024 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3025 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003026 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003027 }
3028 return reconfig;
3029}
3030
3031uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
3032{
3033 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003034 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003035 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003036 } else {
3037 time = 10000;
3038 }
3039 return time;
3040}
3041
3042uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
3043{
3044 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003045 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003046 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003047 } else {
3048 time = 10000;
3049 }
3050 return time;
3051}
3052
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003053uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
3054{
3055 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003056 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003057 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3058 } else {
3059 time = 10000;
3060 }
3061 return time;
3062}
3063
3064
Mathias Agopian65ab4712010-07-14 17:59:35 -07003065// ----------------------------------------------------------------------------
3066
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003067AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003068 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003069 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3070 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003071{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003072 addOutputTrack(mainThread);
3073}
3074
3075AudioFlinger::DuplicatingThread::~DuplicatingThread()
3076{
3077 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3078 mOutputTracks[i]->destroy();
3079 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003080}
3081
3082bool AudioFlinger::DuplicatingThread::threadLoop()
3083{
3084 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08003085 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003086 nsecs_t standbyTime = systemTime();
3087 size_t mixBufferSize = mFrameCount*mFrameSize;
3088 SortedVector< sp<OutputTrack> > outputTracks;
3089 uint32_t writeFrames = 0;
3090 uint32_t activeSleepTime = activeSleepTimeUs();
3091 uint32_t idleSleepTime = idleSleepTimeUs();
3092 uint32_t sleepTime = idleSleepTime;
3093 Vector< sp<EffectChain> > effectChains;
3094
Eric Laurentfeb0db62011-07-22 09:04:31 -07003095 acquireWakeLock();
3096
Mathias Agopian65ab4712010-07-14 17:59:35 -07003097 while (!exitPending())
3098 {
3099 processConfigEvents();
3100
3101 mixerStatus = MIXER_IDLE;
3102 { // scope for the mLock
3103
3104 Mutex::Autolock _l(mLock);
3105
3106 if (checkForNewParameters_l()) {
3107 mixBufferSize = mFrameCount*mFrameSize;
3108 updateWaitTime();
3109 activeSleepTime = activeSleepTimeUs();
3110 idleSleepTime = idleSleepTimeUs();
3111 }
3112
3113 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3114
3115 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3116 outputTracks.add(mOutputTracks[i]);
3117 }
3118
3119 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08003120 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3121 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003122 if (!mStandby) {
3123 for (size_t i = 0; i < outputTracks.size(); i++) {
3124 outputTracks[i]->stop();
3125 }
3126 mStandby = true;
3127 mBytesWritten = 0;
3128 }
3129
3130 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3131 // we're about to wait, flush the binder command buffer
3132 IPCThreadState::self()->flushCommands();
3133 outputTracks.clear();
3134
3135 if (exitPending()) break;
3136
Eric Laurentfeb0db62011-07-22 09:04:31 -07003137 releaseWakeLock_l();
Glenn Kasten90bebef2012-01-27 15:24:38 -08003138 ALOGV("DuplicatingThread %p TID %d going to sleep", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003139 mWaitWorkCV.wait(mLock);
Glenn Kasten90bebef2012-01-27 15:24:38 -08003140 ALOGV("DuplicatingThread %p TID %d waking up", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003141 acquireWakeLock_l();
3142
Eric Laurent27741442012-01-17 19:20:12 -08003143 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08003144 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003145 char value[PROPERTY_VALUE_MAX];
3146 property_get("ro.audio.silent", value, "0");
3147 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00003148 ALOGD("Silence is golden");
Glenn Kasten6637baa2012-01-09 09:40:36 -08003149 setMasterMute_l(true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003150 }
3151 }
3152
John Grossman4ff14ba2012-02-08 16:37:41 -08003153 standbyTime = systemTime() + mStandbyTimeInNsecs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003154 sleepTime = idleSleepTime;
3155 continue;
3156 }
3157 }
3158
3159 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3160
3161 // prevent any changes in effect chain list and in each effect chain
3162 // during mixing and effect process as the audio buffers could be deleted
3163 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003164 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003165 }
3166
Glenn Kastenf6b16782011-12-15 09:51:17 -08003167 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003168 // mix buffers...
3169 if (outputsReady(outputTracks)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08003170 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003171 } else {
3172 memset(mMixBuffer, 0, mixBufferSize);
3173 }
3174 sleepTime = 0;
3175 writeFrames = mFrameCount;
3176 } else {
3177 if (sleepTime == 0) {
3178 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3179 sleepTime = activeSleepTime;
3180 } else {
3181 sleepTime = idleSleepTime;
3182 }
3183 } else if (mBytesWritten != 0) {
3184 // flush remaining overflow buffers in output tracks
3185 for (size_t i = 0; i < outputTracks.size(); i++) {
3186 if (outputTracks[i]->isActive()) {
3187 sleepTime = 0;
3188 writeFrames = 0;
3189 memset(mMixBuffer, 0, mixBufferSize);
3190 break;
3191 }
3192 }
3193 }
3194 }
3195
3196 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003197 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003198 }
3199 // sleepTime == 0 means we must write to audio hardware
3200 if (sleepTime == 0) {
3201 for (size_t i = 0; i < effectChains.size(); i ++) {
3202 effectChains[i]->process_l();
3203 }
3204 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003205 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003206
John Grossman4ff14ba2012-02-08 16:37:41 -08003207 standbyTime = systemTime() + mStandbyTimeInNsecs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003208 for (size_t i = 0; i < outputTracks.size(); i++) {
3209 outputTracks[i]->write(mMixBuffer, writeFrames);
3210 }
3211 mStandby = false;
3212 mBytesWritten += mixBufferSize;
3213 } else {
3214 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003215 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003216 usleep(sleepTime);
3217 }
3218
3219 // finally let go of all our tracks, without the lock held
3220 // since we can't guarantee the destructors won't acquire that
3221 // same lock.
3222 tracksToRemove.clear();
3223 outputTracks.clear();
3224
3225 // Effect chains will be actually deleted here if they were removed from
3226 // mEffectChains list during mixing or effects processing
3227 effectChains.clear();
3228 }
3229
Eric Laurentfeb0db62011-07-22 09:04:31 -07003230 releaseWakeLock();
3231
Mathias Agopian65ab4712010-07-14 17:59:35 -07003232 return false;
3233}
3234
3235void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3236{
Glenn Kasten99e53b82012-01-19 08:59:58 -08003237 // FIXME explain this formula
Mathias Agopian65ab4712010-07-14 17:59:35 -07003238 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3239 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3240 this,
3241 mSampleRate,
3242 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003243 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003244 frameCount);
3245 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003246 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003247 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003248 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003249 updateWaitTime();
3250 }
3251}
3252
3253void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3254{
3255 Mutex::Autolock _l(mLock);
3256 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3257 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3258 mOutputTracks[i]->destroy();
3259 mOutputTracks.removeAt(i);
3260 updateWaitTime();
3261 return;
3262 }
3263 }
Steve Block3856b092011-10-20 11:56:00 +01003264 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003265}
3266
3267void AudioFlinger::DuplicatingThread::updateWaitTime()
3268{
3269 mWaitTimeMs = UINT_MAX;
3270 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3271 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003272 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003273 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3274 if (waitTimeMs < mWaitTimeMs) {
3275 mWaitTimeMs = waitTimeMs;
3276 }
3277 }
3278 }
3279}
3280
3281
3282bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3283{
3284 for (size_t i = 0; i < outputTracks.size(); i++) {
3285 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3286 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003287 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003288 return false;
3289 }
3290 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3291 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003292 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003293 return false;
3294 }
3295 }
3296 return true;
3297}
3298
3299uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3300{
3301 return (mWaitTimeMs * 1000) / 2;
3302}
3303
3304// ----------------------------------------------------------------------------
3305
3306// TrackBase constructor must be called with AudioFlinger::mLock held
3307AudioFlinger::ThreadBase::TrackBase::TrackBase(
3308 const wp<ThreadBase>& thread,
3309 const sp<Client>& client,
3310 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003311 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003312 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003313 int frameCount,
3314 uint32_t flags,
3315 const sp<IMemory>& sharedBuffer,
3316 int sessionId)
3317 : RefBase(),
3318 mThread(thread),
3319 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003320 mCblk(NULL),
3321 // mBuffer
3322 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003323 mFrameCount(0),
3324 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003325 mFormat(format),
3326 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3327 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003328 // mChannelCount
3329 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003330{
Steve Block3856b092011-10-20 11:56:00 +01003331 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003332
Steve Blockb8a80522011-12-20 16:23:08 +00003333 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003334 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003335 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003336 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3337 if (sharedBuffer == 0) {
3338 size += bufferSize;
3339 }
3340
3341 if (client != NULL) {
3342 mCblkMemory = client->heap()->allocate(size);
3343 if (mCblkMemory != 0) {
3344 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003345 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003346 new(mCblk) audio_track_cblk_t();
3347 // clear all buffers
3348 mCblk->frameCount = frameCount;
3349 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003350 mChannelCount = channelCount;
3351 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003352 if (sharedBuffer == 0) {
3353 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3354 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3355 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003356 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003357 mCblk->flags = CBLK_UNDERRUN_ON;
3358 } else {
3359 mBuffer = sharedBuffer->pointer();
3360 }
3361 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3362 }
3363 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003364 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003365 client->heap()->dump("AudioTrack");
3366 return;
3367 }
3368 } else {
3369 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003370 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003371 new(mCblk) audio_track_cblk_t();
3372 // clear all buffers
3373 mCblk->frameCount = frameCount;
3374 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003375 mChannelCount = channelCount;
3376 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003377 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3378 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3379 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003380 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003381 mCblk->flags = CBLK_UNDERRUN_ON;
3382 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003383 }
3384}
3385
3386AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3387{
Glenn Kastena0d68332012-01-27 16:47:15 -08003388 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003389 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003390 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003391 } else {
3392 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003393 }
3394 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003395 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003396 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003397 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003398 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003399 // If the client's reference count drops to zero, the associated destructor
3400 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3401 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003402 mClient.clear();
3403 }
3404}
3405
3406void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3407{
Glenn Kastene0feee32011-12-13 11:53:26 -08003408 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003409 mFrameCount = buffer->frameCount;
3410 step();
3411 buffer->frameCount = 0;
3412}
3413
3414bool AudioFlinger::ThreadBase::TrackBase::step() {
3415 bool result;
3416 audio_track_cblk_t* cblk = this->cblk();
3417
3418 result = cblk->stepServer(mFrameCount);
3419 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003420 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003421 mFlags |= STEPSERVER_FAILED;
3422 }
3423 return result;
3424}
3425
3426void AudioFlinger::ThreadBase::TrackBase::reset() {
3427 audio_track_cblk_t* cblk = this->cblk();
3428
3429 cblk->user = 0;
3430 cblk->server = 0;
3431 cblk->userBase = 0;
3432 cblk->serverBase = 0;
3433 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003434 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003435}
3436
Mathias Agopian65ab4712010-07-14 17:59:35 -07003437int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3438 return (int)mCblk->sampleRate;
3439}
3440
Mathias Agopian65ab4712010-07-14 17:59:35 -07003441void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3442 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003443 size_t frameSize = cblk->frameSize;
3444 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3445 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003446
3447 // Check validity of returned pointer in case the track control block would have been corrupted.
3448 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003449 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003450 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 -07003451 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003452 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003453 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003454 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003455 }
3456
3457 return bufferStart;
3458}
3459
3460// ----------------------------------------------------------------------------
3461
3462// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3463AudioFlinger::PlaybackThread::Track::Track(
3464 const wp<ThreadBase>& thread,
3465 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003466 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003467 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003468 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003469 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003470 int frameCount,
3471 const sp<IMemory>& sharedBuffer,
3472 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003473 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003474 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3475 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003476{
3477 if (mCblk != NULL) {
3478 sp<ThreadBase> baseThread = thread.promote();
3479 if (baseThread != 0) {
3480 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3481 mName = playbackThread->getTrackName_l();
3482 mMainBuffer = playbackThread->mixBuffer();
3483 }
Glenn Kasten23d82a92012-02-03 11:10:00 -08003484 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003485 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003486 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003487 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003488 mStreamType = streamType;
3489 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3490 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003491 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003492 }
3493}
3494
3495AudioFlinger::PlaybackThread::Track::~Track()
3496{
Steve Block3856b092011-10-20 11:56:00 +01003497 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003498 sp<ThreadBase> thread = mThread.promote();
3499 if (thread != 0) {
3500 Mutex::Autolock _l(thread->mLock);
3501 mState = TERMINATED;
3502 }
3503}
3504
3505void AudioFlinger::PlaybackThread::Track::destroy()
3506{
3507 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3508 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08003509 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003510 // we must acquire a strong reference on this Track before locking mLock
3511 // here so that the destructor is called only when exiting this function.
3512 // On the other hand, as long as Track::destroy() is only called by
3513 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3514 // this Track with its member mTrack.
3515 sp<Track> keep(this);
3516 { // scope for mLock
3517 sp<ThreadBase> thread = mThread.promote();
3518 if (thread != 0) {
3519 if (!isOutputTrack()) {
3520 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08003521 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003522
3523 // to track the speaker usage
3524 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003525 }
3526 AudioSystem::releaseOutput(thread->id());
3527 }
3528 Mutex::Autolock _l(thread->mLock);
3529 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3530 playbackThread->destroyTrack_l(this);
3531 }
3532 }
3533}
3534
3535void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3536{
Glenn Kasten83d86532012-01-17 14:39:34 -08003537 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003538 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 -07003539 mName - AudioMixer::TRACK0,
Glenn Kasten44deb052012-02-05 18:09:08 -08003540 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003541 mStreamType,
3542 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003543 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003544 mSessionId,
3545 mFrameCount,
3546 mState,
3547 mMute,
3548 mFillingUpStatus,
3549 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003550 vlr & 0xFFFF,
3551 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003552 mCblk->server,
3553 mCblk->user,
3554 (int)mMainBuffer,
3555 (int)mAuxBuffer);
3556}
3557
John Grossman4ff14ba2012-02-08 16:37:41 -08003558status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
3559 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003560{
3561 audio_track_cblk_t* cblk = this->cblk();
3562 uint32_t framesReady;
3563 uint32_t framesReq = buffer->frameCount;
3564
3565 // Check if last stepServer failed, try to step now
3566 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3567 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003568 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003569 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3570 }
3571
3572 framesReady = cblk->framesReady();
3573
Glenn Kastenf6b16782011-12-15 09:51:17 -08003574 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003575 uint32_t s = cblk->server;
3576 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3577
3578 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3579 if (framesReq > framesReady) {
3580 framesReq = framesReady;
3581 }
3582 if (s + framesReq > bufferEnd) {
3583 framesReq = bufferEnd - s;
3584 }
3585
3586 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003587 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003588
3589 buffer->frameCount = framesReq;
3590 return NO_ERROR;
3591 }
3592
3593getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003594 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003595 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003596 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003597 return NOT_ENOUGH_DATA;
3598}
3599
John Grossman4ff14ba2012-02-08 16:37:41 -08003600uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const{
3601 return mCblk->framesReady();
3602}
3603
Mathias Agopian65ab4712010-07-14 17:59:35 -07003604bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003605 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003606
John Grossman4ff14ba2012-02-08 16:37:41 -08003607 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003608 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3609 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003610 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003611 return true;
3612 }
3613 return false;
3614}
3615
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003616status_t AudioFlinger::PlaybackThread::Track::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003617{
3618 status_t status = NO_ERROR;
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003619 ALOGV("start(%d), calling pid %d session %d tid %d",
3620 mName, IPCThreadState::self()->getCallingPid(), mSessionId, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003621 sp<ThreadBase> thread = mThread.promote();
3622 if (thread != 0) {
3623 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003624 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003625 // here the track could be either new, or restarted
3626 // in both cases "unstop" the track
3627 if (mState == PAUSED) {
3628 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003629 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003630 } else {
3631 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003632 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003633 }
3634
3635 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3636 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003637 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003638 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003639
3640 // to track the speaker usage
3641 if (status == NO_ERROR) {
3642 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3643 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003644 }
3645 if (status == NO_ERROR) {
3646 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3647 playbackThread->addTrack_l(this);
3648 } else {
3649 mState = state;
3650 }
3651 } else {
3652 status = BAD_VALUE;
3653 }
3654 return status;
3655}
3656
3657void AudioFlinger::PlaybackThread::Track::stop()
3658{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003659 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003660 sp<ThreadBase> thread = mThread.promote();
3661 if (thread != 0) {
3662 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003663 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003664 if (mState > STOPPED) {
3665 mState = STOPPED;
3666 // If the track is not active (PAUSED and buffers full), flush buffers
3667 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3668 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3669 reset();
3670 }
Steve Block3856b092011-10-20 11:56:00 +01003671 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003672 }
3673 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3674 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003675 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003676 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003677
3678 // to track the speaker usage
3679 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003680 }
3681 }
3682}
3683
3684void AudioFlinger::PlaybackThread::Track::pause()
3685{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003686 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003687 sp<ThreadBase> thread = mThread.promote();
3688 if (thread != 0) {
3689 Mutex::Autolock _l(thread->mLock);
3690 if (mState == ACTIVE || mState == RESUMING) {
3691 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003692 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003693 if (!isOutputTrack()) {
3694 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003695 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003696 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003697
3698 // to track the speaker usage
3699 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003700 }
3701 }
3702 }
3703}
3704
3705void AudioFlinger::PlaybackThread::Track::flush()
3706{
Steve Block3856b092011-10-20 11:56:00 +01003707 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003708 sp<ThreadBase> thread = mThread.promote();
3709 if (thread != 0) {
3710 Mutex::Autolock _l(thread->mLock);
3711 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3712 return;
3713 }
3714 // No point remaining in PAUSED state after a flush => go to
3715 // STOPPED state
3716 mState = STOPPED;
3717
Eric Laurent38ccae22011-03-28 18:37:07 -07003718 // do not reset the track if it is still in the process of being stopped or paused.
3719 // this will be done by prepareTracks_l() when the track is stopped.
3720 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3721 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3722 reset();
3723 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003724 }
3725}
3726
3727void AudioFlinger::PlaybackThread::Track::reset()
3728{
3729 // Do not reset twice to avoid discarding data written just after a flush and before
3730 // the audioflinger thread detects the track is stopped.
3731 if (!mResetDone) {
3732 TrackBase::reset();
3733 // Force underrun condition to avoid false underrun callback until first data is
3734 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003735 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3736 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003737 mFillingUpStatus = FS_FILLING;
3738 mResetDone = true;
3739 }
3740}
3741
3742void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3743{
3744 mMute = muted;
3745}
3746
Mathias Agopian65ab4712010-07-14 17:59:35 -07003747status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3748{
3749 status_t status = DEAD_OBJECT;
3750 sp<ThreadBase> thread = mThread.promote();
3751 if (thread != 0) {
3752 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3753 status = playbackThread->attachAuxEffect(this, EffectId);
3754 }
3755 return status;
3756}
3757
3758void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3759{
3760 mAuxEffectId = EffectId;
3761 mAuxBuffer = buffer;
3762}
3763
John Grossman4ff14ba2012-02-08 16:37:41 -08003764// timed audio tracks
3765
3766sp<AudioFlinger::PlaybackThread::TimedTrack>
3767AudioFlinger::PlaybackThread::TimedTrack::create(
3768 const wp<ThreadBase>& thread,
3769 const sp<Client>& client,
3770 audio_stream_type_t streamType,
3771 uint32_t sampleRate,
3772 audio_format_t format,
3773 uint32_t channelMask,
3774 int frameCount,
3775 const sp<IMemory>& sharedBuffer,
3776 int sessionId) {
3777 if (!client->reserveTimedTrack())
3778 return NULL;
3779
3780 sp<TimedTrack> track = new TimedTrack(
3781 thread, client, streamType, sampleRate, format, channelMask, frameCount,
3782 sharedBuffer, sessionId);
3783
3784 if (track == NULL) {
3785 client->releaseTimedTrack();
3786 return NULL;
3787 }
3788
3789 return track;
3790}
3791
3792AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
3793 const wp<ThreadBase>& thread,
3794 const sp<Client>& client,
3795 audio_stream_type_t streamType,
3796 uint32_t sampleRate,
3797 audio_format_t format,
3798 uint32_t channelMask,
3799 int frameCount,
3800 const sp<IMemory>& sharedBuffer,
3801 int sessionId)
3802 : Track(thread, client, streamType, sampleRate, format, channelMask,
3803 frameCount, sharedBuffer, sessionId),
3804 mTimedSilenceBuffer(NULL),
3805 mTimedSilenceBufferSize(0),
3806 mTimedAudioOutputOnTime(false),
3807 mMediaTimeTransformValid(false)
3808{
3809 LocalClock lc;
3810 mLocalTimeFreq = lc.getLocalFreq();
3811
3812 mLocalTimeToSampleTransform.a_zero = 0;
3813 mLocalTimeToSampleTransform.b_zero = 0;
3814 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3815 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3816 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3817 &mLocalTimeToSampleTransform.a_to_b_denom);
3818}
3819
3820AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3821 mClient->releaseTimedTrack();
3822 delete [] mTimedSilenceBuffer;
3823}
3824
3825status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3826 size_t size, sp<IMemory>* buffer) {
3827
3828 Mutex::Autolock _l(mTimedBufferQueueLock);
3829
3830 trimTimedBufferQueue_l();
3831
3832 // lazily initialize the shared memory heap for timed buffers
3833 if (mTimedMemoryDealer == NULL) {
3834 const int kTimedBufferHeapSize = 512 << 10;
3835
3836 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3837 "AudioFlingerTimed");
3838 if (mTimedMemoryDealer == NULL)
3839 return NO_MEMORY;
3840 }
3841
3842 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3843 if (newBuffer == NULL) {
3844 newBuffer = mTimedMemoryDealer->allocate(size);
3845 if (newBuffer == NULL)
3846 return NO_MEMORY;
3847 }
3848
3849 *buffer = newBuffer;
3850 return NO_ERROR;
3851}
3852
3853// caller must hold mTimedBufferQueueLock
3854void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
3855 int64_t mediaTimeNow;
3856 {
3857 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3858 if (!mMediaTimeTransformValid)
3859 return;
3860
3861 int64_t targetTimeNow;
3862 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
3863 ? mCCHelper.getCommonTime(&targetTimeNow)
3864 : mCCHelper.getLocalTime(&targetTimeNow);
3865
3866 if (OK != res)
3867 return;
3868
3869 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
3870 &mediaTimeNow)) {
3871 return;
3872 }
3873 }
3874
3875 size_t trimIndex;
3876 for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
3877 if (mTimedBufferQueue[trimIndex].pts() > mediaTimeNow)
3878 break;
3879 }
3880
3881 if (trimIndex) {
3882 mTimedBufferQueue.removeItemsAt(0, trimIndex);
3883 }
3884}
3885
3886status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
3887 const sp<IMemory>& buffer, int64_t pts) {
3888
3889 {
3890 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3891 if (!mMediaTimeTransformValid)
3892 return INVALID_OPERATION;
3893 }
3894
3895 Mutex::Autolock _l(mTimedBufferQueueLock);
3896
3897 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
3898
3899 return NO_ERROR;
3900}
3901
3902status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
3903 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
3904
3905 ALOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
3906 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
3907 target);
3908
3909 if (!(target == TimedAudioTrack::LOCAL_TIME ||
3910 target == TimedAudioTrack::COMMON_TIME)) {
3911 return BAD_VALUE;
3912 }
3913
3914 Mutex::Autolock lock(mMediaTimeTransformLock);
3915 mMediaTimeTransform = xform;
3916 mMediaTimeTransformTarget = target;
3917 mMediaTimeTransformValid = true;
3918
3919 return NO_ERROR;
3920}
3921
3922#define min(a, b) ((a) < (b) ? (a) : (b))
3923
3924// implementation of getNextBuffer for tracks whose buffers have timestamps
3925status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
3926 AudioBufferProvider::Buffer* buffer, int64_t pts)
3927{
3928 if (pts == AudioBufferProvider::kInvalidPTS) {
3929 buffer->raw = 0;
3930 buffer->frameCount = 0;
3931 return INVALID_OPERATION;
3932 }
3933
3934 // get ahold of the output stream that these samples will be written to
3935 sp<ThreadBase> thread = mThread.promote();
3936 if (thread == NULL) {
3937 buffer->raw = 0;
3938 buffer->frameCount = 0;
3939 return INVALID_OPERATION;
3940 }
3941 PlaybackThread* playbackThread = static_cast<PlaybackThread*>(thread.get());
3942
3943 Mutex::Autolock _l(mTimedBufferQueueLock);
3944
3945 while (true) {
3946
3947 // if we have no timed buffers, then fail
3948 if (mTimedBufferQueue.isEmpty()) {
3949 buffer->raw = 0;
3950 buffer->frameCount = 0;
3951 return NOT_ENOUGH_DATA;
3952 }
3953
3954 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
3955
3956 // calculate the PTS of the head of the timed buffer queue expressed in
3957 // local time
3958 int64_t headLocalPTS;
3959 {
3960 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3961
3962 assert(mMediaTimeTransformValid);
3963
3964 if (mMediaTimeTransform.a_to_b_denom == 0) {
3965 // the transform represents a pause, so yield silence
3966 timedYieldSilence(buffer->frameCount, buffer);
3967 return NO_ERROR;
3968 }
3969
3970 int64_t transformedPTS;
3971 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
3972 &transformedPTS)) {
3973 // the transform failed. this shouldn't happen, but if it does
3974 // then just drop this buffer
3975 ALOGW("timedGetNextBuffer transform failed");
3976 buffer->raw = 0;
3977 buffer->frameCount = 0;
3978 mTimedBufferQueue.removeAt(0);
3979 return NO_ERROR;
3980 }
3981
3982 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
3983 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
3984 &headLocalPTS)) {
3985 buffer->raw = 0;
3986 buffer->frameCount = 0;
3987 return INVALID_OPERATION;
3988 }
3989 } else {
3990 headLocalPTS = transformedPTS;
3991 }
3992 }
3993
3994 // adjust the head buffer's PTS to reflect the portion of the head buffer
3995 // that has already been consumed
3996 int64_t effectivePTS = headLocalPTS +
3997 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
3998
3999 // Calculate the delta in samples between the head of the input buffer
4000 // queue and the start of the next output buffer that will be written.
4001 // If the transformation fails because of over or underflow, it means
4002 // that the sample's position in the output stream is so far out of
4003 // whack that it should just be dropped.
4004 int64_t sampleDelta;
4005 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4006 ALOGV("*** head buffer is too far from PTS: dropped buffer");
4007 mTimedBufferQueue.removeAt(0);
4008 continue;
4009 }
4010 if (!mLocalTimeToSampleTransform.doForwardTransform(
4011 (effectivePTS - pts) << 32, &sampleDelta)) {
4012 ALOGV("*** too late during sample rate transform: dropped buffer");
4013 mTimedBufferQueue.removeAt(0);
4014 continue;
4015 }
4016
4017 ALOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
4018 __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
4019 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
4020 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
4021
4022 // if the delta between the ideal placement for the next input sample and
4023 // the current output position is within this threshold, then we will
4024 // concatenate the next input samples to the previous output
4025 const int64_t kSampleContinuityThreshold =
4026 (static_cast<int64_t>(sampleRate()) << 32) / 10;
4027
4028 // if this is the first buffer of audio that we're emitting from this track
4029 // then it should be almost exactly on time.
4030 const int64_t kSampleStartupThreshold = 1LL << 32;
4031
4032 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
4033 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
4034 // the next input is close enough to being on time, so concatenate it
4035 // with the last output
4036 timedYieldSamples(buffer);
4037
4038 ALOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4039 return NO_ERROR;
4040 } else if (sampleDelta > 0) {
4041 // the gap between the current output position and the proper start of
4042 // the next input sample is too big, so fill it with silence
4043 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4044
4045 timedYieldSilence(framesUntilNextInput, buffer);
4046 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4047 return NO_ERROR;
4048 } else {
4049 // the next input sample is late
4050 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4051 size_t onTimeSamplePosition =
4052 head.position() + lateFrames * mCblk->frameSize;
4053
4054 if (onTimeSamplePosition > head.buffer()->size()) {
4055 // all the remaining samples in the head are too late, so
4056 // drop it and move on
4057 ALOGV("*** too late: dropped buffer");
4058 mTimedBufferQueue.removeAt(0);
4059 continue;
4060 } else {
4061 // skip over the late samples
4062 head.setPosition(onTimeSamplePosition);
4063
4064 // yield the available samples
4065 timedYieldSamples(buffer);
4066
4067 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4068 return NO_ERROR;
4069 }
4070 }
4071 }
4072}
4073
4074// Yield samples from the timed buffer queue head up to the given output
4075// buffer's capacity.
4076//
4077// Caller must hold mTimedBufferQueueLock
4078void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples(
4079 AudioBufferProvider::Buffer* buffer) {
4080
4081 const TimedBuffer& head = mTimedBufferQueue[0];
4082
4083 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4084 head.position());
4085
4086 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4087 mCblk->frameSize);
4088 size_t framesRequested = buffer->frameCount;
4089 buffer->frameCount = min(framesLeftInHead, framesRequested);
4090
4091 mTimedAudioOutputOnTime = true;
4092}
4093
4094// Yield samples of silence up to the given output buffer's capacity
4095//
4096// Caller must hold mTimedBufferQueueLock
4097void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence(
4098 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4099
4100 // lazily allocate a buffer filled with silence
4101 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4102 delete [] mTimedSilenceBuffer;
4103 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4104 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4105 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4106 }
4107
4108 buffer->raw = mTimedSilenceBuffer;
4109 size_t framesRequested = buffer->frameCount;
4110 buffer->frameCount = min(numFrames, framesRequested);
4111
4112 mTimedAudioOutputOnTime = false;
4113}
4114
4115void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4116 AudioBufferProvider::Buffer* buffer) {
4117
4118 Mutex::Autolock _l(mTimedBufferQueueLock);
4119
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004120 // If the buffer which was just released is part of the buffer at the head
4121 // of the queue, be sure to update the amt of the buffer which has been
4122 // consumed. If the buffer being returned is not part of the head of the
4123 // queue, its either because the buffer is part of the silence buffer, or
4124 // because the head of the timed queue was trimmed after the mixer called
4125 // getNextBuffer but before the mixer called releaseBuffer.
4126 if ((buffer->raw != mTimedSilenceBuffer) && mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004127 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004128
4129 void* start = head.buffer()->pointer();
4130 void* end = head.buffer()->pointer() + head.buffer()->size();
4131
4132 if ((buffer->raw >= start) && (buffer->raw <= end)) {
4133 head.setPosition(head.position() +
4134 (buffer->frameCount * mCblk->frameSize));
4135 if (static_cast<size_t>(head.position()) >= head.buffer()->size()) {
4136 mTimedBufferQueue.removeAt(0);
4137 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004138 }
4139 }
4140
4141 buffer->raw = 0;
4142 buffer->frameCount = 0;
4143}
4144
4145uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4146 Mutex::Autolock _l(mTimedBufferQueueLock);
4147
4148 uint32_t frames = 0;
4149 for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4150 const TimedBuffer& tb = mTimedBufferQueue[i];
4151 frames += (tb.buffer()->size() - tb.position()) / mCblk->frameSize;
4152 }
4153
4154 return frames;
4155}
4156
4157AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4158 : mPTS(0), mPosition(0) {}
4159
4160AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4161 const sp<IMemory>& buffer, int64_t pts)
4162 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4163
Mathias Agopian65ab4712010-07-14 17:59:35 -07004164// ----------------------------------------------------------------------------
4165
4166// RecordTrack constructor must be called with AudioFlinger::mLock held
4167AudioFlinger::RecordThread::RecordTrack::RecordTrack(
4168 const wp<ThreadBase>& thread,
4169 const sp<Client>& client,
4170 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004171 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004172 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004173 int frameCount,
4174 uint32_t flags,
4175 int sessionId)
4176 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004177 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004178 mOverflow(false)
4179{
4180 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01004181 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07004182 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004183 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07004184 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004185 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004186 } else {
4187 mCblk->frameSize = sizeof(int8_t);
4188 }
4189 }
4190}
4191
4192AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4193{
4194 sp<ThreadBase> thread = mThread.promote();
4195 if (thread != 0) {
4196 AudioSystem::releaseInput(thread->id());
4197 }
4198}
4199
John Grossman4ff14ba2012-02-08 16:37:41 -08004200status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004201{
4202 audio_track_cblk_t* cblk = this->cblk();
4203 uint32_t framesAvail;
4204 uint32_t framesReq = buffer->frameCount;
4205
4206 // Check if last stepServer failed, try to step now
4207 if (mFlags & TrackBase::STEPSERVER_FAILED) {
4208 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004209 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004210 mFlags &= ~TrackBase::STEPSERVER_FAILED;
4211 }
4212
4213 framesAvail = cblk->framesAvailable_l();
4214
Glenn Kastenf6b16782011-12-15 09:51:17 -08004215 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004216 uint32_t s = cblk->server;
4217 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4218
4219 if (framesReq > framesAvail) {
4220 framesReq = framesAvail;
4221 }
4222 if (s + framesReq > bufferEnd) {
4223 framesReq = bufferEnd - s;
4224 }
4225
4226 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004227 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004228
4229 buffer->frameCount = framesReq;
4230 return NO_ERROR;
4231 }
4232
4233getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004234 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004235 buffer->frameCount = 0;
4236 return NOT_ENOUGH_DATA;
4237}
4238
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004239status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004240{
4241 sp<ThreadBase> thread = mThread.promote();
4242 if (thread != 0) {
4243 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004244 return recordThread->start(this, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004245 } else {
4246 return BAD_VALUE;
4247 }
4248}
4249
4250void AudioFlinger::RecordThread::RecordTrack::stop()
4251{
4252 sp<ThreadBase> thread = mThread.promote();
4253 if (thread != 0) {
4254 RecordThread *recordThread = (RecordThread *)thread.get();
4255 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004256 TrackBase::reset();
4257 // Force overerrun condition to avoid false overrun callback until first data is
4258 // read from buffer
4259 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004260 }
4261}
4262
4263void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4264{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004265 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004266 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004267 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004268 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004269 mSessionId,
4270 mFrameCount,
4271 mState,
4272 mCblk->sampleRate,
4273 mCblk->server,
4274 mCblk->user);
4275}
4276
4277
4278// ----------------------------------------------------------------------------
4279
4280AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
4281 const wp<ThreadBase>& thread,
4282 DuplicatingThread *sourceThread,
4283 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004284 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004285 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004286 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004287 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004288 mActive(false), mSourceThread(sourceThread)
4289{
4290
4291 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
4292 if (mCblk != NULL) {
4293 mCblk->flags |= CBLK_DIRECTION_OUT;
4294 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004295 mOutBuffer.frameCount = 0;
4296 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01004297 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004298 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4299 mCblk, mBuffer, mCblk->buffers,
4300 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004301 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004302 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004303 }
4304}
4305
4306AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4307{
4308 clearBufferQueue();
4309}
4310
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004311status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004312{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004313 status_t status = Track::start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004314 if (status != NO_ERROR) {
4315 return status;
4316 }
4317
4318 mActive = true;
4319 mRetryCount = 127;
4320 return status;
4321}
4322
4323void AudioFlinger::PlaybackThread::OutputTrack::stop()
4324{
4325 Track::stop();
4326 clearBufferQueue();
4327 mOutBuffer.frameCount = 0;
4328 mActive = false;
4329}
4330
4331bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4332{
4333 Buffer *pInBuffer;
4334 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004335 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004336 bool outputBufferFull = false;
4337 inBuffer.frameCount = frames;
4338 inBuffer.i16 = data;
4339
4340 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4341
4342 if (!mActive && frames != 0) {
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004343 start(0);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004344 sp<ThreadBase> thread = mThread.promote();
4345 if (thread != 0) {
4346 MixerThread *mixerThread = (MixerThread *)thread.get();
4347 if (mCblk->frameCount > frames){
4348 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4349 uint32_t startFrames = (mCblk->frameCount - frames);
4350 pInBuffer = new Buffer;
4351 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4352 pInBuffer->frameCount = startFrames;
4353 pInBuffer->i16 = pInBuffer->mBuffer;
4354 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4355 mBufferQueue.add(pInBuffer);
4356 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004357 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004358 }
4359 }
4360 }
4361 }
4362
4363 while (waitTimeLeftMs) {
4364 // First write pending buffers, then new data
4365 if (mBufferQueue.size()) {
4366 pInBuffer = mBufferQueue.itemAt(0);
4367 } else {
4368 pInBuffer = &inBuffer;
4369 }
4370
4371 if (pInBuffer->frameCount == 0) {
4372 break;
4373 }
4374
4375 if (mOutBuffer.frameCount == 0) {
4376 mOutBuffer.frameCount = pInBuffer->frameCount;
4377 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08004378 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01004379 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004380 outputBufferFull = true;
4381 break;
4382 }
4383 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4384 if (waitTimeLeftMs >= waitTimeMs) {
4385 waitTimeLeftMs -= waitTimeMs;
4386 } else {
4387 waitTimeLeftMs = 0;
4388 }
4389 }
4390
4391 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4392 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4393 mCblk->stepUser(outFrames);
4394 pInBuffer->frameCount -= outFrames;
4395 pInBuffer->i16 += outFrames * channelCount;
4396 mOutBuffer.frameCount -= outFrames;
4397 mOutBuffer.i16 += outFrames * channelCount;
4398
4399 if (pInBuffer->frameCount == 0) {
4400 if (mBufferQueue.size()) {
4401 mBufferQueue.removeAt(0);
4402 delete [] pInBuffer->mBuffer;
4403 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01004404 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004405 } else {
4406 break;
4407 }
4408 }
4409 }
4410
4411 // If we could not write all frames, allocate a buffer and queue it for next time.
4412 if (inBuffer.frameCount) {
4413 sp<ThreadBase> thread = mThread.promote();
4414 if (thread != 0 && !thread->standby()) {
4415 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4416 pInBuffer = new Buffer;
4417 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4418 pInBuffer->frameCount = inBuffer.frameCount;
4419 pInBuffer->i16 = pInBuffer->mBuffer;
4420 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4421 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01004422 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004423 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004424 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004425 }
4426 }
4427 }
4428
4429 // Calling write() with a 0 length buffer, means that no more data will be written:
4430 // If no more buffers are pending, fill output track buffer to make sure it is started
4431 // by output mixer.
4432 if (frames == 0 && mBufferQueue.size() == 0) {
4433 if (mCblk->user < mCblk->frameCount) {
4434 frames = mCblk->frameCount - mCblk->user;
4435 pInBuffer = new Buffer;
4436 pInBuffer->mBuffer = new int16_t[frames * channelCount];
4437 pInBuffer->frameCount = frames;
4438 pInBuffer->i16 = pInBuffer->mBuffer;
4439 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4440 mBufferQueue.add(pInBuffer);
4441 } else if (mActive) {
4442 stop();
4443 }
4444 }
4445
4446 return outputBufferFull;
4447}
4448
4449status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4450{
4451 int active;
4452 status_t result;
4453 audio_track_cblk_t* cblk = mCblk;
4454 uint32_t framesReq = buffer->frameCount;
4455
Steve Block3856b092011-10-20 11:56:00 +01004456// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004457 buffer->frameCount = 0;
4458
4459 uint32_t framesAvail = cblk->framesAvailable();
4460
4461
4462 if (framesAvail == 0) {
4463 Mutex::Autolock _l(cblk->lock);
4464 goto start_loop_here;
4465 while (framesAvail == 0) {
4466 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004467 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004468 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004469 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004470 }
4471 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4472 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004473 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004474 }
4475 // read the server count again
4476 start_loop_here:
4477 framesAvail = cblk->framesAvailable_l();
4478 }
4479 }
4480
4481// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004482// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004483// }
4484
4485 if (framesReq > framesAvail) {
4486 framesReq = framesAvail;
4487 }
4488
4489 uint32_t u = cblk->user;
4490 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4491
4492 if (u + framesReq > bufferEnd) {
4493 framesReq = bufferEnd - u;
4494 }
4495
4496 buffer->frameCount = framesReq;
4497 buffer->raw = (void *)cblk->buffer(u);
4498 return NO_ERROR;
4499}
4500
4501
4502void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4503{
4504 size_t size = mBufferQueue.size();
4505 Buffer *pBuffer;
4506
4507 for (size_t i = 0; i < size; i++) {
4508 pBuffer = mBufferQueue.itemAt(i);
4509 delete [] pBuffer->mBuffer;
4510 delete pBuffer;
4511 }
4512 mBufferQueue.clear();
4513}
4514
4515// ----------------------------------------------------------------------------
4516
4517AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4518 : RefBase(),
4519 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08004520 // 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 -07004521 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08004522 mPid(pid),
4523 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004524{
4525 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4526}
4527
4528// Client destructor must be called with AudioFlinger::mLock held
4529AudioFlinger::Client::~Client()
4530{
4531 mAudioFlinger->removeClient_l(mPid);
4532}
4533
Glenn Kasten435dbe62012-01-30 10:15:48 -08004534sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004535{
4536 return mMemoryDealer;
4537}
4538
John Grossman4ff14ba2012-02-08 16:37:41 -08004539// Reserve one of the limited slots for a timed audio track associated
4540// with this client
4541bool AudioFlinger::Client::reserveTimedTrack()
4542{
4543 const int kMaxTimedTracksPerClient = 4;
4544
4545 Mutex::Autolock _l(mTimedTrackLock);
4546
4547 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4548 ALOGW("can not create timed track - pid %d has exceeded the limit",
4549 mPid);
4550 return false;
4551 }
4552
4553 mTimedTrackCount++;
4554 return true;
4555}
4556
4557// Release a slot for a timed audio track
4558void AudioFlinger::Client::releaseTimedTrack()
4559{
4560 Mutex::Autolock _l(mTimedTrackLock);
4561 mTimedTrackCount--;
4562}
4563
Mathias Agopian65ab4712010-07-14 17:59:35 -07004564// ----------------------------------------------------------------------------
4565
4566AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4567 const sp<IAudioFlingerClient>& client,
4568 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004569 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004570{
4571}
4572
4573AudioFlinger::NotificationClient::~NotificationClient()
4574{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004575}
4576
4577void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4578{
4579 sp<NotificationClient> keep(this);
4580 {
4581 mAudioFlinger->removeNotificationClient(mPid);
4582 }
4583}
4584
4585// ----------------------------------------------------------------------------
4586
4587AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4588 : BnAudioTrack(),
4589 mTrack(track)
4590{
4591}
4592
4593AudioFlinger::TrackHandle::~TrackHandle() {
4594 // just stop the track on deletion, associated resources
4595 // will be freed from the main thread once all pending buffers have
4596 // been played. Unless it's not in the active track list, in which
4597 // case we free everything now...
4598 mTrack->destroy();
4599}
4600
Glenn Kasten90716c52012-01-26 13:40:12 -08004601sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4602 return mTrack->getCblk();
4603}
4604
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004605status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4606 return mTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004607}
4608
4609void AudioFlinger::TrackHandle::stop() {
4610 mTrack->stop();
4611}
4612
4613void AudioFlinger::TrackHandle::flush() {
4614 mTrack->flush();
4615}
4616
4617void AudioFlinger::TrackHandle::mute(bool e) {
4618 mTrack->mute(e);
4619}
4620
4621void AudioFlinger::TrackHandle::pause() {
4622 mTrack->pause();
4623}
4624
Mathias Agopian65ab4712010-07-14 17:59:35 -07004625status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4626{
4627 return mTrack->attachAuxEffect(EffectId);
4628}
4629
John Grossman4ff14ba2012-02-08 16:37:41 -08004630status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4631 sp<IMemory>* buffer) {
4632 if (!mTrack->isTimedTrack())
4633 return INVALID_OPERATION;
4634
4635 PlaybackThread::TimedTrack* tt =
4636 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4637 return tt->allocateTimedBuffer(size, buffer);
4638}
4639
4640status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4641 int64_t pts) {
4642 if (!mTrack->isTimedTrack())
4643 return INVALID_OPERATION;
4644
4645 PlaybackThread::TimedTrack* tt =
4646 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4647 return tt->queueTimedBuffer(buffer, pts);
4648}
4649
4650status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4651 const LinearTransform& xform, int target) {
4652
4653 if (!mTrack->isTimedTrack())
4654 return INVALID_OPERATION;
4655
4656 PlaybackThread::TimedTrack* tt =
4657 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4658 return tt->setMediaTimeTransform(
4659 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4660}
4661
Mathias Agopian65ab4712010-07-14 17:59:35 -07004662status_t AudioFlinger::TrackHandle::onTransact(
4663 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4664{
4665 return BnAudioTrack::onTransact(code, data, reply, flags);
4666}
4667
4668// ----------------------------------------------------------------------------
4669
4670sp<IAudioRecord> AudioFlinger::openRecord(
4671 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004672 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004673 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004674 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004675 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004676 int frameCount,
4677 uint32_t flags,
4678 int *sessionId,
4679 status_t *status)
4680{
4681 sp<RecordThread::RecordTrack> recordTrack;
4682 sp<RecordHandle> recordHandle;
4683 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004684 status_t lStatus;
4685 RecordThread *thread;
4686 size_t inFrameCount;
4687 int lSessionId;
4688
4689 // check calling permissions
4690 if (!recordingAllowed()) {
4691 lStatus = PERMISSION_DENIED;
4692 goto Exit;
4693 }
4694
4695 // add client to list
4696 { // scope for mLock
4697 Mutex::Autolock _l(mLock);
4698 thread = checkRecordThread_l(input);
4699 if (thread == NULL) {
4700 lStatus = BAD_VALUE;
4701 goto Exit;
4702 }
4703
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004704 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004705
4706 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004707 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004708 lSessionId = *sessionId;
4709 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004710 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004711 if (sessionId != NULL) {
4712 *sessionId = lSessionId;
4713 }
4714 }
4715 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004716 recordTrack = thread->createRecordTrack_l(client,
4717 sampleRate,
4718 format,
4719 channelMask,
4720 frameCount,
4721 flags,
4722 lSessionId,
4723 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004724 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004725 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004726 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4727 // destructor is called by the TrackBase destructor with mLock held
4728 client.clear();
4729 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004730 goto Exit;
4731 }
4732
4733 // return to handle to client
4734 recordHandle = new RecordHandle(recordTrack);
4735 lStatus = NO_ERROR;
4736
4737Exit:
4738 if (status) {
4739 *status = lStatus;
4740 }
4741 return recordHandle;
4742}
4743
4744// ----------------------------------------------------------------------------
4745
4746AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4747 : BnAudioRecord(),
4748 mRecordTrack(recordTrack)
4749{
4750}
4751
4752AudioFlinger::RecordHandle::~RecordHandle() {
4753 stop();
4754}
4755
Glenn Kasten90716c52012-01-26 13:40:12 -08004756sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4757 return mRecordTrack->getCblk();
4758}
4759
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004760status_t AudioFlinger::RecordHandle::start(pid_t tid) {
Steve Block3856b092011-10-20 11:56:00 +01004761 ALOGV("RecordHandle::start()");
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004762 return mRecordTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004763}
4764
4765void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004766 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004767 mRecordTrack->stop();
4768}
4769
Mathias Agopian65ab4712010-07-14 17:59:35 -07004770status_t AudioFlinger::RecordHandle::onTransact(
4771 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4772{
4773 return BnAudioRecord::onTransact(code, data, reply, flags);
4774}
4775
4776// ----------------------------------------------------------------------------
4777
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004778AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4779 AudioStreamIn *input,
4780 uint32_t sampleRate,
4781 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004782 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004783 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004784 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004785 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4786 // mRsmpInIndex and mInputBytes set by readInputParameters()
4787 mReqChannelCount(popcount(channels)),
4788 mReqSampleRate(sampleRate)
4789 // mBytesRead is only meaningful while active, and so is cleared in start()
4790 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004791{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004792 snprintf(mName, kNameLength, "AudioIn_%d", id);
4793
Mathias Agopian65ab4712010-07-14 17:59:35 -07004794 readInputParameters();
4795}
4796
4797
4798AudioFlinger::RecordThread::~RecordThread()
4799{
4800 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004801 delete mResampler;
4802 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004803}
4804
4805void AudioFlinger::RecordThread::onFirstRef()
4806{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004807 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004808}
4809
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004810status_t AudioFlinger::RecordThread::readyToRun()
4811{
4812 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004813 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004814 return status;
4815}
4816
Mathias Agopian65ab4712010-07-14 17:59:35 -07004817bool AudioFlinger::RecordThread::threadLoop()
4818{
4819 AudioBufferProvider::Buffer buffer;
4820 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004821 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004822
Eric Laurent44d98482010-09-30 16:12:31 -07004823 nsecs_t lastWarning = 0;
4824
Eric Laurentfeb0db62011-07-22 09:04:31 -07004825 acquireWakeLock();
4826
Mathias Agopian65ab4712010-07-14 17:59:35 -07004827 // start recording
4828 while (!exitPending()) {
4829
4830 processConfigEvents();
4831
4832 { // scope for mLock
4833 Mutex::Autolock _l(mLock);
4834 checkForNewParameters_l();
4835 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4836 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004837 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004838 mStandby = true;
4839 }
4840
4841 if (exitPending()) break;
4842
Eric Laurentfeb0db62011-07-22 09:04:31 -07004843 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004844 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004845 // go to sleep
4846 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004847 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004848 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004849 continue;
4850 }
4851 if (mActiveTrack != 0) {
4852 if (mActiveTrack->mState == TrackBase::PAUSING) {
4853 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004854 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004855 mStandby = true;
4856 }
4857 mActiveTrack.clear();
4858 mStartStopCond.broadcast();
4859 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4860 if (mReqChannelCount != mActiveTrack->channelCount()) {
4861 mActiveTrack.clear();
4862 mStartStopCond.broadcast();
4863 } else if (mBytesRead != 0) {
4864 // record start succeeds only if first read from audio input
4865 // succeeds
4866 if (mBytesRead > 0) {
4867 mActiveTrack->mState = TrackBase::ACTIVE;
4868 } else {
4869 mActiveTrack.clear();
4870 }
4871 mStartStopCond.broadcast();
4872 }
4873 mStandby = false;
4874 }
4875 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004876 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004877 }
4878
4879 if (mActiveTrack != 0) {
4880 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4881 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004882 unlockEffectChains(effectChains);
4883 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004884 continue;
4885 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004886 for (size_t i = 0; i < effectChains.size(); i ++) {
4887 effectChains[i]->process_l();
4888 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004889
Mathias Agopian65ab4712010-07-14 17:59:35 -07004890 buffer.frameCount = mFrameCount;
John Grossman4ff14ba2012-02-08 16:37:41 -08004891 if (CC_LIKELY(mActiveTrack->getNextBuffer(
4892 &buffer, AudioBufferProvider::kInvalidPTS) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004893 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004894 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004895 // no resampling
4896 while (framesOut) {
4897 size_t framesIn = mFrameCount - mRsmpInIndex;
4898 if (framesIn) {
4899 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4900 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4901 if (framesIn > framesOut)
4902 framesIn = framesOut;
4903 mRsmpInIndex += framesIn;
4904 framesOut -= framesIn;
4905 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004906 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004907 memcpy(dst, src, framesIn * mFrameSize);
4908 } else {
4909 int16_t *src16 = (int16_t *)src;
4910 int16_t *dst16 = (int16_t *)dst;
4911 if (mChannelCount == 1) {
4912 while (framesIn--) {
4913 *dst16++ = *src16;
4914 *dst16++ = *src16++;
4915 }
4916 } else {
4917 while (framesIn--) {
4918 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4919 src16 += 2;
4920 }
4921 }
4922 }
4923 }
4924 if (framesOut && mFrameCount == mRsmpInIndex) {
4925 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004926 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004927 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004928 framesOut = 0;
4929 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004930 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004931 mRsmpInIndex = 0;
4932 }
4933 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004934 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004935 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4936 // Force input into standby so that it tries to
4937 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004938 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004939 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004940 }
4941 mRsmpInIndex = mFrameCount;
4942 framesOut = 0;
4943 buffer.frameCount = 0;
4944 }
4945 }
4946 }
4947 } else {
4948 // resampling
4949
4950 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4951 // alter output frame count as if we were expecting stereo samples
4952 if (mChannelCount == 1 && mReqChannelCount == 1) {
4953 framesOut >>= 1;
4954 }
4955 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4956 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4957 // are 32 bit aligned which should be always true.
4958 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004959 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004960 // the resampler always outputs stereo samples: do post stereo to mono conversion
4961 int16_t *src = (int16_t *)mRsmpOutBuffer;
4962 int16_t *dst = buffer.i16;
4963 while (framesOut--) {
4964 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4965 src += 2;
4966 }
4967 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004968 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004969 }
4970
4971 }
4972 mActiveTrack->releaseBuffer(&buffer);
4973 mActiveTrack->overflow();
4974 }
4975 // client isn't retrieving buffers fast enough
4976 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004977 if (!mActiveTrack->setOverflow()) {
4978 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004979 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004980 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004981 lastWarning = now;
4982 }
4983 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004984 // Release the processor for a while before asking for a new buffer.
4985 // This will give the application more chance to read from the buffer and
4986 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004987 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004988 }
4989 }
Eric Laurentec437d82011-07-26 20:54:46 -07004990 // enable changes in effect chain
4991 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004992 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004993 }
4994
4995 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004996 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004997 }
4998 mActiveTrack.clear();
4999
5000 mStartStopCond.broadcast();
5001
Eric Laurentfeb0db62011-07-22 09:04:31 -07005002 releaseWakeLock();
5003
Steve Block3856b092011-10-20 11:56:00 +01005004 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005005 return false;
5006}
5007
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005008
5009sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5010 const sp<AudioFlinger::Client>& client,
5011 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005012 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005013 int channelMask,
5014 int frameCount,
5015 uint32_t flags,
5016 int sessionId,
5017 status_t *status)
5018{
5019 sp<RecordTrack> track;
5020 status_t lStatus;
5021
5022 lStatus = initCheck();
5023 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005024 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005025 goto Exit;
5026 }
5027
5028 { // scope for mLock
5029 Mutex::Autolock _l(mLock);
5030
5031 track = new RecordTrack(this, client, sampleRate,
5032 format, channelMask, frameCount, flags, sessionId);
5033
Glenn Kasten7378ca52012-01-20 13:44:40 -08005034 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005035 lStatus = NO_MEMORY;
5036 goto Exit;
5037 }
5038
5039 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005040 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5041 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005042 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005043 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5044 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005045 }
5046 lStatus = NO_ERROR;
5047
5048Exit:
5049 if (status) {
5050 *status = lStatus;
5051 }
5052 return track;
5053}
5054
Glenn Kasten6dbc1352012-02-02 10:56:47 -08005055status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005056{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08005057 ALOGV("RecordThread::start tid=%d", tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005058 sp <ThreadBase> strongMe = this;
5059 status_t status = NO_ERROR;
5060 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005061 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005062 if (mActiveTrack != 0) {
5063 if (recordTrack != mActiveTrack.get()) {
5064 status = -EBUSY;
5065 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5066 mActiveTrack->mState = TrackBase::ACTIVE;
5067 }
5068 return status;
5069 }
5070
5071 recordTrack->mState = TrackBase::IDLE;
5072 mActiveTrack = recordTrack;
5073 mLock.unlock();
5074 status_t status = AudioSystem::startInput(mId);
5075 mLock.lock();
5076 if (status != NO_ERROR) {
5077 mActiveTrack.clear();
5078 return status;
5079 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005080 mRsmpInIndex = mFrameCount;
5081 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005082 if (mResampler != NULL) {
5083 mResampler->reset();
5084 }
5085 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005086 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005087 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005088 mWaitWorkCV.signal();
5089 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005090 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005091 mActiveTrack.clear();
5092 status = INVALID_OPERATION;
5093 goto startError;
5094 }
5095 mStartStopCond.wait(mLock);
5096 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005097 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005098 status = BAD_VALUE;
5099 goto startError;
5100 }
Steve Block3856b092011-10-20 11:56:00 +01005101 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005102 return status;
5103 }
5104startError:
5105 AudioSystem::stopInput(mId);
5106 return status;
5107}
5108
5109void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005110 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005111 sp <ThreadBase> strongMe = this;
5112 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005113 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005114 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5115 mActiveTrack->mState = TrackBase::PAUSING;
5116 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005117 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005118 return;
5119 }
5120 mStartStopCond.wait(mLock);
5121 // if we have been restarted, recordTrack == mActiveTrack.get() here
5122 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5123 mLock.unlock();
5124 AudioSystem::stopInput(mId);
5125 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005126 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005127 }
5128 }
5129 }
5130}
5131
5132status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5133{
5134 const size_t SIZE = 256;
5135 char buffer[SIZE];
5136 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005137
5138 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5139 result.append(buffer);
5140
5141 if (mActiveTrack != 0) {
5142 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005143 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005144 mActiveTrack->dump(buffer, SIZE);
5145 result.append(buffer);
5146
5147 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5148 result.append(buffer);
5149 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5150 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005151 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005152 result.append(buffer);
5153 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5154 result.append(buffer);
5155 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5156 result.append(buffer);
5157
5158
5159 } else {
5160 result.append("No record client\n");
5161 }
5162 write(fd, result.string(), result.size());
5163
5164 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005165 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005166
5167 return NO_ERROR;
5168}
5169
John Grossman4ff14ba2012-02-08 16:37:41 -08005170status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005171{
5172 size_t framesReq = buffer->frameCount;
5173 size_t framesReady = mFrameCount - mRsmpInIndex;
5174 int channelCount;
5175
5176 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005177 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005178 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005179 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005180 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5181 // Force input into standby so that it tries to
5182 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005183 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005184 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005185 }
Glenn Kastene0feee32011-12-13 11:53:26 -08005186 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005187 buffer->frameCount = 0;
5188 return NOT_ENOUGH_DATA;
5189 }
5190 mRsmpInIndex = 0;
5191 framesReady = mFrameCount;
5192 }
5193
5194 if (framesReq > framesReady) {
5195 framesReq = framesReady;
5196 }
5197
5198 if (mChannelCount == 1 && mReqChannelCount == 2) {
5199 channelCount = 1;
5200 } else {
5201 channelCount = 2;
5202 }
5203 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5204 buffer->frameCount = framesReq;
5205 return NO_ERROR;
5206}
5207
5208void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5209{
5210 mRsmpInIndex += buffer->frameCount;
5211 buffer->frameCount = 0;
5212}
5213
5214bool AudioFlinger::RecordThread::checkForNewParameters_l()
5215{
5216 bool reconfig = false;
5217
5218 while (!mNewParameters.isEmpty()) {
5219 status_t status = NO_ERROR;
5220 String8 keyValuePair = mNewParameters[0];
5221 AudioParameter param = AudioParameter(keyValuePair);
5222 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08005223 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005224 int reqSamplingRate = mReqSampleRate;
5225 int reqChannelCount = mReqChannelCount;
5226
5227 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5228 reqSamplingRate = value;
5229 reconfig = true;
5230 }
5231 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08005232 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005233 reconfig = true;
5234 }
5235 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005236 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005237 reconfig = true;
5238 }
5239 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5240 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08005241 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005242 // if frame count is changed after track creation
5243 if (mActiveTrack != 0) {
5244 status = INVALID_OPERATION;
5245 } else {
5246 reconfig = true;
5247 }
5248 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005249 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5250 // forward device change to effects that have requested to be
5251 // aware of attached audio device.
5252 for (size_t i = 0; i < mEffectChains.size(); i++) {
5253 mEffectChains[i]->setDevice_l(value);
5254 }
5255 // store input device and output device but do not forward output device to audio HAL.
5256 // Note that status is ignored by the caller for output device
5257 // (see AudioFlinger::setParameters()
5258 if (value & AUDIO_DEVICE_OUT_ALL) {
5259 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5260 status = BAD_VALUE;
5261 } else {
5262 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07005263 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5264 if (mTrack != NULL) {
5265 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005266 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005267 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5268 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5269 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005270 }
5271 mDevice |= (uint32_t)value;
5272 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005273 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005274 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005275 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005276 mInput->stream->common.standby(&mInput->stream->common);
5277 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005278 }
5279 if (reconfig) {
5280 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005281 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005282 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005283 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
5284 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005285 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005286 status = NO_ERROR;
5287 }
5288 if (status == NO_ERROR) {
5289 readInputParameters();
5290 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5291 }
5292 }
5293 }
5294
5295 mNewParameters.removeAt(0);
5296
5297 mParamStatus = status;
5298 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07005299 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5300 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08005301 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005302 }
5303 return reconfig;
5304}
5305
5306String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5307{
Dima Zavinfce7a472011-04-19 22:30:36 -07005308 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005309 String8 out_s8 = String8();
5310
5311 Mutex::Autolock _l(mLock);
5312 if (initCheck() != NO_ERROR) {
5313 return out_s8;
5314 }
Dima Zavinfce7a472011-04-19 22:30:36 -07005315
Dima Zavin799a70e2011-04-18 16:57:27 -07005316 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07005317 out_s8 = String8(s);
5318 free(s);
5319 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005320}
5321
5322void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5323 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08005324 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005325
5326 switch (event) {
5327 case AudioSystem::INPUT_OPENED:
5328 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005329 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005330 desc.samplingRate = mSampleRate;
5331 desc.format = mFormat;
5332 desc.frameCount = mFrameCount;
5333 desc.latency = 0;
5334 param2 = &desc;
5335 break;
5336
5337 case AudioSystem::INPUT_CLOSED:
5338 default:
5339 break;
5340 }
5341 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5342}
5343
5344void AudioFlinger::RecordThread::readInputParameters()
5345{
Glenn Kastene9dd0172012-01-27 18:08:45 -08005346 delete mRsmpInBuffer;
5347 // mRsmpInBuffer is always assigned a new[] below
5348 delete mRsmpOutBuffer;
5349 mRsmpOutBuffer = NULL;
5350 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08005351 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005352
Dima Zavin799a70e2011-04-18 16:57:27 -07005353 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005354 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5355 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07005356 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08005357 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07005358 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005359 mFrameCount = mInputBytes / mFrameSize;
5360 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5361
5362 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
5363 {
5364 int channelCount;
5365 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5366 // stereo to mono post process as the resampler always outputs stereo.
5367 if (mChannelCount == 1 && mReqChannelCount == 2) {
5368 channelCount = 1;
5369 } else {
5370 channelCount = 2;
5371 }
5372 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5373 mResampler->setSampleRate(mSampleRate);
5374 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5375 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5376
5377 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5378 if (mChannelCount == 1 && mReqChannelCount == 1) {
5379 mFrameCount >>= 1;
5380 }
5381
5382 }
5383 mRsmpInIndex = mFrameCount;
5384}
5385
5386unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5387{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005388 Mutex::Autolock _l(mLock);
5389 if (initCheck() != NO_ERROR) {
5390 return 0;
5391 }
5392
Dima Zavin799a70e2011-04-18 16:57:27 -07005393 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005394}
5395
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005396uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5397{
5398 Mutex::Autolock _l(mLock);
5399 uint32_t result = 0;
5400 if (getEffectChain_l(sessionId) != 0) {
5401 result = EFFECT_SESSION;
5402 }
5403
5404 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5405 result |= TRACK_SESSION;
5406 }
5407
5408 return result;
5409}
5410
Eric Laurent59bd0da2011-08-01 09:52:20 -07005411AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5412{
5413 Mutex::Autolock _l(mLock);
5414 return mTrack;
5415}
5416
Glenn Kastenaed850d2012-01-26 09:46:34 -08005417AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005418{
5419 Mutex::Autolock _l(mLock);
5420 return mInput;
5421}
5422
5423AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5424{
5425 Mutex::Autolock _l(mLock);
5426 AudioStreamIn *input = mInput;
5427 mInput = NULL;
5428 return input;
5429}
5430
5431// this method must always be called either with ThreadBase mLock held or inside the thread loop
5432audio_stream_t* AudioFlinger::RecordThread::stream()
5433{
5434 if (mInput == NULL) {
5435 return NULL;
5436 }
5437 return &mInput->stream->common;
5438}
5439
5440
Mathias Agopian65ab4712010-07-14 17:59:35 -07005441// ----------------------------------------------------------------------------
5442
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005443audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005444 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005445 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005446 uint32_t *pChannels,
5447 uint32_t *pLatencyMs,
5448 uint32_t flags)
5449{
5450 status_t status;
5451 PlaybackThread *thread = NULL;
5452 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
5453 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005454 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005455 uint32_t channels = pChannels ? *pChannels : 0;
5456 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07005457 audio_stream_out_t *outStream;
5458 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005459
Steve Block3856b092011-10-20 11:56:00 +01005460 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07005461 pDevices ? *pDevices : 0,
5462 samplingRate,
5463 format,
5464 channels,
5465 flags);
5466
5467 if (pDevices == NULL || *pDevices == 0) {
5468 return 0;
5469 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005470
Mathias Agopian65ab4712010-07-14 17:59:35 -07005471 Mutex::Autolock _l(mLock);
5472
Dima Zavin799a70e2011-04-18 16:57:27 -07005473 outHwDev = findSuitableHwDev_l(*pDevices);
5474 if (outHwDev == NULL)
5475 return 0;
5476
Glenn Kasten58f30212012-01-12 12:27:51 -08005477 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005478 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01005479 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005480 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005481 samplingRate,
5482 format,
5483 channels,
5484 status);
5485
5486 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07005487 if (outStream != NULL) {
5488 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005489 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07005490
Dima Zavinfce7a472011-04-19 22:30:36 -07005491 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5492 (format != AUDIO_FORMAT_PCM_16_BIT) ||
5493 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005494 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005495 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005496 } else {
5497 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005498 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005499 }
5500 mPlaybackThreads.add(id, thread);
5501
Glenn Kastena0d68332012-01-27 16:47:15 -08005502 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5503 if (pFormat != NULL) *pFormat = format;
5504 if (pChannels != NULL) *pChannels = channels;
5505 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005506
5507 // notify client processes of the new output creation
5508 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5509 return id;
5510 }
5511
5512 return 0;
5513}
5514
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005515audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
5516 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005517{
5518 Mutex::Autolock _l(mLock);
5519 MixerThread *thread1 = checkMixerThread_l(output1);
5520 MixerThread *thread2 = checkMixerThread_l(output2);
5521
5522 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005523 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005524 return 0;
5525 }
5526
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005527 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005528 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5529 thread->addOutputTrack(thread2);
5530 mPlaybackThreads.add(id, thread);
5531 // notify client processes of the new output creation
5532 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5533 return id;
5534}
5535
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005536status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005537{
5538 // keep strong reference on the playback thread so that
5539 // it is not destroyed while exit() is executed
5540 sp <PlaybackThread> thread;
5541 {
5542 Mutex::Autolock _l(mLock);
5543 thread = checkPlaybackThread_l(output);
5544 if (thread == NULL) {
5545 return BAD_VALUE;
5546 }
5547
Steve Block3856b092011-10-20 11:56:00 +01005548 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005549
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005550 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005551 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005552 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005553 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5554 dupThread->removeOutputTrack((MixerThread *)thread.get());
5555 }
5556 }
5557 }
Glenn Kastena0d68332012-01-27 16:47:15 -08005558 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005559 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
5560 mPlaybackThreads.removeItem(output);
5561 }
5562 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005563 // The thread entity (active unit of execution) is no longer running here,
5564 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005565
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005566 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005567 AudioStreamOut *out = thread->clearOutput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005568 assert(out != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005569 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005570 out->hwDev->close_output_stream(out->hwDev, out->stream);
5571 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005572 }
5573 return NO_ERROR;
5574}
5575
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005576status_t AudioFlinger::suspendOutput(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("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005586 thread->suspend();
5587
5588 return NO_ERROR;
5589}
5590
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005591status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005592{
5593 Mutex::Autolock _l(mLock);
5594 PlaybackThread *thread = checkPlaybackThread_l(output);
5595
5596 if (thread == NULL) {
5597 return BAD_VALUE;
5598 }
5599
Steve Block3856b092011-10-20 11:56:00 +01005600 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005601
5602 thread->restore();
5603
5604 return NO_ERROR;
5605}
5606
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005607audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005608 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005609 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005610 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005611 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005612{
5613 status_t status;
5614 RecordThread *thread = NULL;
5615 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005616 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005617 uint32_t channels = pChannels ? *pChannels : 0;
5618 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005619 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005620 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005621 audio_stream_in_t *inStream;
5622 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005623
5624 if (pDevices == NULL || *pDevices == 0) {
5625 return 0;
5626 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005627
Mathias Agopian65ab4712010-07-14 17:59:35 -07005628 Mutex::Autolock _l(mLock);
5629
Dima Zavin799a70e2011-04-18 16:57:27 -07005630 inHwDev = findSuitableHwDev_l(*pDevices);
5631 if (inHwDev == NULL)
5632 return 0;
5633
Glenn Kasten58f30212012-01-12 12:27:51 -08005634 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005635 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005636 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005637 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005638 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005639 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005640 samplingRate,
5641 format,
5642 channels,
5643 acoustics,
5644 status);
5645
5646 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5647 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5648 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005649 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005650 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005651 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005652 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005653 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005654 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005655 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005656 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005657 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005658 }
5659
Dima Zavin799a70e2011-04-18 16:57:27 -07005660 if (inStream != NULL) {
5661 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5662
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005663 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005664 // Start record thread
5665 // RecorThread require both input and output device indication to forward to audio
5666 // pre processing modules
5667 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5668 thread = new RecordThread(this,
5669 input,
5670 reqSamplingRate,
5671 reqChannels,
5672 id,
5673 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005674 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005675 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005676 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5677 if (pFormat != NULL) *pFormat = format;
5678 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005679
Dima Zavin799a70e2011-04-18 16:57:27 -07005680 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005681
5682 // notify client processes of the new input creation
5683 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5684 return id;
5685 }
5686
5687 return 0;
5688}
5689
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005690status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005691{
5692 // keep strong reference on the record thread so that
5693 // it is not destroyed while exit() is executed
5694 sp <RecordThread> thread;
5695 {
5696 Mutex::Autolock _l(mLock);
5697 thread = checkRecordThread_l(input);
5698 if (thread == NULL) {
5699 return BAD_VALUE;
5700 }
5701
Steve Block3856b092011-10-20 11:56:00 +01005702 ALOGV("closeInput() %d", input);
Glenn Kastena0d68332012-01-27 16:47:15 -08005703 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005704 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5705 mRecordThreads.removeItem(input);
5706 }
5707 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005708 // The thread entity (active unit of execution) is no longer running here,
5709 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005710
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005711 AudioStreamIn *in = thread->clearInput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005712 assert(in != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005713 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005714 in->hwDev->close_input_stream(in->hwDev, in->stream);
5715 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005716
5717 return NO_ERROR;
5718}
5719
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005720status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005721{
5722 Mutex::Autolock _l(mLock);
5723 MixerThread *dstThread = checkMixerThread_l(output);
5724 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005725 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005726 return BAD_VALUE;
5727 }
5728
Steve Block3856b092011-10-20 11:56:00 +01005729 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005730 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5731
Eric Laurent9f6530f2011-08-30 10:18:54 -07005732 dstThread->setStreamValid(stream, true);
5733
Mathias Agopian65ab4712010-07-14 17:59:35 -07005734 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5735 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5736 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005737 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005738 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005739 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005740 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005741 }
Eric Laurentde070132010-07-13 04:45:46 -07005742 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005743
5744 return NO_ERROR;
5745}
5746
5747
5748int AudioFlinger::newAudioSessionId()
5749{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005750 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005751}
5752
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005753void AudioFlinger::acquireAudioSessionId(int audioSession)
5754{
5755 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005756 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005757 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005758 size_t num = mAudioSessionRefs.size();
5759 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005760 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5761 if (ref->sessionid == audioSession && ref->pid == caller) {
5762 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005763 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005764 return;
5765 }
5766 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005767 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5768 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005769}
5770
5771void AudioFlinger::releaseAudioSessionId(int audioSession)
5772{
5773 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005774 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005775 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005776 size_t num = mAudioSessionRefs.size();
5777 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005778 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5779 if (ref->sessionid == audioSession && ref->pid == caller) {
5780 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005781 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005782 if (ref->cnt == 0) {
5783 mAudioSessionRefs.removeAt(i);
5784 delete ref;
5785 purgeStaleEffects_l();
5786 }
5787 return;
5788 }
5789 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005790 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005791}
5792
5793void AudioFlinger::purgeStaleEffects_l() {
5794
Steve Block3856b092011-10-20 11:56:00 +01005795 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005796
5797 Vector< sp<EffectChain> > chains;
5798
5799 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5800 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5801 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5802 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005803 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5804 chains.push(ec);
5805 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005806 }
5807 }
5808 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5809 sp<RecordThread> t = mRecordThreads.valueAt(i);
5810 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5811 sp<EffectChain> ec = t->mEffectChains[j];
5812 chains.push(ec);
5813 }
5814 }
5815
5816 for (size_t i = 0; i < chains.size(); i++) {
5817 sp<EffectChain> ec = chains[i];
5818 int sessionid = ec->sessionId();
5819 sp<ThreadBase> t = ec->mThread.promote();
5820 if (t == 0) {
5821 continue;
5822 }
5823 size_t numsessionrefs = mAudioSessionRefs.size();
5824 bool found = false;
5825 for (size_t k = 0; k < numsessionrefs; k++) {
5826 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5827 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005828 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005829 sessionid, ref->pid, ref->cnt);
5830 found = true;
5831 break;
5832 }
5833 }
5834 if (!found) {
5835 // remove all effects from the chain
5836 while (ec->mEffects.size()) {
5837 sp<EffectModule> effect = ec->mEffects[0];
5838 effect->unPin();
5839 Mutex::Autolock _l (t->mLock);
5840 t->removeEffect_l(effect);
5841 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5842 sp<EffectHandle> handle = effect->mHandles[j].promote();
5843 if (handle != 0) {
5844 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005845 if (handle->mHasControl && handle->mEnabled) {
5846 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5847 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005848 }
5849 }
5850 AudioSystem::unregisterEffect(effect->id());
5851 }
5852 }
5853 }
5854 return;
5855}
5856
Mathias Agopian65ab4712010-07-14 17:59:35 -07005857// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005858AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005859{
5860 PlaybackThread *thread = NULL;
5861 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5862 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5863 }
5864 return thread;
5865}
5866
5867// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005868AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005869{
5870 PlaybackThread *thread = checkPlaybackThread_l(output);
5871 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005872 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005873 thread = NULL;
5874 }
5875 }
5876 return (MixerThread *)thread;
5877}
5878
5879// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005880AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005881{
5882 RecordThread *thread = NULL;
5883 if (mRecordThreads.indexOfKey(input) >= 0) {
5884 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5885 }
5886 return thread;
5887}
5888
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005889uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005890{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005891 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005892}
5893
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005894AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5895{
5896 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5897 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005898 AudioStreamOut *output = thread->getOutput();
5899 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005900 return thread;
5901 }
5902 }
5903 return NULL;
5904}
5905
5906uint32_t AudioFlinger::primaryOutputDevice_l()
5907{
5908 PlaybackThread *thread = primaryPlaybackThread_l();
5909
5910 if (thread == NULL) {
5911 return 0;
5912 }
5913
5914 return thread->device();
5915}
5916
5917
Mathias Agopian65ab4712010-07-14 17:59:35 -07005918// ----------------------------------------------------------------------------
5919// Effect management
5920// ----------------------------------------------------------------------------
5921
5922
Glenn Kastenf587ba52012-01-26 16:25:10 -08005923status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005924{
5925 Mutex::Autolock _l(mLock);
5926 return EffectQueryNumberEffects(numEffects);
5927}
5928
Glenn Kastenf587ba52012-01-26 16:25:10 -08005929status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005930{
5931 Mutex::Autolock _l(mLock);
5932 return EffectQueryEffect(index, descriptor);
5933}
5934
Glenn Kasten5e92a782012-01-30 07:40:52 -08005935status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08005936 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005937{
5938 Mutex::Autolock _l(mLock);
5939 return EffectGetDescriptor(pUuid, descriptor);
5940}
5941
5942
Mathias Agopian65ab4712010-07-14 17:59:35 -07005943sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5944 effect_descriptor_t *pDesc,
5945 const sp<IEffectClient>& effectClient,
5946 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005947 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005948 int sessionId,
5949 status_t *status,
5950 int *id,
5951 int *enabled)
5952{
5953 status_t lStatus = NO_ERROR;
5954 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005955 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005956
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005957 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005958 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005959
5960 if (pDesc == NULL) {
5961 lStatus = BAD_VALUE;
5962 goto Exit;
5963 }
5964
Eric Laurent84e9a102010-09-23 16:10:16 -07005965 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005966 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005967 lStatus = PERMISSION_DENIED;
5968 goto Exit;
5969 }
5970
Dima Zavinfce7a472011-04-19 22:30:36 -07005971 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005972 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08005973 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005974 lStatus = PERMISSION_DENIED;
5975 goto Exit;
5976 }
5977
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005978 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005979 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005980 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005981 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005982 lStatus = BAD_VALUE;
5983 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005984 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005985 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005986 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005987 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005988 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005989 }
5990 }
5991
Mathias Agopian65ab4712010-07-14 17:59:35 -07005992 {
5993 Mutex::Autolock _l(mLock);
5994
Mathias Agopian65ab4712010-07-14 17:59:35 -07005995
5996 if (!EffectIsNullUuid(&pDesc->uuid)) {
5997 // if uuid is specified, request effect descriptor
5998 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5999 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006000 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006001 goto Exit;
6002 }
6003 } else {
6004 // if uuid is not specified, look for an available implementation
6005 // of the required type in effect factory
6006 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006007 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006008 lStatus = BAD_VALUE;
6009 goto Exit;
6010 }
6011 uint32_t numEffects = 0;
6012 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006013 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07006014 bool found = false;
6015
6016 lStatus = EffectQueryNumberEffects(&numEffects);
6017 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006018 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006019 goto Exit;
6020 }
6021 for (uint32_t i = 0; i < numEffects; i++) {
6022 lStatus = EffectQueryEffect(i, &desc);
6023 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006024 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006025 continue;
6026 }
6027 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
6028 // If matching type found save effect descriptor. If the session is
6029 // 0 and the effect is not auxiliary, continue enumeration in case
6030 // an auxiliary version of this effect type is available
6031 found = true;
6032 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07006033 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006034 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6035 break;
6036 }
6037 }
6038 }
6039 if (!found) {
6040 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00006041 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006042 goto Exit;
6043 }
6044 // For same effect type, chose auxiliary version over insert version if
6045 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07006046 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006047 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
6048 memcpy(&desc, &d, sizeof(effect_descriptor_t));
6049 }
6050 }
6051
6052 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07006053 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006054 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6055 lStatus = INVALID_OPERATION;
6056 goto Exit;
6057 }
6058
Eric Laurent59255e42011-07-27 19:49:51 -07006059 // check recording permission for visualizer
6060 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
6061 !recordingAllowed()) {
6062 lStatus = PERMISSION_DENIED;
6063 goto Exit;
6064 }
6065
Mathias Agopian65ab4712010-07-14 17:59:35 -07006066 // return effect descriptor
6067 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
6068
6069 // If output is not specified try to find a matching audio session ID in one of the
6070 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07006071 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
6072 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006073 // Note: io is never 0 when creating an effect on an input
6074 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006075 // look for the thread where the specified audio session is present
6076 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6077 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006078 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07006079 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07006080 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006081 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006082 if (io == 0) {
6083 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6084 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6085 io = mRecordThreads.keyAt(i);
6086 break;
6087 }
6088 }
6089 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006090 // If no output thread contains the requested session ID, default to
6091 // first output. The effect chain will be moved to the correct output
6092 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006093 if (io == 0 && mPlaybackThreads.size()) {
6094 io = mPlaybackThreads.keyAt(0);
6095 }
Steve Block3856b092011-10-20 11:56:00 +01006096 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006097 }
6098 ThreadBase *thread = checkRecordThread_l(io);
6099 if (thread == NULL) {
6100 thread = checkPlaybackThread_l(io);
6101 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00006102 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006103 lStatus = BAD_VALUE;
6104 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07006105 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006106 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006107
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006108 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006109
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006110 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07006111 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6112 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006113 if (handle != 0 && id != NULL) {
6114 *id = handle->id();
6115 }
6116 }
6117
6118Exit:
6119 if(status) {
6120 *status = lStatus;
6121 }
6122 return handle;
6123}
6124
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006125status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
6126 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07006127{
Steve Block3856b092011-10-20 11:56:00 +01006128 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07006129 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006130 Mutex::Autolock _l(mLock);
6131 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006132 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006133 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006134 }
Eric Laurentde070132010-07-13 04:45:46 -07006135 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6136 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006137 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006138 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006139 }
Eric Laurentde070132010-07-13 04:45:46 -07006140 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6141 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006142 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006143 return BAD_VALUE;
6144 }
6145
6146 Mutex::Autolock _dl(dstThread->mLock);
6147 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07006148 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07006149
Mathias Agopian65ab4712010-07-14 17:59:35 -07006150 return NO_ERROR;
6151}
6152
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006153// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07006154status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07006155 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07006156 AudioFlinger::PlaybackThread *dstThread,
6157 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07006158{
Steve Block3856b092011-10-20 11:56:00 +01006159 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006160 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07006161
Eric Laurent59255e42011-07-27 19:49:51 -07006162 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006163 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006164 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006165 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07006166 return INVALID_OPERATION;
6167 }
6168
Eric Laurent39e94f82010-07-28 01:32:47 -07006169 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07006170 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07006171 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07006172 // removed.
6173 srcThread->removeEffectChain_l(chain);
6174
6175 // transfer all effects one by one so that new effect chain is created on new thread with
6176 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006177 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07006178 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006179 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07006180 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6181 while (effect != 0) {
6182 srcThread->removeEffect_l(effect);
6183 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07006184 // removeEffect_l() has stopped the effect if it was active so it must be restarted
6185 if (effect->state() == EffectModule::ACTIVE ||
6186 effect->state() == EffectModule::STOPPING) {
6187 effect->start();
6188 }
Eric Laurent39e94f82010-07-28 01:32:47 -07006189 // if the move request is not received from audio policy manager, the effect must be
6190 // re-registered with the new strategy and output
6191 if (dstChain == 0) {
6192 dstChain = effect->chain().promote();
6193 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006194 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07006195 srcThread->addEffect_l(effect);
6196 return NO_INIT;
6197 }
6198 strategy = dstChain->strategy();
6199 }
6200 if (reRegister) {
6201 AudioSystem::unregisterEffect(effect->id());
6202 AudioSystem::registerEffect(&effect->desc(),
6203 dstOutput,
6204 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07006205 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07006206 effect->id());
6207 }
Eric Laurentde070132010-07-13 04:45:46 -07006208 effect = chain->getEffectFromId_l(0);
6209 }
6210
6211 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006212}
6213
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006214
Mathias Agopian65ab4712010-07-14 17:59:35 -07006215// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006216sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07006217 const sp<AudioFlinger::Client>& client,
6218 const sp<IEffectClient>& effectClient,
6219 int32_t priority,
6220 int sessionId,
6221 effect_descriptor_t *desc,
6222 int *enabled,
6223 status_t *status
6224 )
6225{
6226 sp<EffectModule> effect;
6227 sp<EffectHandle> handle;
6228 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006229 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07006230 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006231 bool effectCreated = false;
6232 bool effectRegistered = false;
6233
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006234 lStatus = initCheck();
6235 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006236 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006237 goto Exit;
6238 }
6239
6240 // Do not allow effects with session ID 0 on direct output or duplicating threads
6241 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07006242 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006243 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07006244 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006245 lStatus = BAD_VALUE;
6246 goto Exit;
6247 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006248 // Only Pre processor effects are allowed on input threads and only on input threads
6249 if ((mType == RECORD &&
6250 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
6251 (mType != RECORD &&
6252 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006253 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006254 desc->name, desc->flags, mType);
6255 lStatus = BAD_VALUE;
6256 goto Exit;
6257 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006258
Steve Block3856b092011-10-20 11:56:00 +01006259 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006260
6261 { // scope for mLock
6262 Mutex::Autolock _l(mLock);
6263
6264 // check for existing effect chain with the requested audio session
6265 chain = getEffectChain_l(sessionId);
6266 if (chain == 0) {
6267 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006268 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006269 chain = new EffectChain(this, sessionId);
6270 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07006271 chain->setStrategy(getStrategyForSession_l(sessionId));
6272 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006273 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07006274 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006275 }
6276
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08006277 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006278
6279 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006280 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006281 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07006282 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006283 if (lStatus != NO_ERROR) {
6284 goto Exit;
6285 }
6286 effectRegistered = true;
6287 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07006288 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006289 lStatus = effect->status();
6290 if (lStatus != NO_ERROR) {
6291 goto Exit;
6292 }
Eric Laurentcab11242010-07-15 12:50:15 -07006293 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006294 if (lStatus != NO_ERROR) {
6295 goto Exit;
6296 }
6297 effectCreated = true;
6298
6299 effect->setDevice(mDevice);
6300 effect->setMode(mAudioFlinger->getMode());
6301 }
6302 // create effect handle and connect it to effect module
6303 handle = new EffectHandle(effect, client, effectClient, priority);
6304 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08006305 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006306 *enabled = (int)effect->isEnabled();
6307 }
6308 }
6309
6310Exit:
6311 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07006312 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006313 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07006314 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006315 }
6316 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07006317 AudioSystem::unregisterEffect(effect->id());
6318 }
6319 if (chainCreated) {
6320 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006321 }
6322 handle.clear();
6323 }
6324
6325 if(status) {
6326 *status = lStatus;
6327 }
6328 return handle;
6329}
6330
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006331sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6332{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006333 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08006334 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006335}
6336
Eric Laurentde070132010-07-13 04:45:46 -07006337// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6338// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006339status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07006340{
6341 // check for existing effect chain with the requested audio session
6342 int sessionId = effect->sessionId();
6343 sp<EffectChain> chain = getEffectChain_l(sessionId);
6344 bool chainCreated = false;
6345
6346 if (chain == 0) {
6347 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006348 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006349 chain = new EffectChain(this, sessionId);
6350 addEffectChain_l(chain);
6351 chain->setStrategy(getStrategyForSession_l(sessionId));
6352 chainCreated = true;
6353 }
Steve Block3856b092011-10-20 11:56:00 +01006354 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006355
6356 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006357 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07006358 this, effect->desc().name, chain.get());
6359 return BAD_VALUE;
6360 }
6361
6362 status_t status = chain->addEffect_l(effect);
6363 if (status != NO_ERROR) {
6364 if (chainCreated) {
6365 removeEffectChain_l(chain);
6366 }
6367 return status;
6368 }
6369
6370 effect->setDevice(mDevice);
6371 effect->setMode(mAudioFlinger->getMode());
6372 return NO_ERROR;
6373}
6374
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006375void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07006376
Steve Block3856b092011-10-20 11:56:00 +01006377 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006378 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07006379 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6380 detachAuxEffect_l(effect->id());
6381 }
6382
6383 sp<EffectChain> chain = effect->chain().promote();
6384 if (chain != 0) {
6385 // remove effect chain if removing last effect
6386 if (chain->removeEffect_l(effect) == 0) {
6387 removeEffectChain_l(chain);
6388 }
6389 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00006390 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006391 }
6392}
6393
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006394void AudioFlinger::ThreadBase::lockEffectChains_l(
6395 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
6396{
6397 effectChains = mEffectChains;
6398 for (size_t i = 0; i < mEffectChains.size(); i++) {
6399 mEffectChains[i]->lock();
6400 }
6401}
6402
6403void AudioFlinger::ThreadBase::unlockEffectChains(
6404 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
6405{
6406 for (size_t i = 0; i < effectChains.size(); i++) {
6407 effectChains[i]->unlock();
6408 }
6409}
6410
6411sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6412{
6413 Mutex::Autolock _l(mLock);
6414 return getEffectChain_l(sessionId);
6415}
6416
6417sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6418{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006419 size_t size = mEffectChains.size();
6420 for (size_t i = 0; i < size; i++) {
6421 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08006422 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006423 }
6424 }
Glenn Kasten090f0192012-01-30 13:00:02 -08006425 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006426}
6427
Glenn Kastenf78aee72012-01-04 11:00:47 -08006428void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006429{
6430 Mutex::Autolock _l(mLock);
6431 size_t size = mEffectChains.size();
6432 for (size_t i = 0; i < size; i++) {
6433 mEffectChains[i]->setMode_l(mode);
6434 }
6435}
6436
6437void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006438 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08006439 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07006440
Mathias Agopian65ab4712010-07-14 17:59:35 -07006441 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006442 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006443 // delete the effect module if removing last handle on it
6444 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006445 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006446 removeEffect_l(effect);
6447 AudioSystem::unregisterEffect(effect->id());
6448 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006449 }
6450}
6451
6452status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6453{
6454 int session = chain->sessionId();
6455 int16_t *buffer = mMixBuffer;
6456 bool ownsBuffer = false;
6457
Steve Block3856b092011-10-20 11:56:00 +01006458 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006459 if (session > 0) {
6460 // Only one effect chain can be present in direct output thread and it uses
6461 // the mix buffer as input
6462 if (mType != DIRECT) {
6463 size_t numSamples = mFrameCount * mChannelCount;
6464 buffer = new int16_t[numSamples];
6465 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01006466 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006467 ownsBuffer = true;
6468 }
6469
6470 // Attach all tracks with same session ID to this chain.
6471 for (size_t i = 0; i < mTracks.size(); ++i) {
6472 sp<Track> track = mTracks[i];
6473 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006474 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006475 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006476 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006477 }
6478 }
6479
6480 // indicate all active tracks in the chain
6481 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6482 sp<Track> track = mActiveTracks[i].promote();
6483 if (track == 0) continue;
6484 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006485 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07006486 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006487 }
6488 }
6489 }
6490
6491 chain->setInBuffer(buffer, ownsBuffer);
6492 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006493 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006494 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006495 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6496 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006497 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006498 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6499 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006500 // Effect chain for other sessions are inserted at beginning of effect
6501 // chains list to be processed before output mix effects. Relative order between other
6502 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006503 size_t size = mEffectChains.size();
6504 size_t i = 0;
6505 for (i = 0; i < size; i++) {
6506 if (mEffectChains[i]->sessionId() < session) break;
6507 }
6508 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006509 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006510
6511 return NO_ERROR;
6512}
6513
6514size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6515{
6516 int session = chain->sessionId();
6517
Steve Block3856b092011-10-20 11:56:00 +01006518 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006519
6520 for (size_t i = 0; i < mEffectChains.size(); i++) {
6521 if (chain == mEffectChains[i]) {
6522 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006523 // detach all active tracks from the chain
6524 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6525 sp<Track> track = mActiveTracks[i].promote();
6526 if (track == 0) continue;
6527 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006528 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006529 chain.get(), session);
6530 chain->decActiveTrackCnt();
6531 }
6532 }
6533
Mathias Agopian65ab4712010-07-14 17:59:35 -07006534 // detach all tracks with same session ID from this chain
6535 for (size_t i = 0; i < mTracks.size(); ++i) {
6536 sp<Track> track = mTracks[i];
6537 if (session == track->sessionId()) {
6538 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006539 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006540 }
6541 }
Eric Laurentde070132010-07-13 04:45:46 -07006542 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006543 }
6544 }
6545 return mEffectChains.size();
6546}
6547
Eric Laurentde070132010-07-13 04:45:46 -07006548status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6549 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006550{
6551 Mutex::Autolock _l(mLock);
6552 return attachAuxEffect_l(track, EffectId);
6553}
6554
Eric Laurentde070132010-07-13 04:45:46 -07006555status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6556 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006557{
6558 status_t status = NO_ERROR;
6559
6560 if (EffectId == 0) {
6561 track->setAuxBuffer(0, NULL);
6562 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006563 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6564 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006565 if (effect != 0) {
6566 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6567 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6568 } else {
6569 status = INVALID_OPERATION;
6570 }
6571 } else {
6572 status = BAD_VALUE;
6573 }
6574 }
6575 return status;
6576}
6577
6578void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6579{
6580 for (size_t i = 0; i < mTracks.size(); ++i) {
6581 sp<Track> track = mTracks[i];
6582 if (track->auxEffectId() == effectId) {
6583 attachAuxEffect_l(track, 0);
6584 }
6585 }
6586}
6587
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006588status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6589{
6590 // only one chain per input thread
6591 if (mEffectChains.size() != 0) {
6592 return INVALID_OPERATION;
6593 }
Steve Block3856b092011-10-20 11:56:00 +01006594 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006595
6596 chain->setInBuffer(NULL);
6597 chain->setOutBuffer(NULL);
6598
Eric Laurent59255e42011-07-27 19:49:51 -07006599 checkSuspendOnAddEffectChain_l(chain);
6600
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006601 mEffectChains.add(chain);
6602
6603 return NO_ERROR;
6604}
6605
6606size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6607{
Steve Block3856b092011-10-20 11:56:00 +01006608 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006609 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006610 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6611 chain.get(), mEffectChains.size(), this);
6612 if (mEffectChains.size() == 1) {
6613 mEffectChains.removeAt(0);
6614 }
6615 return 0;
6616}
6617
Mathias Agopian65ab4712010-07-14 17:59:35 -07006618// ----------------------------------------------------------------------------
6619// EffectModule implementation
6620// ----------------------------------------------------------------------------
6621
6622#undef LOG_TAG
6623#define LOG_TAG "AudioFlinger::EffectModule"
6624
6625AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6626 const wp<AudioFlinger::EffectChain>& chain,
6627 effect_descriptor_t *desc,
6628 int id,
6629 int sessionId)
6630 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006631 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006632{
Steve Block3856b092011-10-20 11:56:00 +01006633 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006634 int lStatus;
6635 sp<ThreadBase> thread = mThread.promote();
6636 if (thread == 0) {
6637 return;
6638 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006639
6640 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6641
6642 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006643 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006644
6645 if (mStatus != NO_ERROR) {
6646 return;
6647 }
6648 lStatus = init();
6649 if (lStatus < 0) {
6650 mStatus = lStatus;
6651 goto Error;
6652 }
6653
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006654 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6655 mPinned = true;
6656 }
Steve Block3856b092011-10-20 11:56:00 +01006657 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006658 return;
6659Error:
6660 EffectRelease(mEffectInterface);
6661 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006662 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006663}
6664
6665AudioFlinger::EffectModule::~EffectModule()
6666{
Steve Block3856b092011-10-20 11:56:00 +01006667 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006668 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006669 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6670 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6671 sp<ThreadBase> thread = mThread.promote();
6672 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006673 audio_stream_t *stream = thread->stream();
6674 if (stream != NULL) {
6675 stream->remove_audio_effect(stream, mEffectInterface);
6676 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006677 }
6678 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006679 // release effect engine
6680 EffectRelease(mEffectInterface);
6681 }
6682}
6683
Glenn Kasten435dbe62012-01-30 10:15:48 -08006684status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006685{
6686 status_t status;
6687
6688 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006689 int priority = handle->priority();
6690 size_t size = mHandles.size();
6691 sp<EffectHandle> h;
6692 size_t i;
6693 for (i = 0; i < size; i++) {
6694 h = mHandles[i].promote();
6695 if (h == 0) continue;
6696 if (h->priority() <= priority) break;
6697 }
6698 // if inserted in first place, move effect control from previous owner to this handle
6699 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006700 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006701 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006702 enabled = h->enabled();
6703 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006704 }
Eric Laurent59255e42011-07-27 19:49:51 -07006705 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006706 status = NO_ERROR;
6707 } else {
6708 status = ALREADY_EXISTS;
6709 }
Steve Block3856b092011-10-20 11:56:00 +01006710 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006711 mHandles.insertAt(handle, i);
6712 return status;
6713}
6714
6715size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6716{
6717 Mutex::Autolock _l(mLock);
6718 size_t size = mHandles.size();
6719 size_t i;
6720 for (i = 0; i < size; i++) {
6721 if (mHandles[i] == handle) break;
6722 }
6723 if (i == size) {
6724 return size;
6725 }
Steve Block3856b092011-10-20 11:56:00 +01006726 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006727
6728 bool enabled = false;
6729 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006730 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006731 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006732 enabled = hdl->enabled();
6733 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006734 mHandles.removeAt(i);
6735 size = mHandles.size();
6736 // if removed from first place, move effect control from this handle to next in line
6737 if (i == 0 && size != 0) {
6738 sp<EffectHandle> h = mHandles[0].promote();
6739 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006740 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006741 }
6742 }
6743
Eric Laurentec437d82011-07-26 20:54:46 -07006744 // Prevent calls to process() and other functions on effect interface from now on.
6745 // The effect engine will be released by the destructor when the last strong reference on
6746 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006747 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006748 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006749 }
6750
Mathias Agopian65ab4712010-07-14 17:59:35 -07006751 return size;
6752}
6753
Eric Laurent59255e42011-07-27 19:49:51 -07006754sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6755{
6756 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08006757 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07006758}
6759
Glenn Kasten58123c32012-02-03 10:32:24 -08006760void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006761{
Glenn Kasten90bebef2012-01-27 15:24:38 -08006762 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006763 // keep a strong reference on this EffectModule to avoid calling the
6764 // destructor before we exit
6765 sp<EffectModule> keep(this);
6766 {
6767 sp<ThreadBase> thread = mThread.promote();
6768 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006769 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006770 }
6771 }
6772}
6773
6774void AudioFlinger::EffectModule::updateState() {
6775 Mutex::Autolock _l(mLock);
6776
6777 switch (mState) {
6778 case RESTART:
6779 reset_l();
6780 // FALL THROUGH
6781
6782 case STARTING:
6783 // clear auxiliary effect input buffer for next accumulation
6784 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6785 memset(mConfig.inputCfg.buffer.raw,
6786 0,
6787 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6788 }
6789 start_l();
6790 mState = ACTIVE;
6791 break;
6792 case STOPPING:
6793 stop_l();
6794 mDisableWaitCnt = mMaxDisableWaitCnt;
6795 mState = STOPPED;
6796 break;
6797 case STOPPED:
6798 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6799 // turn off sequence.
6800 if (--mDisableWaitCnt == 0) {
6801 reset_l();
6802 mState = IDLE;
6803 }
6804 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006805 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006806 break;
6807 }
6808}
6809
6810void AudioFlinger::EffectModule::process()
6811{
6812 Mutex::Autolock _l(mLock);
6813
Eric Laurentec437d82011-07-26 20:54:46 -07006814 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006815 mConfig.inputCfg.buffer.raw == NULL ||
6816 mConfig.outputCfg.buffer.raw == NULL) {
6817 return;
6818 }
6819
Eric Laurent8f45bd72010-08-31 13:50:07 -07006820 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006821 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6822 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006823 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006824 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006825 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006826 }
6827
6828 // do the actual processing in the effect engine
6829 int ret = (*mEffectInterface)->process(mEffectInterface,
6830 &mConfig.inputCfg.buffer,
6831 &mConfig.outputCfg.buffer);
6832
6833 // force transition to IDLE state when engine is ready
6834 if (mState == STOPPED && ret == -ENODATA) {
6835 mDisableWaitCnt = 1;
6836 }
6837
6838 // clear auxiliary effect input buffer for next accumulation
6839 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006840 memset(mConfig.inputCfg.buffer.raw, 0,
6841 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006842 }
6843 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006844 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6845 // If an insert effect is idle and input buffer is different from output buffer,
6846 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006847 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006848 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006849 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6850 int16_t *in = mConfig.inputCfg.buffer.s16;
6851 int16_t *out = mConfig.outputCfg.buffer.s16;
6852 for (size_t i = 0; i < frameCnt; i++) {
6853 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006854 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006855 }
6856 }
6857}
6858
6859void AudioFlinger::EffectModule::reset_l()
6860{
6861 if (mEffectInterface == NULL) {
6862 return;
6863 }
6864 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6865}
6866
6867status_t AudioFlinger::EffectModule::configure()
6868{
6869 uint32_t channels;
6870 if (mEffectInterface == NULL) {
6871 return NO_INIT;
6872 }
6873
6874 sp<ThreadBase> thread = mThread.promote();
6875 if (thread == 0) {
6876 return DEAD_OBJECT;
6877 }
6878
6879 // TODO: handle configuration of effects replacing track process
6880 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006881 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006882 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006883 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006884 }
6885
6886 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006887 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006888 } else {
6889 mConfig.inputCfg.channels = channels;
6890 }
6891 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006892 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6893 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006894 mConfig.inputCfg.samplingRate = thread->sampleRate();
6895 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6896 mConfig.inputCfg.bufferProvider.cookie = NULL;
6897 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6898 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6899 mConfig.outputCfg.bufferProvider.cookie = NULL;
6900 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6901 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6902 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6903 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006904 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006905 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006906 // - in other sessions:
6907 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6908 // other effect: overwrites output buffer: input buffer == output buffer
6909 // Auxiliary effect:
6910 // accumulates in output buffer: input buffer != output buffer
6911 // Therefore: accumulate <=> input buffer != output buffer
6912 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6913 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6914 } else {
6915 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6916 }
6917 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6918 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6919 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6920 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6921
Steve Block3856b092011-10-20 11:56:00 +01006922 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006923 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6924
Mathias Agopian65ab4712010-07-14 17:59:35 -07006925 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006926 uint32_t size = sizeof(int);
6927 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006928 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006929 sizeof(effect_config_t),
6930 &mConfig,
6931 &size,
6932 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006933 if (status == 0) {
6934 status = cmdStatus;
6935 }
6936
6937 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6938 (1000 * mConfig.outputCfg.buffer.frameCount);
6939
6940 return status;
6941}
6942
6943status_t AudioFlinger::EffectModule::init()
6944{
6945 Mutex::Autolock _l(mLock);
6946 if (mEffectInterface == NULL) {
6947 return NO_INIT;
6948 }
6949 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006950 uint32_t size = sizeof(status_t);
6951 status_t status = (*mEffectInterface)->command(mEffectInterface,
6952 EFFECT_CMD_INIT,
6953 0,
6954 NULL,
6955 &size,
6956 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006957 if (status == 0) {
6958 status = cmdStatus;
6959 }
6960 return status;
6961}
6962
Eric Laurentec35a142011-10-05 17:42:25 -07006963status_t AudioFlinger::EffectModule::start()
6964{
6965 Mutex::Autolock _l(mLock);
6966 return start_l();
6967}
6968
Mathias Agopian65ab4712010-07-14 17:59:35 -07006969status_t AudioFlinger::EffectModule::start_l()
6970{
6971 if (mEffectInterface == NULL) {
6972 return NO_INIT;
6973 }
6974 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006975 uint32_t size = sizeof(status_t);
6976 status_t status = (*mEffectInterface)->command(mEffectInterface,
6977 EFFECT_CMD_ENABLE,
6978 0,
6979 NULL,
6980 &size,
6981 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006982 if (status == 0) {
6983 status = cmdStatus;
6984 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006985 if (status == 0 &&
6986 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6987 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6988 sp<ThreadBase> thread = mThread.promote();
6989 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006990 audio_stream_t *stream = thread->stream();
6991 if (stream != NULL) {
6992 stream->add_audio_effect(stream, mEffectInterface);
6993 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006994 }
6995 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006996 return status;
6997}
6998
Eric Laurentec437d82011-07-26 20:54:46 -07006999status_t AudioFlinger::EffectModule::stop()
7000{
7001 Mutex::Autolock _l(mLock);
7002 return stop_l();
7003}
7004
Mathias Agopian65ab4712010-07-14 17:59:35 -07007005status_t AudioFlinger::EffectModule::stop_l()
7006{
7007 if (mEffectInterface == NULL) {
7008 return NO_INIT;
7009 }
7010 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007011 uint32_t size = sizeof(status_t);
7012 status_t status = (*mEffectInterface)->command(mEffectInterface,
7013 EFFECT_CMD_DISABLE,
7014 0,
7015 NULL,
7016 &size,
7017 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007018 if (status == 0) {
7019 status = cmdStatus;
7020 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007021 if (status == 0 &&
7022 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7023 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7024 sp<ThreadBase> thread = mThread.promote();
7025 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007026 audio_stream_t *stream = thread->stream();
7027 if (stream != NULL) {
7028 stream->remove_audio_effect(stream, mEffectInterface);
7029 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007030 }
7031 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007032 return status;
7033}
7034
Eric Laurent25f43952010-07-28 05:40:18 -07007035status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
7036 uint32_t cmdSize,
7037 void *pCmdData,
7038 uint32_t *replySize,
7039 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007040{
7041 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007042// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007043
Eric Laurentec437d82011-07-26 20:54:46 -07007044 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007045 return NO_INIT;
7046 }
Eric Laurent25f43952010-07-28 05:40:18 -07007047 status_t status = (*mEffectInterface)->command(mEffectInterface,
7048 cmdCode,
7049 cmdSize,
7050 pCmdData,
7051 replySize,
7052 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007053 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07007054 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007055 for (size_t i = 1; i < mHandles.size(); i++) {
7056 sp<EffectHandle> h = mHandles[i].promote();
7057 if (h != 0) {
7058 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
7059 }
7060 }
7061 }
7062 return status;
7063}
7064
7065status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
7066{
Eric Laurentdb7c0792011-08-10 10:37:50 -07007067
Mathias Agopian65ab4712010-07-14 17:59:35 -07007068 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007069 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007070
7071 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007072 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
7073 if (enabled && status != NO_ERROR) {
7074 return status;
7075 }
7076
Mathias Agopian65ab4712010-07-14 17:59:35 -07007077 switch (mState) {
7078 // going from disabled to enabled
7079 case IDLE:
7080 mState = STARTING;
7081 break;
7082 case STOPPED:
7083 mState = RESTART;
7084 break;
7085 case STOPPING:
7086 mState = ACTIVE;
7087 break;
7088
7089 // going from enabled to disabled
7090 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007091 mState = STOPPED;
7092 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007093 case STARTING:
7094 mState = IDLE;
7095 break;
7096 case ACTIVE:
7097 mState = STOPPING;
7098 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007099 case DESTROYED:
7100 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007101 }
7102 for (size_t i = 1; i < mHandles.size(); i++) {
7103 sp<EffectHandle> h = mHandles[i].promote();
7104 if (h != 0) {
7105 h->setEnabled(enabled);
7106 }
7107 }
7108 }
7109 return NO_ERROR;
7110}
7111
Glenn Kastenc59c0042012-02-02 14:06:11 -08007112bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007113{
7114 switch (mState) {
7115 case RESTART:
7116 case STARTING:
7117 case ACTIVE:
7118 return true;
7119 case IDLE:
7120 case STOPPING:
7121 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07007122 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07007123 default:
7124 return false;
7125 }
7126}
7127
Glenn Kastenc59c0042012-02-02 14:06:11 -08007128bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07007129{
7130 switch (mState) {
7131 case RESTART:
7132 case ACTIVE:
7133 case STOPPING:
7134 case STOPPED:
7135 return true;
7136 case IDLE:
7137 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07007138 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007139 default:
7140 return false;
7141 }
7142}
7143
Mathias Agopian65ab4712010-07-14 17:59:35 -07007144status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7145{
7146 Mutex::Autolock _l(mLock);
7147 status_t status = NO_ERROR;
7148
7149 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7150 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07007151 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07007152 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7153 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007154 status_t cmdStatus;
7155 uint32_t volume[2];
7156 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07007157 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007158 volume[0] = *left;
7159 volume[1] = *right;
7160 if (controller) {
7161 pVolume = volume;
7162 }
Eric Laurent25f43952010-07-28 05:40:18 -07007163 status = (*mEffectInterface)->command(mEffectInterface,
7164 EFFECT_CMD_SET_VOLUME,
7165 size,
7166 volume,
7167 &size,
7168 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007169 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7170 *left = volume[0];
7171 *right = volume[1];
7172 }
7173 }
7174 return status;
7175}
7176
7177status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7178{
7179 Mutex::Autolock _l(mLock);
7180 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007181 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7182 // audio pre processing modules on RecordThread can receive both output and
7183 // input device indication in the same call
7184 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7185 if (dev) {
7186 status_t cmdStatus;
7187 uint32_t size = sizeof(status_t);
7188
7189 status = (*mEffectInterface)->command(mEffectInterface,
7190 EFFECT_CMD_SET_DEVICE,
7191 sizeof(uint32_t),
7192 &dev,
7193 &size,
7194 &cmdStatus);
7195 if (status == NO_ERROR) {
7196 status = cmdStatus;
7197 }
7198 }
7199 dev = device & AUDIO_DEVICE_IN_ALL;
7200 if (dev) {
7201 status_t cmdStatus;
7202 uint32_t size = sizeof(status_t);
7203
7204 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7205 EFFECT_CMD_SET_INPUT_DEVICE,
7206 sizeof(uint32_t),
7207 &dev,
7208 &size,
7209 &cmdStatus);
7210 if (status2 == NO_ERROR) {
7211 status2 = cmdStatus;
7212 }
7213 if (status == NO_ERROR) {
7214 status = status2;
7215 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007216 }
7217 }
7218 return status;
7219}
7220
Glenn Kastenf78aee72012-01-04 11:00:47 -08007221status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007222{
7223 Mutex::Autolock _l(mLock);
7224 status_t status = NO_ERROR;
7225 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007226 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007227 uint32_t size = sizeof(status_t);
7228 status = (*mEffectInterface)->command(mEffectInterface,
7229 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08007230 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07007231 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07007232 &size,
7233 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007234 if (status == NO_ERROR) {
7235 status = cmdStatus;
7236 }
7237 }
7238 return status;
7239}
7240
Eric Laurent59255e42011-07-27 19:49:51 -07007241void AudioFlinger::EffectModule::setSuspended(bool suspended)
7242{
7243 Mutex::Autolock _l(mLock);
7244 mSuspended = suspended;
7245}
Glenn Kastena3a85482012-01-04 11:01:11 -08007246
7247bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07007248{
7249 Mutex::Autolock _l(mLock);
7250 return mSuspended;
7251}
7252
Mathias Agopian65ab4712010-07-14 17:59:35 -07007253status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7254{
7255 const size_t SIZE = 256;
7256 char buffer[SIZE];
7257 String8 result;
7258
7259 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7260 result.append(buffer);
7261
7262 bool locked = tryLock(mLock);
7263 // failed to lock - AudioFlinger is probably deadlocked
7264 if (!locked) {
7265 result.append("\t\tCould not lock Fx mutex:\n");
7266 }
7267
7268 result.append("\t\tSession Status State Engine:\n");
7269 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7270 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7271 result.append(buffer);
7272
7273 result.append("\t\tDescriptor:\n");
7274 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7275 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7276 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7277 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7278 result.append(buffer);
7279 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7280 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7281 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7282 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7283 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07007284 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007285 mDescriptor.apiVersion,
7286 mDescriptor.flags);
7287 result.append(buffer);
7288 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7289 mDescriptor.name);
7290 result.append(buffer);
7291 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7292 mDescriptor.implementor);
7293 result.append(buffer);
7294
7295 result.append("\t\t- Input configuration:\n");
7296 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7297 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7298 (uint32_t)mConfig.inputCfg.buffer.raw,
7299 mConfig.inputCfg.buffer.frameCount,
7300 mConfig.inputCfg.samplingRate,
7301 mConfig.inputCfg.channels,
7302 mConfig.inputCfg.format);
7303 result.append(buffer);
7304
7305 result.append("\t\t- Output configuration:\n");
7306 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7307 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7308 (uint32_t)mConfig.outputCfg.buffer.raw,
7309 mConfig.outputCfg.buffer.frameCount,
7310 mConfig.outputCfg.samplingRate,
7311 mConfig.outputCfg.channels,
7312 mConfig.outputCfg.format);
7313 result.append(buffer);
7314
7315 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7316 result.append(buffer);
7317 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7318 for (size_t i = 0; i < mHandles.size(); ++i) {
7319 sp<EffectHandle> handle = mHandles[i].promote();
7320 if (handle != 0) {
7321 handle->dump(buffer, SIZE);
7322 result.append(buffer);
7323 }
7324 }
7325
7326 result.append("\n");
7327
7328 write(fd, result.string(), result.length());
7329
7330 if (locked) {
7331 mLock.unlock();
7332 }
7333
7334 return NO_ERROR;
7335}
7336
7337// ----------------------------------------------------------------------------
7338// EffectHandle implementation
7339// ----------------------------------------------------------------------------
7340
7341#undef LOG_TAG
7342#define LOG_TAG "AudioFlinger::EffectHandle"
7343
7344AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7345 const sp<AudioFlinger::Client>& client,
7346 const sp<IEffectClient>& effectClient,
7347 int32_t priority)
7348 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007349 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007350 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007351{
Steve Block3856b092011-10-20 11:56:00 +01007352 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007353
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007354 if (client == 0) {
7355 return;
7356 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007357 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7358 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7359 if (mCblkMemory != 0) {
7360 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7361
Glenn Kastena0d68332012-01-27 16:47:15 -08007362 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007363 new(mCblk) effect_param_cblk_t();
7364 mBuffer = (uint8_t *)mCblk + bufOffset;
7365 }
7366 } else {
Steve Block29357bc2012-01-06 19:20:56 +00007367 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007368 return;
7369 }
7370}
7371
7372AudioFlinger::EffectHandle::~EffectHandle()
7373{
Steve Block3856b092011-10-20 11:56:00 +01007374 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007375 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01007376 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007377}
7378
7379status_t AudioFlinger::EffectHandle::enable()
7380{
Steve Block3856b092011-10-20 11:56:00 +01007381 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007382 if (!mHasControl) return INVALID_OPERATION;
7383 if (mEffect == 0) return DEAD_OBJECT;
7384
Eric Laurentdb7c0792011-08-10 10:37:50 -07007385 if (mEnabled) {
7386 return NO_ERROR;
7387 }
7388
Eric Laurent59255e42011-07-27 19:49:51 -07007389 mEnabled = true;
7390
7391 sp<ThreadBase> thread = mEffect->thread().promote();
7392 if (thread != 0) {
7393 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7394 }
7395
7396 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7397 if (mEffect->suspended()) {
7398 return NO_ERROR;
7399 }
7400
Eric Laurentdb7c0792011-08-10 10:37:50 -07007401 status_t status = mEffect->setEnabled(true);
7402 if (status != NO_ERROR) {
7403 if (thread != 0) {
7404 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7405 }
7406 mEnabled = false;
7407 }
7408 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007409}
7410
7411status_t AudioFlinger::EffectHandle::disable()
7412{
Steve Block3856b092011-10-20 11:56:00 +01007413 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007414 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07007415 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007416
Eric Laurentdb7c0792011-08-10 10:37:50 -07007417 if (!mEnabled) {
7418 return NO_ERROR;
7419 }
Eric Laurent59255e42011-07-27 19:49:51 -07007420 mEnabled = false;
7421
7422 if (mEffect->suspended()) {
7423 return NO_ERROR;
7424 }
7425
7426 status_t status = mEffect->setEnabled(false);
7427
7428 sp<ThreadBase> thread = mEffect->thread().promote();
7429 if (thread != 0) {
7430 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7431 }
7432
7433 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007434}
7435
7436void AudioFlinger::EffectHandle::disconnect()
7437{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007438 disconnect(true);
7439}
7440
Glenn Kasten58123c32012-02-03 10:32:24 -08007441void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007442{
Glenn Kasten58123c32012-02-03 10:32:24 -08007443 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007444 if (mEffect == 0) {
7445 return;
7446 }
Glenn Kasten58123c32012-02-03 10:32:24 -08007447 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07007448
Eric Laurenta85a74a2011-10-19 11:44:54 -07007449 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007450 sp<ThreadBase> thread = mEffect->thread().promote();
7451 if (thread != 0) {
7452 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7453 }
Eric Laurent59255e42011-07-27 19:49:51 -07007454 }
7455
Mathias Agopian65ab4712010-07-14 17:59:35 -07007456 // release sp on module => module destructor can be called now
7457 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007458 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08007459 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08007460 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007461 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7462 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08007463 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007464 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07007465 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7466 mClient.clear();
7467 }
7468}
7469
Eric Laurent25f43952010-07-28 05:40:18 -07007470status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7471 uint32_t cmdSize,
7472 void *pCmdData,
7473 uint32_t *replySize,
7474 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007475{
Steve Block3856b092011-10-20 11:56:00 +01007476// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07007477// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007478
7479 // only get parameter command is permitted for applications not controlling the effect
7480 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7481 return INVALID_OPERATION;
7482 }
7483 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007484 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007485
7486 // handle commands that are not forwarded transparently to effect engine
7487 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7488 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7489 // no risk to block the whole media server process or mixer threads is we are stuck here
7490 Mutex::Autolock _l(mCblk->lock);
7491 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7492 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7493 mCblk->serverIndex = 0;
7494 mCblk->clientIndex = 0;
7495 return BAD_VALUE;
7496 }
7497 status_t status = NO_ERROR;
7498 while (mCblk->serverIndex < mCblk->clientIndex) {
7499 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007500 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007501 int *p = (int *)(mBuffer + mCblk->serverIndex);
7502 int size = *p++;
7503 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007504 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007505 break;
7506 }
7507 effect_param_t *param = (effect_param_t *)p;
7508 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007509 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007510 mCblk->serverIndex += size;
7511 continue;
7512 }
Eric Laurent25f43952010-07-28 05:40:18 -07007513 uint32_t psize = sizeof(effect_param_t) +
7514 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7515 param->vsize;
7516 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7517 psize,
7518 p,
7519 &rsize,
7520 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007521 // stop at first error encountered
7522 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007523 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007524 *(int *)pReplyData = reply;
7525 break;
7526 } else if (reply != NO_ERROR) {
7527 *(int *)pReplyData = reply;
7528 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007529 }
7530 mCblk->serverIndex += size;
7531 }
7532 mCblk->serverIndex = 0;
7533 mCblk->clientIndex = 0;
7534 return status;
7535 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007536 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007537 return enable();
7538 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007539 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007540 return disable();
7541 }
7542
7543 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7544}
7545
Eric Laurent59255e42011-07-27 19:49:51 -07007546void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007547{
Steve Block3856b092011-10-20 11:56:00 +01007548 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007549
7550 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007551 mEnabled = enabled;
7552
Mathias Agopian65ab4712010-07-14 17:59:35 -07007553 if (signal && mEffectClient != 0) {
7554 mEffectClient->controlStatusChanged(hasControl);
7555 }
7556}
7557
Eric Laurent25f43952010-07-28 05:40:18 -07007558void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7559 uint32_t cmdSize,
7560 void *pCmdData,
7561 uint32_t replySize,
7562 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007563{
7564 if (mEffectClient != 0) {
7565 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7566 }
7567}
7568
7569
7570
7571void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7572{
7573 if (mEffectClient != 0) {
7574 mEffectClient->enableStatusChanged(enabled);
7575 }
7576}
7577
7578status_t AudioFlinger::EffectHandle::onTransact(
7579 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7580{
7581 return BnEffect::onTransact(code, data, reply, flags);
7582}
7583
7584
7585void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7586{
Glenn Kastena0d68332012-01-27 16:47:15 -08007587 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007588
7589 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08007590 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007591 mPriority,
7592 mHasControl,
7593 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007594 mCblk ? mCblk->clientIndex : 0,
7595 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007596 );
7597
7598 if (locked) {
7599 mCblk->lock.unlock();
7600 }
7601}
7602
7603#undef LOG_TAG
7604#define LOG_TAG "AudioFlinger::EffectChain"
7605
7606AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7607 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007608 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007609 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7610 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007611{
Dima Zavinfce7a472011-04-19 22:30:36 -07007612 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007613 sp<ThreadBase> thread = mThread.promote();
7614 if (thread == 0) {
7615 return;
7616 }
7617 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7618 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007619}
7620
7621AudioFlinger::EffectChain::~EffectChain()
7622{
7623 if (mOwnInBuffer) {
7624 delete mInBuffer;
7625 }
7626
7627}
7628
Eric Laurent59255e42011-07-27 19:49:51 -07007629// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007630sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007631{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007632 size_t size = mEffects.size();
7633
7634 for (size_t i = 0; i < size; i++) {
7635 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007636 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007637 }
7638 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007639 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007640}
7641
Eric Laurent59255e42011-07-27 19:49:51 -07007642// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007643sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007644{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007645 size_t size = mEffects.size();
7646
7647 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007648 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7649 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007650 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007651 }
7652 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007653 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007654}
7655
Eric Laurent59255e42011-07-27 19:49:51 -07007656// getEffectFromType_l() must be called with ThreadBase::mLock held
7657sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7658 const effect_uuid_t *type)
7659{
Eric Laurent59255e42011-07-27 19:49:51 -07007660 size_t size = mEffects.size();
7661
7662 for (size_t i = 0; i < size; i++) {
7663 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007664 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007665 }
7666 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007667 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007668}
7669
Mathias Agopian65ab4712010-07-14 17:59:35 -07007670// Must be called with EffectChain::mLock locked
7671void AudioFlinger::EffectChain::process_l()
7672{
Eric Laurentdac69112010-09-28 14:09:57 -07007673 sp<ThreadBase> thread = mThread.promote();
7674 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007675 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007676 return;
7677 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007678 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7679 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007680 // always process effects unless no more tracks are on the session and the effect tail
7681 // has been rendered
7682 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007683 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007684 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007685
Eric Laurent544fe9b2011-11-11 15:42:52 -08007686 if (!tracksOnSession && mTailBufferCount == 0) {
7687 doProcess = false;
7688 }
7689
7690 if (activeTrackCnt() == 0) {
7691 // if no track is active and the effect tail has not been rendered,
7692 // the input buffer must be cleared here as the mixer process will not do it
7693 if (tracksOnSession || mTailBufferCount > 0) {
7694 size_t numSamples = thread->frameCount() * thread->channelCount();
7695 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7696 if (mTailBufferCount > 0) {
7697 mTailBufferCount--;
7698 }
7699 }
7700 }
Eric Laurentdac69112010-09-28 14:09:57 -07007701 }
7702
Mathias Agopian65ab4712010-07-14 17:59:35 -07007703 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007704 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007705 for (size_t i = 0; i < size; i++) {
7706 mEffects[i]->process();
7707 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007708 }
7709 for (size_t i = 0; i < size; i++) {
7710 mEffects[i]->updateState();
7711 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007712}
7713
Eric Laurentcab11242010-07-15 12:50:15 -07007714// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007715status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007716{
7717 effect_descriptor_t desc = effect->desc();
7718 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7719
7720 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007721 effect->setChain(this);
7722 sp<ThreadBase> thread = mThread.promote();
7723 if (thread == 0) {
7724 return NO_INIT;
7725 }
7726 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007727
7728 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7729 // Auxiliary effects are inserted at the beginning of mEffects vector as
7730 // they are processed first and accumulated in chain input buffer
7731 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007732
Mathias Agopian65ab4712010-07-14 17:59:35 -07007733 // the input buffer for auxiliary effect contains mono samples in
7734 // 32 bit format. This is to avoid saturation in AudoMixer
7735 // accumulation stage. Saturation is done in EffectModule::process() before
7736 // calling the process in effect engine
7737 size_t numSamples = thread->frameCount();
7738 int32_t *buffer = new int32_t[numSamples];
7739 memset(buffer, 0, numSamples * sizeof(int32_t));
7740 effect->setInBuffer((int16_t *)buffer);
7741 // auxiliary effects output samples to chain input buffer for further processing
7742 // by insert effects
7743 effect->setOutBuffer(mInBuffer);
7744 } else {
7745 // Insert effects are inserted at the end of mEffects vector as they are processed
7746 // after track and auxiliary effects.
7747 // Insert effect order as a function of indicated preference:
7748 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7749 // another effect is present
7750 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7751 // last effect claiming first position
7752 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7753 // first effect claiming last position
7754 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7755 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7756 // already present
7757
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007758 size_t size = mEffects.size();
7759 size_t idx_insert = size;
7760 ssize_t idx_insert_first = -1;
7761 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007762
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007763 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007764 effect_descriptor_t d = mEffects[i]->desc();
7765 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7766 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7767 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7768 // check invalid effect chaining combinations
7769 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7770 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007771 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007772 return INVALID_OPERATION;
7773 }
7774 // remember position of first insert effect and by default
7775 // select this as insert position for new effect
7776 if (idx_insert == size) {
7777 idx_insert = i;
7778 }
7779 // remember position of last insert effect claiming
7780 // first position
7781 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7782 idx_insert_first = i;
7783 }
7784 // remember position of first insert effect claiming
7785 // last position
7786 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7787 idx_insert_last == -1) {
7788 idx_insert_last = i;
7789 }
7790 }
7791 }
7792
7793 // modify idx_insert from first position if needed
7794 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7795 if (idx_insert_last != -1) {
7796 idx_insert = idx_insert_last;
7797 } else {
7798 idx_insert = size;
7799 }
7800 } else {
7801 if (idx_insert_first != -1) {
7802 idx_insert = idx_insert_first + 1;
7803 }
7804 }
7805
7806 // always read samples from chain input buffer
7807 effect->setInBuffer(mInBuffer);
7808
7809 // if last effect in the chain, output samples to chain
7810 // output buffer, otherwise to chain input buffer
7811 if (idx_insert == size) {
7812 if (idx_insert != 0) {
7813 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7814 mEffects[idx_insert-1]->configure();
7815 }
7816 effect->setOutBuffer(mOutBuffer);
7817 } else {
7818 effect->setOutBuffer(mInBuffer);
7819 }
7820 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007821
Steve Block3856b092011-10-20 11:56:00 +01007822 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007823 }
7824 effect->configure();
7825 return NO_ERROR;
7826}
7827
Eric Laurentcab11242010-07-15 12:50:15 -07007828// removeEffect_l() must be called with PlaybackThread::mLock held
7829size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007830{
7831 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007832 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007833 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7834
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007835 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007836 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007837 // calling stop here will remove pre-processing effect from the audio HAL.
7838 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7839 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007840 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7841 mEffects[i]->state() == EffectModule::STOPPING) {
7842 mEffects[i]->stop();
7843 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007844 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7845 delete[] effect->inBuffer();
7846 } else {
7847 if (i == size - 1 && i != 0) {
7848 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7849 mEffects[i - 1]->configure();
7850 }
7851 }
7852 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007853 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007854 break;
7855 }
7856 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007857
7858 return mEffects.size();
7859}
7860
Eric Laurentcab11242010-07-15 12:50:15 -07007861// setDevice_l() must be called with PlaybackThread::mLock held
7862void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007863{
7864 size_t size = mEffects.size();
7865 for (size_t i = 0; i < size; i++) {
7866 mEffects[i]->setDevice(device);
7867 }
7868}
7869
Eric Laurentcab11242010-07-15 12:50:15 -07007870// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007871void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007872{
7873 size_t size = mEffects.size();
7874 for (size_t i = 0; i < size; i++) {
7875 mEffects[i]->setMode(mode);
7876 }
7877}
7878
Eric Laurentcab11242010-07-15 12:50:15 -07007879// setVolume_l() must be called with PlaybackThread::mLock held
7880bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007881{
7882 uint32_t newLeft = *left;
7883 uint32_t newRight = *right;
7884 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007885 int ctrlIdx = -1;
7886 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007887
Eric Laurentcab11242010-07-15 12:50:15 -07007888 // first update volume controller
7889 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007890 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007891 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7892 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007893 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007894 break;
7895 }
7896 }
7897
7898 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007899 if (hasControl) {
7900 *left = mNewLeftVolume;
7901 *right = mNewRightVolume;
7902 }
7903 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007904 }
7905
7906 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007907 mLeftVolume = newLeft;
7908 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007909
7910 // second get volume update from volume controller
7911 if (ctrlIdx >= 0) {
7912 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007913 mNewLeftVolume = newLeft;
7914 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007915 }
7916 // then indicate volume to all other effects in chain.
7917 // Pass altered volume to effects before volume controller
7918 // and requested volume to effects after controller
7919 uint32_t lVol = newLeft;
7920 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007921
Mathias Agopian65ab4712010-07-14 17:59:35 -07007922 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007923 if ((int)i == ctrlIdx) continue;
7924 // this also works for ctrlIdx == -1 when there is no volume controller
7925 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007926 lVol = *left;
7927 rVol = *right;
7928 }
7929 mEffects[i]->setVolume(&lVol, &rVol, false);
7930 }
7931 *left = newLeft;
7932 *right = newRight;
7933
7934 return hasControl;
7935}
7936
Mathias Agopian65ab4712010-07-14 17:59:35 -07007937status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7938{
7939 const size_t SIZE = 256;
7940 char buffer[SIZE];
7941 String8 result;
7942
7943 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7944 result.append(buffer);
7945
7946 bool locked = tryLock(mLock);
7947 // failed to lock - AudioFlinger is probably deadlocked
7948 if (!locked) {
7949 result.append("\tCould not lock mutex:\n");
7950 }
7951
Eric Laurentcab11242010-07-15 12:50:15 -07007952 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7953 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007954 mEffects.size(),
7955 (uint32_t)mInBuffer,
7956 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007957 mActiveTrackCnt);
7958 result.append(buffer);
7959 write(fd, result.string(), result.size());
7960
7961 for (size_t i = 0; i < mEffects.size(); ++i) {
7962 sp<EffectModule> effect = mEffects[i];
7963 if (effect != 0) {
7964 effect->dump(fd, args);
7965 }
7966 }
7967
7968 if (locked) {
7969 mLock.unlock();
7970 }
7971
7972 return NO_ERROR;
7973}
7974
Eric Laurent59255e42011-07-27 19:49:51 -07007975// must be called with ThreadBase::mLock held
7976void AudioFlinger::EffectChain::setEffectSuspended_l(
7977 const effect_uuid_t *type, bool suspend)
7978{
7979 sp<SuspendedEffectDesc> desc;
7980 // use effect type UUID timelow as key as there is no real risk of identical
7981 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007982 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007983 if (suspend) {
7984 if (index >= 0) {
7985 desc = mSuspendedEffects.valueAt(index);
7986 } else {
7987 desc = new SuspendedEffectDesc();
7988 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7989 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007990 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007991 }
7992 if (desc->mRefCount++ == 0) {
7993 sp<EffectModule> effect = getEffectIfEnabled(type);
7994 if (effect != 0) {
7995 desc->mEffect = effect;
7996 effect->setSuspended(true);
7997 effect->setEnabled(false);
7998 }
7999 }
8000 } else {
8001 if (index < 0) {
8002 return;
8003 }
8004 desc = mSuspendedEffects.valueAt(index);
8005 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008006 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008007 desc->mRefCount = 1;
8008 }
8009 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01008010 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008011 if (desc->mEffect != 0) {
8012 sp<EffectModule> effect = desc->mEffect.promote();
8013 if (effect != 0) {
8014 effect->setSuspended(false);
8015 sp<EffectHandle> handle = effect->controlHandle();
8016 if (handle != 0) {
8017 effect->setEnabled(handle->enabled());
8018 }
8019 }
8020 desc->mEffect.clear();
8021 }
8022 mSuspendedEffects.removeItemsAt(index);
8023 }
8024 }
8025}
8026
8027// must be called with ThreadBase::mLock held
8028void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
8029{
8030 sp<SuspendedEffectDesc> desc;
8031
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008032 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07008033 if (suspend) {
8034 if (index >= 0) {
8035 desc = mSuspendedEffects.valueAt(index);
8036 } else {
8037 desc = new SuspendedEffectDesc();
8038 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01008039 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07008040 }
8041 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08008042 Vector< sp<EffectModule> > effects;
8043 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07008044 for (size_t i = 0; i < effects.size(); i++) {
8045 setEffectSuspended_l(&effects[i]->desc().type, true);
8046 }
8047 }
8048 } else {
8049 if (index < 0) {
8050 return;
8051 }
8052 desc = mSuspendedEffects.valueAt(index);
8053 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008054 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008055 desc->mRefCount = 1;
8056 }
8057 if (--desc->mRefCount == 0) {
8058 Vector<const effect_uuid_t *> types;
8059 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
8060 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
8061 continue;
8062 }
8063 types.add(&mSuspendedEffects.valueAt(i)->mType);
8064 }
8065 for (size_t i = 0; i < types.size(); i++) {
8066 setEffectSuspended_l(types[i], false);
8067 }
Steve Block3856b092011-10-20 11:56:00 +01008068 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008069 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
8070 }
8071 }
8072}
8073
Eric Laurent6bffdb82011-09-23 08:40:41 -07008074
8075// The volume effect is used for automated tests only
8076#ifndef OPENSL_ES_H_
8077static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
8078 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
8079const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
8080#endif //OPENSL_ES_H_
8081
Eric Laurentdb7c0792011-08-10 10:37:50 -07008082bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
8083{
8084 // auxiliary effects and visualizer are never suspended on output mix
8085 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8086 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07008087 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8088 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008089 return false;
8090 }
8091 return true;
8092}
8093
Glenn Kastend0539712012-01-30 12:56:03 -08008094void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07008095{
Glenn Kastend0539712012-01-30 12:56:03 -08008096 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07008097 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08008098 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8099 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07008100 }
Eric Laurent59255e42011-07-27 19:49:51 -07008101 }
Eric Laurent59255e42011-07-27 19:49:51 -07008102}
8103
8104sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8105 const effect_uuid_t *type)
8106{
Glenn Kasten090f0192012-01-30 13:00:02 -08008107 sp<EffectModule> effect = getEffectFromType_l(type);
8108 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008109}
8110
8111void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8112 bool enabled)
8113{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008114 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008115 if (enabled) {
8116 if (index < 0) {
8117 // if the effect is not suspend check if all effects are suspended
8118 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8119 if (index < 0) {
8120 return;
8121 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07008122 if (!isEffectEligibleForSuspend(effect->desc())) {
8123 return;
8124 }
Eric Laurent59255e42011-07-27 19:49:51 -07008125 setEffectSuspended_l(&effect->desc().type, enabled);
8126 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07008127 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008128 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07008129 return;
8130 }
Eric Laurent59255e42011-07-27 19:49:51 -07008131 }
Steve Block3856b092011-10-20 11:56:00 +01008132 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07008133 effect->desc().type.timeLow);
8134 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8135 // if effect is requested to suspended but was not yet enabled, supend it now.
8136 if (desc->mEffect == 0) {
8137 desc->mEffect = effect;
8138 effect->setEnabled(false);
8139 effect->setSuspended(true);
8140 }
8141 } else {
8142 if (index < 0) {
8143 return;
8144 }
Steve Block3856b092011-10-20 11:56:00 +01008145 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07008146 effect->desc().type.timeLow);
8147 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8148 desc->mEffect.clear();
8149 effect->setSuspended(false);
8150 }
8151}
8152
Mathias Agopian65ab4712010-07-14 17:59:35 -07008153#undef LOG_TAG
8154#define LOG_TAG "AudioFlinger"
8155
8156// ----------------------------------------------------------------------------
8157
8158status_t AudioFlinger::onTransact(
8159 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8160{
8161 return BnAudioFlinger::onTransact(code, data, reply, flags);
8162}
8163
Mathias Agopian65ab4712010-07-14 17:59:35 -07008164}; // namespace android