blob: 7627dabeb724f8473b2c8f6ec99935ce4a31cbbe [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;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001938 nsecs_t standbyTime = systemTime();
1939 size_t mixBufferSize = mFrameCount * mFrameSize;
1940 // FIXME: Relaxed timing because of a certain device that can't meet latency
1941 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001942 // increase threshold again due to low power audio mode. The way this warning threshold is
1943 // calculated and its usefulness should be reconsidered anyway.
1944 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001945 nsecs_t lastWarning = 0;
1946 bool longStandbyExit = false;
1947 uint32_t activeSleepTime = activeSleepTimeUs();
1948 uint32_t idleSleepTime = idleSleepTimeUs();
1949 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001950 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001951 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001952#ifdef DEBUG_CPU_USAGE
1953 ThreadCpuUsage cpu;
1954 const CentralTendencyStatistics& stats = cpu.statistics();
1955#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001956
Eric Laurentfeb0db62011-07-22 09:04:31 -07001957 acquireWakeLock();
1958
Mathias Agopian65ab4712010-07-14 17:59:35 -07001959 while (!exitPending())
1960 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001961#ifdef DEBUG_CPU_USAGE
1962 cpu.sampleAndEnable();
1963 unsigned n = stats.n();
1964 // cpu.elapsed() is expensive, so don't call it every loop
1965 if ((n & 127) == 1) {
1966 long long elapsed = cpu.elapsed();
1967 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1968 double perLoop = elapsed / (double) n;
1969 double perLoop100 = perLoop * 0.01;
1970 double mean = stats.mean();
1971 double stddev = stats.stddev();
1972 double minimum = stats.minimum();
1973 double maximum = stats.maximum();
1974 cpu.resetStatistics();
Steve Blockdf64d152012-01-04 20:05:49 +00001975 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 -07001976 elapsed * .000000001, n, perLoop * .000001,
1977 mean * .001,
1978 stddev * .001,
1979 minimum * .001,
1980 maximum * .001,
1981 mean / perLoop100,
1982 stddev / perLoop100,
1983 minimum / perLoop100,
1984 maximum / perLoop100);
1985 }
1986 }
1987#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988 processConfigEvents();
1989
Glenn Kasten5d4eeea2012-02-24 07:25:40 -08001990 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001991 { // scope for mLock
1992
1993 Mutex::Autolock _l(mLock);
1994
1995 if (checkForNewParameters_l()) {
1996 mixBufferSize = mFrameCount * mFrameSize;
1997 // FIXME: Relaxed timing because of a certain device that can't meet latency
1998 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001999 // increase threshold again due to low power audio mode. The way this warning
2000 // threshold is calculated and its usefulness should be reconsidered anyway.
2001 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002002 activeSleepTime = activeSleepTimeUs();
2003 idleSleepTime = idleSleepTimeUs();
2004 }
2005
2006 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2007
2008 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002009 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2010 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002011 if (!mStandby) {
Glenn Kasten90bebef2012-01-27 15:24:38 -08002012 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07002013 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002014 mStandby = true;
2015 mBytesWritten = 0;
2016 }
2017
2018 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2019 // we're about to wait, flush the binder command buffer
2020 IPCThreadState::self()->flushCommands();
2021
2022 if (exitPending()) break;
2023
Eric Laurentfeb0db62011-07-22 09:04:31 -07002024 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002025 // wait until we have something to do...
Glenn Kasten90bebef2012-01-27 15:24:38 -08002026 ALOGV("MixerThread %p TID %d going to sleep", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002027 mWaitWorkCV.wait(mLock);
Glenn Kasten90bebef2012-01-27 15:24:38 -08002028 ALOGV("MixerThread %p TID %d waking up", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002029 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002030
Eric Laurent27741442012-01-17 19:20:12 -08002031 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08002032 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002033 char value[PROPERTY_VALUE_MAX];
2034 property_get("ro.audio.silent", value, "0");
2035 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002036 ALOGD("Silence is golden");
Glenn Kasten6637baa2012-01-09 09:40:36 -08002037 setMasterMute_l(true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002038 }
2039 }
2040
John Grossman4ff14ba2012-02-08 16:37:41 -08002041 standbyTime = systemTime() + mStandbyTimeInNsecs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002042 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08002043 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002044 continue;
2045 }
2046 }
2047
2048 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
2049
2050 // prevent any changes in effect chain list and in each effect chain
2051 // during mixing and effect process as the audio buffers could be deleted
2052 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002053 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002054 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002055
Glenn Kastenf6b16782011-12-15 09:51:17 -08002056 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08002057 // obtain the presentation timestamp of the next output buffer
2058 int64_t pts;
2059 status_t status = INVALID_OPERATION;
2060
2061 if (NULL != mOutput->stream->get_next_write_timestamp) {
2062 status = mOutput->stream->get_next_write_timestamp(
2063 mOutput->stream, &pts);
2064 }
2065
2066 if (status != NO_ERROR) {
2067 pts = AudioBufferProvider::kInvalidPTS;
2068 }
2069
Mathias Agopian65ab4712010-07-14 17:59:35 -07002070 // mix buffers...
John Grossman4ff14ba2012-02-08 16:37:41 -08002071 mAudioMixer->process(pts);
Eric Laurent21e4b6e2012-01-23 18:56:59 -08002072 // increase sleep time progressively when application underrun condition clears.
2073 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2074 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2075 // such that we would underrun the audio HAL.
2076 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08002077 sleepTimeShift--;
2078 }
Eric Laurent21e4b6e2012-01-23 18:56:59 -08002079 sleepTime = 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08002080 standbyTime = systemTime() + mStandbyTimeInNsecs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002081 //TODO: delay standby when effects have a tail
2082 } else {
2083 // If no tracks are ready, sleep once for the duration of an output
2084 // buffer size, then write 0s to the output
2085 if (sleepTime == 0) {
2086 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08002087 sleepTime = activeSleepTime >> sleepTimeShift;
2088 if (sleepTime < kMinThreadSleepTimeUs) {
2089 sleepTime = kMinThreadSleepTimeUs;
2090 }
2091 // reduce sleep time in case of consecutive application underruns to avoid
2092 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2093 // duration we would end up writing less data than needed by the audio HAL if
2094 // the condition persists.
2095 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2096 sleepTimeShift++;
2097 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002098 } else {
2099 sleepTime = idleSleepTime;
2100 }
2101 } else if (mBytesWritten != 0 ||
2102 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2103 memset (mMixBuffer, 0, mixBufferSize);
2104 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01002105 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002106 }
2107 // TODO add standby time extension fct of effect tail
2108 }
2109
2110 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002111 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002112 }
2113 // sleepTime == 0 means we must write to audio hardware
2114 if (sleepTime == 0) {
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002115 for (size_t i = 0; i < effectChains.size(); i ++) {
2116 effectChains[i]->process_l();
2117 }
2118 // enable changes in effect chain
2119 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002120 mLastWriteTime = systemTime();
2121 mInWrite = true;
2122 mBytesWritten += mixBufferSize;
2123
Dima Zavin799a70e2011-04-18 16:57:27 -07002124 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002125 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2126 mNumWrites++;
2127 mInWrite = false;
2128 nsecs_t now = systemTime();
2129 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002130 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002131 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002132 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002133 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002134 ns2ms(delta), mNumDelayedWrites, this);
2135 lastWarning = now;
2136 }
2137 if (mStandby) {
2138 longStandbyExit = true;
2139 }
2140 }
2141 mStandby = false;
2142 } else {
2143 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002144 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002145 usleep(sleepTime);
2146 }
2147
2148 // finally let go of all our tracks, without the lock held
2149 // since we can't guarantee the destructors won't acquire that
2150 // same lock.
2151 tracksToRemove.clear();
2152
2153 // Effect chains will be actually deleted here if they were removed from
2154 // mEffectChains list during mixing or effects processing
2155 effectChains.clear();
2156 }
2157
2158 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002159 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002160 }
2161
Eric Laurentfeb0db62011-07-22 09:04:31 -07002162 releaseWakeLock();
2163
Steve Block3856b092011-10-20 11:56:00 +01002164 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002165 return false;
2166}
2167
2168// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002169AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2170 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002171{
2172
Glenn Kasten29c23c32012-01-26 13:37:52 -08002173 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002174 // find out which tracks need to be processed
2175 size_t count = activeTracks.size();
2176 size_t mixedTracks = 0;
2177 size_t tracksWithEffect = 0;
2178
2179 float masterVolume = mMasterVolume;
2180 bool masterMute = mMasterMute;
2181
Eric Laurent571d49c2010-08-11 05:20:11 -07002182 if (masterMute) {
2183 masterVolume = 0;
2184 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002185 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002186 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002187 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002188 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002189 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002190 masterVolume = (float)((v + (1 << 23)) >> 24);
2191 chain.clear();
2192 }
2193
2194 for (size_t i=0 ; i<count ; i++) {
2195 sp<Track> t = activeTracks[i].promote();
2196 if (t == 0) continue;
2197
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002198 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002199 Track* const track = t.get();
2200 audio_track_cblk_t* cblk = track->cblk();
2201
2202 // The first time a track is added we wait
2203 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002204 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002205 // make sure that we have enough frames to mix one full buffer.
2206 // enforce this condition only once to enable draining the buffer in case the client
2207 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002208 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002209 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002210 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002211 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002212 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002213 if (t->sampleRate() == (int)mSampleRate) {
2214 minFrames = mFrameCount;
2215 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002216 // +1 for rounding and +1 for additional sample needed for interpolation
2217 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2218 // add frames already consumed but not yet released by the resampler
2219 // because cblk->framesReady() will include these frames
2220 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2221 // the minimum track buffer size is normally twice the number of frames necessary
2222 // to fill one buffer and the resampler should not leave more than one buffer worth
2223 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002224 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002225 }
2226 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002227 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002228 !track->isPaused() && !track->isTerminated())
2229 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002230 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002231
2232 mixedTracks++;
2233
2234 // track->mainBuffer() != mMixBuffer means there is an effect chain
2235 // connected to the track
2236 chain.clear();
2237 if (track->mainBuffer() != mMixBuffer) {
2238 chain = getEffectChain_l(track->sessionId());
2239 // Delegate volume control to effect in track effect chain if needed
2240 if (chain != 0) {
2241 tracksWithEffect++;
2242 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002243 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002244 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002245 }
2246 }
2247
2248
2249 int param = AudioMixer::VOLUME;
2250 if (track->mFillingUpStatus == Track::FS_FILLED) {
2251 // no ramp for the first volume setting
2252 track->mFillingUpStatus = Track::FS_ACTIVE;
2253 if (track->mState == TrackBase::RESUMING) {
2254 track->mState = TrackBase::ACTIVE;
2255 param = AudioMixer::RAMP_VOLUME;
2256 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002257 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002258 } else if (cblk->server != 0) {
2259 // If the track is stopped before the first frame was mixed,
2260 // do not apply ramp
2261 param = AudioMixer::RAMP_VOLUME;
2262 }
2263
2264 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002265 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002266 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002267 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002268 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002269 if (track->isPausing()) {
2270 track->setPaused();
2271 }
2272 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002273
Mathias Agopian65ab4712010-07-14 17:59:35 -07002274 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002275 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002276 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002277 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002278 vl = vlr & 0xFFFF;
2279 vr = vlr >> 16;
2280 // track volumes come from shared memory, so can't be trusted and must be clamped
2281 if (vl > MAX_GAIN_INT) {
2282 ALOGV("Track left volume out of range: %04X", vl);
2283 vl = MAX_GAIN_INT;
2284 }
2285 if (vr > MAX_GAIN_INT) {
2286 ALOGV("Track right volume out of range: %04X", vr);
2287 vr = MAX_GAIN_INT;
2288 }
2289 // now apply the master volume and stream type volume
2290 vl = (uint32_t)(v * vl) << 12;
2291 vr = (uint32_t)(v * vr) << 12;
2292 // assuming master volume and stream type volume each go up to 1.0,
2293 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002294
Glenn Kasten05632a52012-01-03 14:22:33 -08002295 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2296 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002297 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002298 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002299 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002300 }
2301 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002302 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002303 // Delegate volume control to effect in track effect chain if needed
2304 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2305 // Do not ramp volume if volume is controlled by effect
2306 param = AudioMixer::VOLUME;
2307 track->mHasVolumeController = true;
2308 } else {
2309 // force no volume ramp when volume controller was just disabled or removed
2310 // from effect chain to avoid volume spike
2311 if (track->mHasVolumeController) {
2312 param = AudioMixer::VOLUME;
2313 }
2314 track->mHasVolumeController = false;
2315 }
2316
2317 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002318 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002319 vl = (vl + (1 << 11)) >> 12;
2320 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2321 vr = (vr + (1 << 11)) >> 12;
2322 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002323
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002324 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
Mathias Agopian65ab4712010-07-14 17:59:35 -07002325
Mathias Agopian65ab4712010-07-14 17:59:35 -07002326 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002327 mAudioMixer->setBufferProvider(name, track);
2328 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002329
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002330 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2331 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2332 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002333 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002334 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002335 AudioMixer::TRACK,
2336 AudioMixer::FORMAT, (void *)track->format());
2337 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002338 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002339 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002340 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002341 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002342 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002343 AudioMixer::RESAMPLE,
2344 AudioMixer::SAMPLE_RATE,
2345 (void *)(cblk->sampleRate));
2346 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002347 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002348 AudioMixer::TRACK,
2349 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2350 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002351 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002352 AudioMixer::TRACK,
2353 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2354
2355 // reset retry count
2356 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002357 // If one track is ready, set the mixer ready if:
2358 // - the mixer was not ready during previous round OR
2359 // - no other track is not ready
2360 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2361 mixerStatus != MIXER_TRACKS_ENABLED) {
2362 mixerStatus = MIXER_TRACKS_READY;
2363 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002364 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002365 //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 -07002366 if (track->isStopped()) {
2367 track->reset();
2368 }
2369 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2370 // We have consumed all the buffers of this track.
2371 // Remove it from the list of active tracks.
2372 tracksToRemove->add(track);
2373 } else {
2374 // No buffers for this track. Give it a few chances to
2375 // fill a buffer, then remove it from active list.
2376 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002377 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002378 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002379 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002380 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002381 // If one track is not ready, mark the mixer also not ready if:
2382 // - the mixer was ready during previous round OR
2383 // - no other track is ready
2384 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2385 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002386 mixerStatus = MIXER_TRACKS_ENABLED;
2387 }
2388 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002389 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002390 }
2391 }
2392
2393 // remove all the tracks that need to be...
2394 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002395 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002396 for (size_t i=0 ; i<count ; i++) {
2397 const sp<Track>& track = tracksToRemove->itemAt(i);
2398 mActiveTracks.remove(track);
2399 if (track->mainBuffer() != mMixBuffer) {
2400 chain = getEffectChain_l(track->sessionId());
2401 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002402 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002403 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002404 }
2405 }
2406 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002407 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002408 }
2409 }
2410 }
2411
2412 // mix buffer must be cleared if all tracks are connected to an
2413 // effect chain as in this case the mixer will not write to
2414 // mix buffer and track effects will accumulate into it
2415 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2416 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2417 }
2418
Eric Laurent27741442012-01-17 19:20:12 -08002419 mPrevMixerStatus = mixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002420 return mixerStatus;
2421}
2422
Glenn Kastenfff6d712012-01-12 16:38:12 -08002423void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002424{
Steve Block3856b092011-10-20 11:56:00 +01002425 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002426 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002427 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002428
Mathias Agopian65ab4712010-07-14 17:59:35 -07002429 size_t size = mTracks.size();
2430 for (size_t i = 0; i < size; i++) {
2431 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08002432 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002433 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002434 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002435 }
2436 }
2437}
2438
Glenn Kastenfff6d712012-01-12 16:38:12 -08002439void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002440{
Steve Block3856b092011-10-20 11:56:00 +01002441 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002442 this, streamType, valid);
2443 Mutex::Autolock _l(mLock);
2444
2445 mStreamTypes[streamType].valid = valid;
2446}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002447
2448// getTrackName_l() must be called with ThreadBase::mLock held
2449int AudioFlinger::MixerThread::getTrackName_l()
2450{
2451 return mAudioMixer->getTrackName();
2452}
2453
2454// deleteTrackName_l() must be called with ThreadBase::mLock held
2455void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2456{
Steve Block3856b092011-10-20 11:56:00 +01002457 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002458 mAudioMixer->deleteTrackName(name);
2459}
2460
2461// checkForNewParameters_l() must be called with ThreadBase::mLock held
2462bool AudioFlinger::MixerThread::checkForNewParameters_l()
2463{
2464 bool reconfig = false;
2465
2466 while (!mNewParameters.isEmpty()) {
2467 status_t status = NO_ERROR;
2468 String8 keyValuePair = mNewParameters[0];
2469 AudioParameter param = AudioParameter(keyValuePair);
2470 int value;
2471
2472 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2473 reconfig = true;
2474 }
2475 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002476 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002477 status = BAD_VALUE;
2478 } else {
2479 reconfig = true;
2480 }
2481 }
2482 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002483 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002484 status = BAD_VALUE;
2485 } else {
2486 reconfig = true;
2487 }
2488 }
2489 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2490 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002491 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002492 // if frame count is changed after track creation
2493 if (!mTracks.isEmpty()) {
2494 status = INVALID_OPERATION;
2495 } else {
2496 reconfig = true;
2497 }
2498 }
2499 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002500 // when changing the audio output device, call addBatteryData to notify
2501 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002502 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002503 uint32_t params = 0;
2504 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002505 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002506 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2507 }
2508
2509 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002510 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002511 // check if any other device (except speaker) is on
2512 if (value & deviceWithoutSpeaker ) {
2513 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2514 }
2515
2516 if (params != 0) {
2517 addBatteryData(params);
2518 }
2519 }
2520
Mathias Agopian65ab4712010-07-14 17:59:35 -07002521 // forward device change to effects that have requested to be
2522 // aware of attached audio device.
2523 mDevice = (uint32_t)value;
2524 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002525 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002526 }
2527 }
2528
2529 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002530 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002531 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002532 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002533 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002534 mStandby = true;
2535 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002536 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002537 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002538 }
2539 if (status == NO_ERROR && reconfig) {
2540 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002541 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2542 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002543 readOutputParameters();
2544 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2545 for (size_t i = 0; i < mTracks.size() ; i++) {
2546 int name = getTrackName_l();
2547 if (name < 0) break;
2548 mTracks[i]->mName = name;
2549 // limit track sample rate to 2 x new output sample rate
2550 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2551 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2552 }
2553 }
2554 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2555 }
2556 }
2557
2558 mNewParameters.removeAt(0);
2559
2560 mParamStatus = status;
2561 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002562 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2563 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002564 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002565 }
2566 return reconfig;
2567}
2568
2569status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2570{
2571 const size_t SIZE = 256;
2572 char buffer[SIZE];
2573 String8 result;
2574
2575 PlaybackThread::dumpInternals(fd, args);
2576
2577 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2578 result.append(buffer);
2579 write(fd, result.string(), result.size());
2580 return NO_ERROR;
2581}
2582
Mathias Agopian65ab4712010-07-14 17:59:35 -07002583uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2584{
Eric Laurent60e18242010-07-29 06:50:24 -07002585 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002586}
2587
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002588uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2589{
2590 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2591}
2592
Mathias Agopian65ab4712010-07-14 17:59:35 -07002593// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002594AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2595 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002596 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002597 // mLeftVolFloat, mRightVolFloat
2598 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002599{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002600}
2601
2602AudioFlinger::DirectOutputThread::~DirectOutputThread()
2603{
2604}
2605
Mathias Agopian65ab4712010-07-14 17:59:35 -07002606void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2607{
2608 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002609 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002610 return;
2611 }
2612
2613 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002614 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002615 size_t count = mFrameCount * mChannelCount;
2616 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2617 int16_t *dst = mMixBuffer + count-1;
2618 while(count--) {
2619 *dst-- = (int16_t)(*src--^0x80) << 8;
2620 }
2621 }
2622
2623 size_t frameCount = mFrameCount;
2624 int16_t *out = mMixBuffer;
2625 if (ramp) {
2626 if (mChannelCount == 1) {
2627 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2628 int32_t vlInc = d / (int32_t)frameCount;
2629 int32_t vl = ((int32_t)mLeftVolShort << 16);
2630 do {
2631 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2632 out++;
2633 vl += vlInc;
2634 } while (--frameCount);
2635
2636 } else {
2637 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2638 int32_t vlInc = d / (int32_t)frameCount;
2639 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2640 int32_t vrInc = d / (int32_t)frameCount;
2641 int32_t vl = ((int32_t)mLeftVolShort << 16);
2642 int32_t vr = ((int32_t)mRightVolShort << 16);
2643 do {
2644 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2645 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2646 out += 2;
2647 vl += vlInc;
2648 vr += vrInc;
2649 } while (--frameCount);
2650 }
2651 } else {
2652 if (mChannelCount == 1) {
2653 do {
2654 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2655 out++;
2656 } while (--frameCount);
2657 } else {
2658 do {
2659 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2660 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2661 out += 2;
2662 } while (--frameCount);
2663 }
2664 }
2665
2666 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002667 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002668 size_t count = mFrameCount * mChannelCount;
2669 int16_t *src = mMixBuffer;
2670 uint8_t *dst = (uint8_t *)mMixBuffer;
2671 while(count--) {
2672 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2673 }
2674 }
2675
2676 mLeftVolShort = leftVol;
2677 mRightVolShort = rightVol;
2678}
2679
2680bool AudioFlinger::DirectOutputThread::threadLoop()
2681{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002682 sp<Track> trackToRemove;
2683 sp<Track> activeTrack;
2684 nsecs_t standbyTime = systemTime();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002685 size_t mixBufferSize = mFrameCount*mFrameSize;
2686 uint32_t activeSleepTime = activeSleepTimeUs();
2687 uint32_t idleSleepTime = idleSleepTimeUs();
2688 uint32_t sleepTime = idleSleepTime;
2689 // use shorter standby delay as on normal output to release
2690 // hardware resources as soon as possible
2691 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2692
Eric Laurentfeb0db62011-07-22 09:04:31 -07002693 acquireWakeLock();
2694
Mathias Agopian65ab4712010-07-14 17:59:35 -07002695 while (!exitPending())
2696 {
2697 bool rampVolume;
2698 uint16_t leftVol;
2699 uint16_t rightVol;
2700 Vector< sp<EffectChain> > effectChains;
2701
2702 processConfigEvents();
2703
Glenn Kasten5d4eeea2012-02-24 07:25:40 -08002704 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002705 { // scope for the mLock
2706
2707 Mutex::Autolock _l(mLock);
2708
2709 if (checkForNewParameters_l()) {
2710 mixBufferSize = mFrameCount*mFrameSize;
2711 activeSleepTime = activeSleepTimeUs();
2712 idleSleepTime = idleSleepTimeUs();
2713 standbyDelay = microseconds(activeSleepTime*2);
2714 }
2715
2716 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002717 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2718 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002719 // wait until we have something to do...
2720 if (!mStandby) {
Glenn Kasten90bebef2012-01-27 15:24:38 -08002721 ALOGV("Audio hardware entering standby, mixer %p", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002722 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002723 mStandby = true;
2724 mBytesWritten = 0;
2725 }
2726
2727 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2728 // we're about to wait, flush the binder command buffer
2729 IPCThreadState::self()->flushCommands();
2730
2731 if (exitPending()) break;
2732
Eric Laurentfeb0db62011-07-22 09:04:31 -07002733 releaseWakeLock_l();
Glenn Kasten90bebef2012-01-27 15:24:38 -08002734 ALOGV("DirectOutputThread %p TID %d going to sleep", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002735 mWaitWorkCV.wait(mLock);
Glenn Kasten90bebef2012-01-27 15:24:38 -08002736 ALOGV("DirectOutputThread %p TID %d waking up in active mode", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002737 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002738
Glenn Kastenf1d45922012-01-13 15:54:24 -08002739 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002740 char value[PROPERTY_VALUE_MAX];
2741 property_get("ro.audio.silent", value, "0");
2742 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002743 ALOGD("Silence is golden");
Glenn Kasten6637baa2012-01-09 09:40:36 -08002744 setMasterMute_l(true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002745 }
2746 }
2747
2748 standbyTime = systemTime() + standbyDelay;
2749 sleepTime = idleSleepTime;
2750 continue;
2751 }
2752 }
2753
2754 effectChains = mEffectChains;
2755
2756 // find out which tracks need to be processed
2757 if (mActiveTracks.size() != 0) {
2758 sp<Track> t = mActiveTracks[0].promote();
2759 if (t == 0) continue;
2760
2761 Track* const track = t.get();
2762 audio_track_cblk_t* cblk = track->cblk();
2763
2764 // The first time a track is added we wait
2765 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002766 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002767 !track->isPaused() && !track->isTerminated())
2768 {
Steve Block3856b092011-10-20 11:56:00 +01002769 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002770
2771 if (track->mFillingUpStatus == Track::FS_FILLED) {
2772 track->mFillingUpStatus = Track::FS_ACTIVE;
2773 mLeftVolFloat = mRightVolFloat = 0;
2774 mLeftVolShort = mRightVolShort = 0;
2775 if (track->mState == TrackBase::RESUMING) {
2776 track->mState = TrackBase::ACTIVE;
2777 rampVolume = true;
2778 }
2779 } else if (cblk->server != 0) {
2780 // If the track is stopped before the first frame was mixed,
2781 // do not apply ramp
2782 rampVolume = true;
2783 }
2784 // compute volume for this track
2785 float left, right;
2786 if (track->isMuted() || mMasterMute || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002787 mStreamTypes[track->streamType()].mute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002788 left = right = 0;
2789 if (track->isPausing()) {
2790 track->setPaused();
2791 }
2792 } else {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002793 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002794 float v = mMasterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002795 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002796 float v_clamped = v * (vlr & 0xFFFF);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002797 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2798 left = v_clamped/MAX_GAIN;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002799 v_clamped = v * (vlr >> 16);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002800 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2801 right = v_clamped/MAX_GAIN;
2802 }
2803
2804 if (left != mLeftVolFloat || right != mRightVolFloat) {
2805 mLeftVolFloat = left;
2806 mRightVolFloat = right;
2807
2808 // If audio HAL implements volume control,
2809 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002810 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002811 left = 1.0f;
2812 right = 1.0f;
2813 }
2814
2815 // Convert volumes from float to 8.24
2816 uint32_t vl = (uint32_t)(left * (1 << 24));
2817 uint32_t vr = (uint32_t)(right * (1 << 24));
2818
2819 // Delegate volume control to effect in track effect chain if needed
2820 // only one effect chain can be present on DirectOutputThread, so if
2821 // there is one, the track is connected to it
2822 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002823 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002824 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002825 rampVolume = false;
2826 }
2827 }
2828
2829 // Convert volumes from 8.24 to 4.12 format
2830 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2831 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2832 leftVol = (uint16_t)v_clamped;
2833 v_clamped = (vr + (1 << 11)) >> 12;
2834 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2835 rightVol = (uint16_t)v_clamped;
2836 } else {
2837 leftVol = mLeftVolShort;
2838 rightVol = mRightVolShort;
2839 rampVolume = false;
2840 }
2841
2842 // reset retry count
2843 track->mRetryCount = kMaxTrackRetriesDirect;
2844 activeTrack = t;
2845 mixerStatus = MIXER_TRACKS_READY;
2846 } else {
Steve Block3856b092011-10-20 11:56:00 +01002847 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002848 if (track->isStopped()) {
2849 track->reset();
2850 }
2851 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2852 // We have consumed all the buffers of this track.
2853 // Remove it from the list of active tracks.
2854 trackToRemove = track;
2855 } else {
2856 // No buffers for this track. Give it a few chances to
2857 // fill a buffer, then remove it from active list.
2858 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002859 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002860 trackToRemove = track;
2861 } else {
2862 mixerStatus = MIXER_TRACKS_ENABLED;
2863 }
2864 }
2865 }
2866 }
2867
2868 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002869 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002870 mActiveTracks.remove(trackToRemove);
2871 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002872 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002873 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002874 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002875 }
2876 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002877 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002878 }
2879 }
2880
Eric Laurentde070132010-07-13 04:45:46 -07002881 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002882 }
2883
Glenn Kastenf6b16782011-12-15 09:51:17 -08002884 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002885 AudioBufferProvider::Buffer buffer;
2886 size_t frameCount = mFrameCount;
Glenn Kastena1117922012-01-26 10:53:32 -08002887 int8_t *curBuf = (int8_t *)mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002888 // output audio to hardware
2889 while (frameCount) {
2890 buffer.frameCount = frameCount;
John Grossman4ff14ba2012-02-08 16:37:41 -08002891 activeTrack->getNextBuffer(&buffer,
2892 AudioBufferProvider::kInvalidPTS);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002893 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002894 memset(curBuf, 0, frameCount * mFrameSize);
2895 break;
2896 }
2897 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2898 frameCount -= buffer.frameCount;
2899 curBuf += buffer.frameCount * mFrameSize;
2900 activeTrack->releaseBuffer(&buffer);
2901 }
2902 sleepTime = 0;
2903 standbyTime = systemTime() + standbyDelay;
2904 } else {
2905 if (sleepTime == 0) {
2906 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2907 sleepTime = activeSleepTime;
2908 } else {
2909 sleepTime = idleSleepTime;
2910 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002911 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002912 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2913 sleepTime = 0;
2914 }
2915 }
2916
2917 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002918 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002919 }
2920 // sleepTime == 0 means we must write to audio hardware
2921 if (sleepTime == 0) {
2922 if (mixerStatus == MIXER_TRACKS_READY) {
2923 applyVolume(leftVol, rightVol, rampVolume);
2924 }
2925 for (size_t i = 0; i < effectChains.size(); i ++) {
2926 effectChains[i]->process_l();
2927 }
Eric Laurentde070132010-07-13 04:45:46 -07002928 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002929
2930 mLastWriteTime = systemTime();
2931 mInWrite = true;
2932 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002933 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002934 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2935 mNumWrites++;
2936 mInWrite = false;
2937 mStandby = false;
2938 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002939 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002940 usleep(sleepTime);
2941 }
2942
2943 // finally let go of removed track, without the lock held
2944 // since we can't guarantee the destructors won't acquire that
2945 // same lock.
2946 trackToRemove.clear();
2947 activeTrack.clear();
2948
2949 // Effect chains will be actually deleted here if they were removed from
2950 // mEffectChains list during mixing or effects processing
2951 effectChains.clear();
2952 }
2953
2954 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002955 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002956 }
2957
Eric Laurentfeb0db62011-07-22 09:04:31 -07002958 releaseWakeLock();
2959
Steve Block3856b092011-10-20 11:56:00 +01002960 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002961 return false;
2962}
2963
2964// getTrackName_l() must be called with ThreadBase::mLock held
2965int AudioFlinger::DirectOutputThread::getTrackName_l()
2966{
2967 return 0;
2968}
2969
2970// deleteTrackName_l() must be called with ThreadBase::mLock held
2971void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2972{
2973}
2974
2975// checkForNewParameters_l() must be called with ThreadBase::mLock held
2976bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2977{
2978 bool reconfig = false;
2979
2980 while (!mNewParameters.isEmpty()) {
2981 status_t status = NO_ERROR;
2982 String8 keyValuePair = mNewParameters[0];
2983 AudioParameter param = AudioParameter(keyValuePair);
2984 int value;
2985
2986 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2987 // do not accept frame count changes if tracks are open as the track buffer
2988 // size depends on frame count and correct behavior would not be garantied
2989 // if frame count is changed after track creation
2990 if (!mTracks.isEmpty()) {
2991 status = INVALID_OPERATION;
2992 } else {
2993 reconfig = true;
2994 }
2995 }
2996 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002997 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002998 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002999 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003000 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003001 mStandby = true;
3002 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07003003 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003004 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003005 }
3006 if (status == NO_ERROR && reconfig) {
3007 readOutputParameters();
3008 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3009 }
3010 }
3011
3012 mNewParameters.removeAt(0);
3013
3014 mParamStatus = status;
3015 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003016 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3017 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003018 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003019 }
3020 return reconfig;
3021}
3022
3023uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
3024{
3025 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003026 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003027 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003028 } else {
3029 time = 10000;
3030 }
3031 return time;
3032}
3033
3034uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
3035{
3036 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003037 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003038 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003039 } else {
3040 time = 10000;
3041 }
3042 return time;
3043}
3044
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003045uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
3046{
3047 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003048 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003049 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3050 } else {
3051 time = 10000;
3052 }
3053 return time;
3054}
3055
3056
Mathias Agopian65ab4712010-07-14 17:59:35 -07003057// ----------------------------------------------------------------------------
3058
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003059AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003060 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003061 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3062 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003063{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003064 addOutputTrack(mainThread);
3065}
3066
3067AudioFlinger::DuplicatingThread::~DuplicatingThread()
3068{
3069 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3070 mOutputTracks[i]->destroy();
3071 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003072}
3073
3074bool AudioFlinger::DuplicatingThread::threadLoop()
3075{
3076 Vector< sp<Track> > tracksToRemove;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003077 nsecs_t standbyTime = systemTime();
3078 size_t mixBufferSize = mFrameCount*mFrameSize;
3079 SortedVector< sp<OutputTrack> > outputTracks;
3080 uint32_t writeFrames = 0;
3081 uint32_t activeSleepTime = activeSleepTimeUs();
3082 uint32_t idleSleepTime = idleSleepTimeUs();
3083 uint32_t sleepTime = idleSleepTime;
3084 Vector< sp<EffectChain> > effectChains;
3085
Eric Laurentfeb0db62011-07-22 09:04:31 -07003086 acquireWakeLock();
3087
Mathias Agopian65ab4712010-07-14 17:59:35 -07003088 while (!exitPending())
3089 {
3090 processConfigEvents();
3091
Glenn Kasten5d4eeea2012-02-24 07:25:40 -08003092 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003093 { // scope for the mLock
3094
3095 Mutex::Autolock _l(mLock);
3096
3097 if (checkForNewParameters_l()) {
3098 mixBufferSize = mFrameCount*mFrameSize;
3099 updateWaitTime();
3100 activeSleepTime = activeSleepTimeUs();
3101 idleSleepTime = idleSleepTimeUs();
3102 }
3103
3104 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3105
3106 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3107 outputTracks.add(mOutputTracks[i]);
3108 }
3109
3110 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08003111 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3112 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003113 if (!mStandby) {
3114 for (size_t i = 0; i < outputTracks.size(); i++) {
3115 outputTracks[i]->stop();
3116 }
3117 mStandby = true;
3118 mBytesWritten = 0;
3119 }
3120
3121 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3122 // we're about to wait, flush the binder command buffer
3123 IPCThreadState::self()->flushCommands();
3124 outputTracks.clear();
3125
3126 if (exitPending()) break;
3127
Eric Laurentfeb0db62011-07-22 09:04:31 -07003128 releaseWakeLock_l();
Glenn Kasten90bebef2012-01-27 15:24:38 -08003129 ALOGV("DuplicatingThread %p TID %d going to sleep", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003130 mWaitWorkCV.wait(mLock);
Glenn Kasten90bebef2012-01-27 15:24:38 -08003131 ALOGV("DuplicatingThread %p TID %d waking up", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003132 acquireWakeLock_l();
3133
Eric Laurent27741442012-01-17 19:20:12 -08003134 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08003135 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003136 char value[PROPERTY_VALUE_MAX];
3137 property_get("ro.audio.silent", value, "0");
3138 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00003139 ALOGD("Silence is golden");
Glenn Kasten6637baa2012-01-09 09:40:36 -08003140 setMasterMute_l(true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003141 }
3142 }
3143
John Grossman4ff14ba2012-02-08 16:37:41 -08003144 standbyTime = systemTime() + mStandbyTimeInNsecs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003145 sleepTime = idleSleepTime;
3146 continue;
3147 }
3148 }
3149
3150 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3151
3152 // prevent any changes in effect chain list and in each effect chain
3153 // during mixing and effect process as the audio buffers could be deleted
3154 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003155 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003156 }
3157
Glenn Kastenf6b16782011-12-15 09:51:17 -08003158 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003159 // mix buffers...
3160 if (outputsReady(outputTracks)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08003161 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003162 } else {
3163 memset(mMixBuffer, 0, mixBufferSize);
3164 }
3165 sleepTime = 0;
3166 writeFrames = mFrameCount;
3167 } else {
3168 if (sleepTime == 0) {
3169 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3170 sleepTime = activeSleepTime;
3171 } else {
3172 sleepTime = idleSleepTime;
3173 }
3174 } else if (mBytesWritten != 0) {
3175 // flush remaining overflow buffers in output tracks
3176 for (size_t i = 0; i < outputTracks.size(); i++) {
3177 if (outputTracks[i]->isActive()) {
3178 sleepTime = 0;
3179 writeFrames = 0;
3180 memset(mMixBuffer, 0, mixBufferSize);
3181 break;
3182 }
3183 }
3184 }
3185 }
3186
3187 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003188 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003189 }
3190 // sleepTime == 0 means we must write to audio hardware
3191 if (sleepTime == 0) {
3192 for (size_t i = 0; i < effectChains.size(); i ++) {
3193 effectChains[i]->process_l();
3194 }
3195 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003196 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003197
John Grossman4ff14ba2012-02-08 16:37:41 -08003198 standbyTime = systemTime() + mStandbyTimeInNsecs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003199 for (size_t i = 0; i < outputTracks.size(); i++) {
3200 outputTracks[i]->write(mMixBuffer, writeFrames);
3201 }
3202 mStandby = false;
3203 mBytesWritten += mixBufferSize;
3204 } else {
3205 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003206 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003207 usleep(sleepTime);
3208 }
3209
3210 // finally let go of all our tracks, without the lock held
3211 // since we can't guarantee the destructors won't acquire that
3212 // same lock.
3213 tracksToRemove.clear();
3214 outputTracks.clear();
3215
3216 // Effect chains will be actually deleted here if they were removed from
3217 // mEffectChains list during mixing or effects processing
3218 effectChains.clear();
3219 }
3220
Eric Laurentfeb0db62011-07-22 09:04:31 -07003221 releaseWakeLock();
3222
Mathias Agopian65ab4712010-07-14 17:59:35 -07003223 return false;
3224}
3225
3226void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3227{
Glenn Kasten99e53b82012-01-19 08:59:58 -08003228 // FIXME explain this formula
Mathias Agopian65ab4712010-07-14 17:59:35 -07003229 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003230 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003231 this,
3232 mSampleRate,
3233 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003234 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003235 frameCount);
3236 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003237 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003238 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003239 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003240 updateWaitTime();
3241 }
3242}
3243
3244void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3245{
3246 Mutex::Autolock _l(mLock);
3247 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003248 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003249 mOutputTracks[i]->destroy();
3250 mOutputTracks.removeAt(i);
3251 updateWaitTime();
3252 return;
3253 }
3254 }
Steve Block3856b092011-10-20 11:56:00 +01003255 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003256}
3257
3258void AudioFlinger::DuplicatingThread::updateWaitTime()
3259{
3260 mWaitTimeMs = UINT_MAX;
3261 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3262 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003263 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003264 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3265 if (waitTimeMs < mWaitTimeMs) {
3266 mWaitTimeMs = waitTimeMs;
3267 }
3268 }
3269 }
3270}
3271
3272
3273bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3274{
3275 for (size_t i = 0; i < outputTracks.size(); i++) {
3276 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3277 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003278 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003279 return false;
3280 }
3281 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3282 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003283 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003284 return false;
3285 }
3286 }
3287 return true;
3288}
3289
3290uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3291{
3292 return (mWaitTimeMs * 1000) / 2;
3293}
3294
3295// ----------------------------------------------------------------------------
3296
3297// TrackBase constructor must be called with AudioFlinger::mLock held
3298AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003299 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003300 const sp<Client>& client,
3301 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003302 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003303 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003304 int frameCount,
3305 uint32_t flags,
3306 const sp<IMemory>& sharedBuffer,
3307 int sessionId)
3308 : RefBase(),
3309 mThread(thread),
3310 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003311 mCblk(NULL),
3312 // mBuffer
3313 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003314 mFrameCount(0),
3315 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003316 mFormat(format),
3317 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3318 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003319 // mChannelCount
3320 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003321{
Steve Block3856b092011-10-20 11:56:00 +01003322 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003323
Steve Blockb8a80522011-12-20 16:23:08 +00003324 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003325 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003326 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003327 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3328 if (sharedBuffer == 0) {
3329 size += bufferSize;
3330 }
3331
3332 if (client != NULL) {
3333 mCblkMemory = client->heap()->allocate(size);
3334 if (mCblkMemory != 0) {
3335 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003336 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003337 new(mCblk) audio_track_cblk_t();
3338 // clear all buffers
3339 mCblk->frameCount = frameCount;
3340 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003341 mChannelCount = channelCount;
3342 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003343 if (sharedBuffer == 0) {
3344 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3345 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3346 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003347 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003348 mCblk->flags = CBLK_UNDERRUN_ON;
3349 } else {
3350 mBuffer = sharedBuffer->pointer();
3351 }
3352 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3353 }
3354 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003355 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003356 client->heap()->dump("AudioTrack");
3357 return;
3358 }
3359 } else {
3360 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003361 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003362 new(mCblk) audio_track_cblk_t();
3363 // clear all buffers
3364 mCblk->frameCount = frameCount;
3365 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003366 mChannelCount = channelCount;
3367 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003368 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3369 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3370 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003371 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003372 mCblk->flags = CBLK_UNDERRUN_ON;
3373 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003374 }
3375}
3376
3377AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3378{
Glenn Kastena0d68332012-01-27 16:47:15 -08003379 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003380 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003381 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003382 } else {
3383 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003384 }
3385 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003386 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003387 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003388 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003389 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003390 // If the client's reference count drops to zero, the associated destructor
3391 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3392 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003393 mClient.clear();
3394 }
3395}
3396
3397void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3398{
Glenn Kastene0feee32011-12-13 11:53:26 -08003399 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003400 mFrameCount = buffer->frameCount;
3401 step();
3402 buffer->frameCount = 0;
3403}
3404
3405bool AudioFlinger::ThreadBase::TrackBase::step() {
3406 bool result;
3407 audio_track_cblk_t* cblk = this->cblk();
3408
3409 result = cblk->stepServer(mFrameCount);
3410 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003411 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003412 mFlags |= STEPSERVER_FAILED;
3413 }
3414 return result;
3415}
3416
3417void AudioFlinger::ThreadBase::TrackBase::reset() {
3418 audio_track_cblk_t* cblk = this->cblk();
3419
3420 cblk->user = 0;
3421 cblk->server = 0;
3422 cblk->userBase = 0;
3423 cblk->serverBase = 0;
3424 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003425 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003426}
3427
Mathias Agopian65ab4712010-07-14 17:59:35 -07003428int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3429 return (int)mCblk->sampleRate;
3430}
3431
Mathias Agopian65ab4712010-07-14 17:59:35 -07003432void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3433 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003434 size_t frameSize = cblk->frameSize;
3435 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3436 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003437
3438 // Check validity of returned pointer in case the track control block would have been corrupted.
3439 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003440 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003441 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 -07003442 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003443 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003444 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003445 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003446 }
3447
3448 return bufferStart;
3449}
3450
3451// ----------------------------------------------------------------------------
3452
3453// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3454AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003455 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003456 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003457 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003458 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003459 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003460 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003461 int frameCount,
3462 const sp<IMemory>& sharedBuffer,
3463 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003464 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003465 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3466 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003467{
3468 if (mCblk != NULL) {
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003469 if (thread != NULL) {
3470 mName = thread->getTrackName_l();
3471 mMainBuffer = thread->mixBuffer();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003472 }
Glenn Kasten23d82a92012-02-03 11:10:00 -08003473 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003474 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003475 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003476 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003477 mStreamType = streamType;
3478 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3479 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003480 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003481 }
3482}
3483
3484AudioFlinger::PlaybackThread::Track::~Track()
3485{
Steve Block3856b092011-10-20 11:56:00 +01003486 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003487 sp<ThreadBase> thread = mThread.promote();
3488 if (thread != 0) {
3489 Mutex::Autolock _l(thread->mLock);
3490 mState = TERMINATED;
3491 }
3492}
3493
3494void AudioFlinger::PlaybackThread::Track::destroy()
3495{
3496 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3497 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08003498 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003499 // we must acquire a strong reference on this Track before locking mLock
3500 // here so that the destructor is called only when exiting this function.
3501 // On the other hand, as long as Track::destroy() is only called by
3502 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3503 // this Track with its member mTrack.
3504 sp<Track> keep(this);
3505 { // scope for mLock
3506 sp<ThreadBase> thread = mThread.promote();
3507 if (thread != 0) {
3508 if (!isOutputTrack()) {
3509 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08003510 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003511
3512 // to track the speaker usage
3513 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003514 }
3515 AudioSystem::releaseOutput(thread->id());
3516 }
3517 Mutex::Autolock _l(thread->mLock);
3518 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3519 playbackThread->destroyTrack_l(this);
3520 }
3521 }
3522}
3523
3524void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3525{
Glenn Kasten83d86532012-01-17 14:39:34 -08003526 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003527 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 -07003528 mName - AudioMixer::TRACK0,
Glenn Kasten44deb052012-02-05 18:09:08 -08003529 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003530 mStreamType,
3531 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003532 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003533 mSessionId,
3534 mFrameCount,
3535 mState,
3536 mMute,
3537 mFillingUpStatus,
3538 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003539 vlr & 0xFFFF,
3540 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003541 mCblk->server,
3542 mCblk->user,
3543 (int)mMainBuffer,
3544 (int)mAuxBuffer);
3545}
3546
John Grossman4ff14ba2012-02-08 16:37:41 -08003547status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
3548 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003549{
3550 audio_track_cblk_t* cblk = this->cblk();
3551 uint32_t framesReady;
3552 uint32_t framesReq = buffer->frameCount;
3553
3554 // Check if last stepServer failed, try to step now
3555 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3556 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003557 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003558 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3559 }
3560
3561 framesReady = cblk->framesReady();
3562
Glenn Kastenf6b16782011-12-15 09:51:17 -08003563 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003564 uint32_t s = cblk->server;
3565 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3566
3567 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3568 if (framesReq > framesReady) {
3569 framesReq = framesReady;
3570 }
3571 if (s + framesReq > bufferEnd) {
3572 framesReq = bufferEnd - s;
3573 }
3574
3575 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003576 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003577
3578 buffer->frameCount = framesReq;
3579 return NO_ERROR;
3580 }
3581
3582getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003583 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003584 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003585 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003586 return NOT_ENOUGH_DATA;
3587}
3588
John Grossman4ff14ba2012-02-08 16:37:41 -08003589uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const{
3590 return mCblk->framesReady();
3591}
3592
Mathias Agopian65ab4712010-07-14 17:59:35 -07003593bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003594 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003595
John Grossman4ff14ba2012-02-08 16:37:41 -08003596 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003597 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3598 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003599 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003600 return true;
3601 }
3602 return false;
3603}
3604
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003605status_t AudioFlinger::PlaybackThread::Track::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003606{
3607 status_t status = NO_ERROR;
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003608 ALOGV("start(%d), calling pid %d session %d tid %d",
3609 mName, IPCThreadState::self()->getCallingPid(), mSessionId, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003610 sp<ThreadBase> thread = mThread.promote();
3611 if (thread != 0) {
3612 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003613 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003614 // here the track could be either new, or restarted
3615 // in both cases "unstop" the track
3616 if (mState == PAUSED) {
3617 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003618 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003619 } else {
3620 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003621 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003622 }
3623
3624 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3625 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003626 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003627 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003628
3629 // to track the speaker usage
3630 if (status == NO_ERROR) {
3631 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3632 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003633 }
3634 if (status == NO_ERROR) {
3635 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3636 playbackThread->addTrack_l(this);
3637 } else {
3638 mState = state;
3639 }
3640 } else {
3641 status = BAD_VALUE;
3642 }
3643 return status;
3644}
3645
3646void AudioFlinger::PlaybackThread::Track::stop()
3647{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003648 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003649 sp<ThreadBase> thread = mThread.promote();
3650 if (thread != 0) {
3651 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003652 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003653 if (mState > STOPPED) {
3654 mState = STOPPED;
3655 // If the track is not active (PAUSED and buffers full), flush buffers
3656 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3657 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3658 reset();
3659 }
Steve Block3856b092011-10-20 11:56:00 +01003660 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003661 }
3662 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3663 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003664 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003665 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003666
3667 // to track the speaker usage
3668 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003669 }
3670 }
3671}
3672
3673void AudioFlinger::PlaybackThread::Track::pause()
3674{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003675 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003676 sp<ThreadBase> thread = mThread.promote();
3677 if (thread != 0) {
3678 Mutex::Autolock _l(thread->mLock);
3679 if (mState == ACTIVE || mState == RESUMING) {
3680 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003681 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003682 if (!isOutputTrack()) {
3683 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003684 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003685 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003686
3687 // to track the speaker usage
3688 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003689 }
3690 }
3691 }
3692}
3693
3694void AudioFlinger::PlaybackThread::Track::flush()
3695{
Steve Block3856b092011-10-20 11:56:00 +01003696 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003697 sp<ThreadBase> thread = mThread.promote();
3698 if (thread != 0) {
3699 Mutex::Autolock _l(thread->mLock);
3700 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3701 return;
3702 }
3703 // No point remaining in PAUSED state after a flush => go to
3704 // STOPPED state
3705 mState = STOPPED;
3706
Eric Laurent38ccae22011-03-28 18:37:07 -07003707 // do not reset the track if it is still in the process of being stopped or paused.
3708 // this will be done by prepareTracks_l() when the track is stopped.
3709 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3710 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3711 reset();
3712 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003713 }
3714}
3715
3716void AudioFlinger::PlaybackThread::Track::reset()
3717{
3718 // Do not reset twice to avoid discarding data written just after a flush and before
3719 // the audioflinger thread detects the track is stopped.
3720 if (!mResetDone) {
3721 TrackBase::reset();
3722 // Force underrun condition to avoid false underrun callback until first data is
3723 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003724 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3725 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003726 mFillingUpStatus = FS_FILLING;
3727 mResetDone = true;
3728 }
3729}
3730
3731void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3732{
3733 mMute = muted;
3734}
3735
Mathias Agopian65ab4712010-07-14 17:59:35 -07003736status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3737{
3738 status_t status = DEAD_OBJECT;
3739 sp<ThreadBase> thread = mThread.promote();
3740 if (thread != 0) {
3741 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3742 status = playbackThread->attachAuxEffect(this, EffectId);
3743 }
3744 return status;
3745}
3746
3747void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3748{
3749 mAuxEffectId = EffectId;
3750 mAuxBuffer = buffer;
3751}
3752
John Grossman4ff14ba2012-02-08 16:37:41 -08003753// timed audio tracks
3754
3755sp<AudioFlinger::PlaybackThread::TimedTrack>
3756AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003757 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003758 const sp<Client>& client,
3759 audio_stream_type_t streamType,
3760 uint32_t sampleRate,
3761 audio_format_t format,
3762 uint32_t channelMask,
3763 int frameCount,
3764 const sp<IMemory>& sharedBuffer,
3765 int sessionId) {
3766 if (!client->reserveTimedTrack())
3767 return NULL;
3768
3769 sp<TimedTrack> track = new TimedTrack(
3770 thread, client, streamType, sampleRate, format, channelMask, frameCount,
3771 sharedBuffer, sessionId);
3772
3773 if (track == NULL) {
3774 client->releaseTimedTrack();
3775 return NULL;
3776 }
3777
3778 return track;
3779}
3780
3781AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003782 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003783 const sp<Client>& client,
3784 audio_stream_type_t streamType,
3785 uint32_t sampleRate,
3786 audio_format_t format,
3787 uint32_t channelMask,
3788 int frameCount,
3789 const sp<IMemory>& sharedBuffer,
3790 int sessionId)
3791 : Track(thread, client, streamType, sampleRate, format, channelMask,
3792 frameCount, sharedBuffer, sessionId),
3793 mTimedSilenceBuffer(NULL),
3794 mTimedSilenceBufferSize(0),
3795 mTimedAudioOutputOnTime(false),
3796 mMediaTimeTransformValid(false)
3797{
3798 LocalClock lc;
3799 mLocalTimeFreq = lc.getLocalFreq();
3800
3801 mLocalTimeToSampleTransform.a_zero = 0;
3802 mLocalTimeToSampleTransform.b_zero = 0;
3803 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3804 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3805 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3806 &mLocalTimeToSampleTransform.a_to_b_denom);
3807}
3808
3809AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3810 mClient->releaseTimedTrack();
3811 delete [] mTimedSilenceBuffer;
3812}
3813
3814status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3815 size_t size, sp<IMemory>* buffer) {
3816
3817 Mutex::Autolock _l(mTimedBufferQueueLock);
3818
3819 trimTimedBufferQueue_l();
3820
3821 // lazily initialize the shared memory heap for timed buffers
3822 if (mTimedMemoryDealer == NULL) {
3823 const int kTimedBufferHeapSize = 512 << 10;
3824
3825 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3826 "AudioFlingerTimed");
3827 if (mTimedMemoryDealer == NULL)
3828 return NO_MEMORY;
3829 }
3830
3831 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3832 if (newBuffer == NULL) {
3833 newBuffer = mTimedMemoryDealer->allocate(size);
3834 if (newBuffer == NULL)
3835 return NO_MEMORY;
3836 }
3837
3838 *buffer = newBuffer;
3839 return NO_ERROR;
3840}
3841
3842// caller must hold mTimedBufferQueueLock
3843void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
3844 int64_t mediaTimeNow;
3845 {
3846 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3847 if (!mMediaTimeTransformValid)
3848 return;
3849
3850 int64_t targetTimeNow;
3851 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
3852 ? mCCHelper.getCommonTime(&targetTimeNow)
3853 : mCCHelper.getLocalTime(&targetTimeNow);
3854
3855 if (OK != res)
3856 return;
3857
3858 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
3859 &mediaTimeNow)) {
3860 return;
3861 }
3862 }
3863
3864 size_t trimIndex;
3865 for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
3866 if (mTimedBufferQueue[trimIndex].pts() > mediaTimeNow)
3867 break;
3868 }
3869
3870 if (trimIndex) {
3871 mTimedBufferQueue.removeItemsAt(0, trimIndex);
3872 }
3873}
3874
3875status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
3876 const sp<IMemory>& buffer, int64_t pts) {
3877
3878 {
3879 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3880 if (!mMediaTimeTransformValid)
3881 return INVALID_OPERATION;
3882 }
3883
3884 Mutex::Autolock _l(mTimedBufferQueueLock);
3885
3886 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
3887
3888 return NO_ERROR;
3889}
3890
3891status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
3892 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
3893
3894 ALOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
3895 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
3896 target);
3897
3898 if (!(target == TimedAudioTrack::LOCAL_TIME ||
3899 target == TimedAudioTrack::COMMON_TIME)) {
3900 return BAD_VALUE;
3901 }
3902
3903 Mutex::Autolock lock(mMediaTimeTransformLock);
3904 mMediaTimeTransform = xform;
3905 mMediaTimeTransformTarget = target;
3906 mMediaTimeTransformValid = true;
3907
3908 return NO_ERROR;
3909}
3910
3911#define min(a, b) ((a) < (b) ? (a) : (b))
3912
3913// implementation of getNextBuffer for tracks whose buffers have timestamps
3914status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
3915 AudioBufferProvider::Buffer* buffer, int64_t pts)
3916{
3917 if (pts == AudioBufferProvider::kInvalidPTS) {
3918 buffer->raw = 0;
3919 buffer->frameCount = 0;
3920 return INVALID_OPERATION;
3921 }
3922
John Grossman4ff14ba2012-02-08 16:37:41 -08003923 Mutex::Autolock _l(mTimedBufferQueueLock);
3924
3925 while (true) {
3926
3927 // if we have no timed buffers, then fail
3928 if (mTimedBufferQueue.isEmpty()) {
3929 buffer->raw = 0;
3930 buffer->frameCount = 0;
3931 return NOT_ENOUGH_DATA;
3932 }
3933
3934 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
3935
3936 // calculate the PTS of the head of the timed buffer queue expressed in
3937 // local time
3938 int64_t headLocalPTS;
3939 {
3940 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3941
3942 assert(mMediaTimeTransformValid);
3943
3944 if (mMediaTimeTransform.a_to_b_denom == 0) {
3945 // the transform represents a pause, so yield silence
3946 timedYieldSilence(buffer->frameCount, buffer);
3947 return NO_ERROR;
3948 }
3949
3950 int64_t transformedPTS;
3951 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
3952 &transformedPTS)) {
3953 // the transform failed. this shouldn't happen, but if it does
3954 // then just drop this buffer
3955 ALOGW("timedGetNextBuffer transform failed");
3956 buffer->raw = 0;
3957 buffer->frameCount = 0;
3958 mTimedBufferQueue.removeAt(0);
3959 return NO_ERROR;
3960 }
3961
3962 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
3963 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
3964 &headLocalPTS)) {
3965 buffer->raw = 0;
3966 buffer->frameCount = 0;
3967 return INVALID_OPERATION;
3968 }
3969 } else {
3970 headLocalPTS = transformedPTS;
3971 }
3972 }
3973
3974 // adjust the head buffer's PTS to reflect the portion of the head buffer
3975 // that has already been consumed
3976 int64_t effectivePTS = headLocalPTS +
3977 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
3978
3979 // Calculate the delta in samples between the head of the input buffer
3980 // queue and the start of the next output buffer that will be written.
3981 // If the transformation fails because of over or underflow, it means
3982 // that the sample's position in the output stream is so far out of
3983 // whack that it should just be dropped.
3984 int64_t sampleDelta;
3985 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
3986 ALOGV("*** head buffer is too far from PTS: dropped buffer");
3987 mTimedBufferQueue.removeAt(0);
3988 continue;
3989 }
3990 if (!mLocalTimeToSampleTransform.doForwardTransform(
3991 (effectivePTS - pts) << 32, &sampleDelta)) {
3992 ALOGV("*** too late during sample rate transform: dropped buffer");
3993 mTimedBufferQueue.removeAt(0);
3994 continue;
3995 }
3996
3997 ALOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
3998 __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
3999 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
4000 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
4001
4002 // if the delta between the ideal placement for the next input sample and
4003 // the current output position is within this threshold, then we will
4004 // concatenate the next input samples to the previous output
4005 const int64_t kSampleContinuityThreshold =
4006 (static_cast<int64_t>(sampleRate()) << 32) / 10;
4007
4008 // if this is the first buffer of audio that we're emitting from this track
4009 // then it should be almost exactly on time.
4010 const int64_t kSampleStartupThreshold = 1LL << 32;
4011
4012 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
4013 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
4014 // the next input is close enough to being on time, so concatenate it
4015 // with the last output
4016 timedYieldSamples(buffer);
4017
4018 ALOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4019 return NO_ERROR;
4020 } else if (sampleDelta > 0) {
4021 // the gap between the current output position and the proper start of
4022 // the next input sample is too big, so fill it with silence
4023 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4024
4025 timedYieldSilence(framesUntilNextInput, buffer);
4026 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4027 return NO_ERROR;
4028 } else {
4029 // the next input sample is late
4030 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4031 size_t onTimeSamplePosition =
4032 head.position() + lateFrames * mCblk->frameSize;
4033
4034 if (onTimeSamplePosition > head.buffer()->size()) {
4035 // all the remaining samples in the head are too late, so
4036 // drop it and move on
4037 ALOGV("*** too late: dropped buffer");
4038 mTimedBufferQueue.removeAt(0);
4039 continue;
4040 } else {
4041 // skip over the late samples
4042 head.setPosition(onTimeSamplePosition);
4043
4044 // yield the available samples
4045 timedYieldSamples(buffer);
4046
4047 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4048 return NO_ERROR;
4049 }
4050 }
4051 }
4052}
4053
4054// Yield samples from the timed buffer queue head up to the given output
4055// buffer's capacity.
4056//
4057// Caller must hold mTimedBufferQueueLock
4058void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples(
4059 AudioBufferProvider::Buffer* buffer) {
4060
4061 const TimedBuffer& head = mTimedBufferQueue[0];
4062
4063 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4064 head.position());
4065
4066 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4067 mCblk->frameSize);
4068 size_t framesRequested = buffer->frameCount;
4069 buffer->frameCount = min(framesLeftInHead, framesRequested);
4070
4071 mTimedAudioOutputOnTime = true;
4072}
4073
4074// Yield samples of silence up to the given output buffer's capacity
4075//
4076// Caller must hold mTimedBufferQueueLock
4077void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence(
4078 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4079
4080 // lazily allocate a buffer filled with silence
4081 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4082 delete [] mTimedSilenceBuffer;
4083 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4084 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4085 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4086 }
4087
4088 buffer->raw = mTimedSilenceBuffer;
4089 size_t framesRequested = buffer->frameCount;
4090 buffer->frameCount = min(numFrames, framesRequested);
4091
4092 mTimedAudioOutputOnTime = false;
4093}
4094
4095void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4096 AudioBufferProvider::Buffer* buffer) {
4097
4098 Mutex::Autolock _l(mTimedBufferQueueLock);
4099
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004100 // If the buffer which was just released is part of the buffer at the head
4101 // of the queue, be sure to update the amt of the buffer which has been
4102 // consumed. If the buffer being returned is not part of the head of the
4103 // queue, its either because the buffer is part of the silence buffer, or
4104 // because the head of the timed queue was trimmed after the mixer called
4105 // getNextBuffer but before the mixer called releaseBuffer.
4106 if ((buffer->raw != mTimedSilenceBuffer) && mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004107 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004108
4109 void* start = head.buffer()->pointer();
Glenn Kastenf063b492012-02-17 16:24:10 -08004110 void* end = (char *) head.buffer()->pointer() + head.buffer()->size();
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004111
4112 if ((buffer->raw >= start) && (buffer->raw <= end)) {
4113 head.setPosition(head.position() +
4114 (buffer->frameCount * mCblk->frameSize));
4115 if (static_cast<size_t>(head.position()) >= head.buffer()->size()) {
4116 mTimedBufferQueue.removeAt(0);
4117 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004118 }
4119 }
4120
4121 buffer->raw = 0;
4122 buffer->frameCount = 0;
4123}
4124
4125uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4126 Mutex::Autolock _l(mTimedBufferQueueLock);
4127
4128 uint32_t frames = 0;
4129 for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4130 const TimedBuffer& tb = mTimedBufferQueue[i];
4131 frames += (tb.buffer()->size() - tb.position()) / mCblk->frameSize;
4132 }
4133
4134 return frames;
4135}
4136
4137AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4138 : mPTS(0), mPosition(0) {}
4139
4140AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4141 const sp<IMemory>& buffer, int64_t pts)
4142 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4143
Mathias Agopian65ab4712010-07-14 17:59:35 -07004144// ----------------------------------------------------------------------------
4145
4146// RecordTrack constructor must be called with AudioFlinger::mLock held
4147AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004148 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004149 const sp<Client>& client,
4150 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004151 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004152 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004153 int frameCount,
4154 uint32_t flags,
4155 int sessionId)
4156 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004157 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004158 mOverflow(false)
4159{
4160 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01004161 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07004162 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004163 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07004164 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004165 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004166 } else {
4167 mCblk->frameSize = sizeof(int8_t);
4168 }
4169 }
4170}
4171
4172AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4173{
4174 sp<ThreadBase> thread = mThread.promote();
4175 if (thread != 0) {
4176 AudioSystem::releaseInput(thread->id());
4177 }
4178}
4179
John Grossman4ff14ba2012-02-08 16:37:41 -08004180status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004181{
4182 audio_track_cblk_t* cblk = this->cblk();
4183 uint32_t framesAvail;
4184 uint32_t framesReq = buffer->frameCount;
4185
4186 // Check if last stepServer failed, try to step now
4187 if (mFlags & TrackBase::STEPSERVER_FAILED) {
4188 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004189 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004190 mFlags &= ~TrackBase::STEPSERVER_FAILED;
4191 }
4192
4193 framesAvail = cblk->framesAvailable_l();
4194
Glenn Kastenf6b16782011-12-15 09:51:17 -08004195 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004196 uint32_t s = cblk->server;
4197 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4198
4199 if (framesReq > framesAvail) {
4200 framesReq = framesAvail;
4201 }
4202 if (s + framesReq > bufferEnd) {
4203 framesReq = bufferEnd - s;
4204 }
4205
4206 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004207 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004208
4209 buffer->frameCount = framesReq;
4210 return NO_ERROR;
4211 }
4212
4213getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004214 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004215 buffer->frameCount = 0;
4216 return NOT_ENOUGH_DATA;
4217}
4218
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004219status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004220{
4221 sp<ThreadBase> thread = mThread.promote();
4222 if (thread != 0) {
4223 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004224 return recordThread->start(this, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004225 } else {
4226 return BAD_VALUE;
4227 }
4228}
4229
4230void AudioFlinger::RecordThread::RecordTrack::stop()
4231{
4232 sp<ThreadBase> thread = mThread.promote();
4233 if (thread != 0) {
4234 RecordThread *recordThread = (RecordThread *)thread.get();
4235 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004236 TrackBase::reset();
4237 // Force overerrun condition to avoid false overrun callback until first data is
4238 // read from buffer
4239 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004240 }
4241}
4242
4243void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4244{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004245 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004246 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004247 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004248 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004249 mSessionId,
4250 mFrameCount,
4251 mState,
4252 mCblk->sampleRate,
4253 mCblk->server,
4254 mCblk->user);
4255}
4256
4257
4258// ----------------------------------------------------------------------------
4259
4260AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004261 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004262 DuplicatingThread *sourceThread,
4263 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004264 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004265 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004266 int frameCount)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004267 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004268 mActive(false), mSourceThread(sourceThread)
4269{
4270
Mathias Agopian65ab4712010-07-14 17:59:35 -07004271 if (mCblk != NULL) {
4272 mCblk->flags |= CBLK_DIRECTION_OUT;
4273 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004274 mOutBuffer.frameCount = 0;
4275 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01004276 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004277 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4278 mCblk, mBuffer, mCblk->buffers,
4279 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004280 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004281 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004282 }
4283}
4284
4285AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4286{
4287 clearBufferQueue();
4288}
4289
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004290status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004291{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004292 status_t status = Track::start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004293 if (status != NO_ERROR) {
4294 return status;
4295 }
4296
4297 mActive = true;
4298 mRetryCount = 127;
4299 return status;
4300}
4301
4302void AudioFlinger::PlaybackThread::OutputTrack::stop()
4303{
4304 Track::stop();
4305 clearBufferQueue();
4306 mOutBuffer.frameCount = 0;
4307 mActive = false;
4308}
4309
4310bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4311{
4312 Buffer *pInBuffer;
4313 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004314 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004315 bool outputBufferFull = false;
4316 inBuffer.frameCount = frames;
4317 inBuffer.i16 = data;
4318
4319 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4320
4321 if (!mActive && frames != 0) {
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004322 start(0);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004323 sp<ThreadBase> thread = mThread.promote();
4324 if (thread != 0) {
4325 MixerThread *mixerThread = (MixerThread *)thread.get();
4326 if (mCblk->frameCount > frames){
4327 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4328 uint32_t startFrames = (mCblk->frameCount - frames);
4329 pInBuffer = new Buffer;
4330 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4331 pInBuffer->frameCount = startFrames;
4332 pInBuffer->i16 = pInBuffer->mBuffer;
4333 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4334 mBufferQueue.add(pInBuffer);
4335 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004336 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004337 }
4338 }
4339 }
4340 }
4341
4342 while (waitTimeLeftMs) {
4343 // First write pending buffers, then new data
4344 if (mBufferQueue.size()) {
4345 pInBuffer = mBufferQueue.itemAt(0);
4346 } else {
4347 pInBuffer = &inBuffer;
4348 }
4349
4350 if (pInBuffer->frameCount == 0) {
4351 break;
4352 }
4353
4354 if (mOutBuffer.frameCount == 0) {
4355 mOutBuffer.frameCount = pInBuffer->frameCount;
4356 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08004357 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01004358 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004359 outputBufferFull = true;
4360 break;
4361 }
4362 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4363 if (waitTimeLeftMs >= waitTimeMs) {
4364 waitTimeLeftMs -= waitTimeMs;
4365 } else {
4366 waitTimeLeftMs = 0;
4367 }
4368 }
4369
4370 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4371 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4372 mCblk->stepUser(outFrames);
4373 pInBuffer->frameCount -= outFrames;
4374 pInBuffer->i16 += outFrames * channelCount;
4375 mOutBuffer.frameCount -= outFrames;
4376 mOutBuffer.i16 += outFrames * channelCount;
4377
4378 if (pInBuffer->frameCount == 0) {
4379 if (mBufferQueue.size()) {
4380 mBufferQueue.removeAt(0);
4381 delete [] pInBuffer->mBuffer;
4382 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01004383 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004384 } else {
4385 break;
4386 }
4387 }
4388 }
4389
4390 // If we could not write all frames, allocate a buffer and queue it for next time.
4391 if (inBuffer.frameCount) {
4392 sp<ThreadBase> thread = mThread.promote();
4393 if (thread != 0 && !thread->standby()) {
4394 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4395 pInBuffer = new Buffer;
4396 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4397 pInBuffer->frameCount = inBuffer.frameCount;
4398 pInBuffer->i16 = pInBuffer->mBuffer;
4399 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4400 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01004401 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004402 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004403 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004404 }
4405 }
4406 }
4407
4408 // Calling write() with a 0 length buffer, means that no more data will be written:
4409 // If no more buffers are pending, fill output track buffer to make sure it is started
4410 // by output mixer.
4411 if (frames == 0 && mBufferQueue.size() == 0) {
4412 if (mCblk->user < mCblk->frameCount) {
4413 frames = mCblk->frameCount - mCblk->user;
4414 pInBuffer = new Buffer;
4415 pInBuffer->mBuffer = new int16_t[frames * channelCount];
4416 pInBuffer->frameCount = frames;
4417 pInBuffer->i16 = pInBuffer->mBuffer;
4418 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4419 mBufferQueue.add(pInBuffer);
4420 } else if (mActive) {
4421 stop();
4422 }
4423 }
4424
4425 return outputBufferFull;
4426}
4427
4428status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4429{
4430 int active;
4431 status_t result;
4432 audio_track_cblk_t* cblk = mCblk;
4433 uint32_t framesReq = buffer->frameCount;
4434
Steve Block3856b092011-10-20 11:56:00 +01004435// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004436 buffer->frameCount = 0;
4437
4438 uint32_t framesAvail = cblk->framesAvailable();
4439
4440
4441 if (framesAvail == 0) {
4442 Mutex::Autolock _l(cblk->lock);
4443 goto start_loop_here;
4444 while (framesAvail == 0) {
4445 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004446 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004447 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004448 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004449 }
4450 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4451 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004452 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004453 }
4454 // read the server count again
4455 start_loop_here:
4456 framesAvail = cblk->framesAvailable_l();
4457 }
4458 }
4459
4460// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004461// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004462// }
4463
4464 if (framesReq > framesAvail) {
4465 framesReq = framesAvail;
4466 }
4467
4468 uint32_t u = cblk->user;
4469 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4470
4471 if (u + framesReq > bufferEnd) {
4472 framesReq = bufferEnd - u;
4473 }
4474
4475 buffer->frameCount = framesReq;
4476 buffer->raw = (void *)cblk->buffer(u);
4477 return NO_ERROR;
4478}
4479
4480
4481void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4482{
4483 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004484
4485 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004486 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004487 delete [] pBuffer->mBuffer;
4488 delete pBuffer;
4489 }
4490 mBufferQueue.clear();
4491}
4492
4493// ----------------------------------------------------------------------------
4494
4495AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4496 : RefBase(),
4497 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08004498 // 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 -07004499 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08004500 mPid(pid),
4501 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004502{
4503 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4504}
4505
4506// Client destructor must be called with AudioFlinger::mLock held
4507AudioFlinger::Client::~Client()
4508{
4509 mAudioFlinger->removeClient_l(mPid);
4510}
4511
Glenn Kasten435dbe62012-01-30 10:15:48 -08004512sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004513{
4514 return mMemoryDealer;
4515}
4516
John Grossman4ff14ba2012-02-08 16:37:41 -08004517// Reserve one of the limited slots for a timed audio track associated
4518// with this client
4519bool AudioFlinger::Client::reserveTimedTrack()
4520{
4521 const int kMaxTimedTracksPerClient = 4;
4522
4523 Mutex::Autolock _l(mTimedTrackLock);
4524
4525 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4526 ALOGW("can not create timed track - pid %d has exceeded the limit",
4527 mPid);
4528 return false;
4529 }
4530
4531 mTimedTrackCount++;
4532 return true;
4533}
4534
4535// Release a slot for a timed audio track
4536void AudioFlinger::Client::releaseTimedTrack()
4537{
4538 Mutex::Autolock _l(mTimedTrackLock);
4539 mTimedTrackCount--;
4540}
4541
Mathias Agopian65ab4712010-07-14 17:59:35 -07004542// ----------------------------------------------------------------------------
4543
4544AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4545 const sp<IAudioFlingerClient>& client,
4546 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004547 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004548{
4549}
4550
4551AudioFlinger::NotificationClient::~NotificationClient()
4552{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004553}
4554
4555void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4556{
4557 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08004558 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004559}
4560
4561// ----------------------------------------------------------------------------
4562
4563AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4564 : BnAudioTrack(),
4565 mTrack(track)
4566{
4567}
4568
4569AudioFlinger::TrackHandle::~TrackHandle() {
4570 // just stop the track on deletion, associated resources
4571 // will be freed from the main thread once all pending buffers have
4572 // been played. Unless it's not in the active track list, in which
4573 // case we free everything now...
4574 mTrack->destroy();
4575}
4576
Glenn Kasten90716c52012-01-26 13:40:12 -08004577sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4578 return mTrack->getCblk();
4579}
4580
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004581status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4582 return mTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004583}
4584
4585void AudioFlinger::TrackHandle::stop() {
4586 mTrack->stop();
4587}
4588
4589void AudioFlinger::TrackHandle::flush() {
4590 mTrack->flush();
4591}
4592
4593void AudioFlinger::TrackHandle::mute(bool e) {
4594 mTrack->mute(e);
4595}
4596
4597void AudioFlinger::TrackHandle::pause() {
4598 mTrack->pause();
4599}
4600
Mathias Agopian65ab4712010-07-14 17:59:35 -07004601status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4602{
4603 return mTrack->attachAuxEffect(EffectId);
4604}
4605
John Grossman4ff14ba2012-02-08 16:37:41 -08004606status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4607 sp<IMemory>* buffer) {
4608 if (!mTrack->isTimedTrack())
4609 return INVALID_OPERATION;
4610
4611 PlaybackThread::TimedTrack* tt =
4612 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4613 return tt->allocateTimedBuffer(size, buffer);
4614}
4615
4616status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4617 int64_t pts) {
4618 if (!mTrack->isTimedTrack())
4619 return INVALID_OPERATION;
4620
4621 PlaybackThread::TimedTrack* tt =
4622 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4623 return tt->queueTimedBuffer(buffer, pts);
4624}
4625
4626status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4627 const LinearTransform& xform, int target) {
4628
4629 if (!mTrack->isTimedTrack())
4630 return INVALID_OPERATION;
4631
4632 PlaybackThread::TimedTrack* tt =
4633 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4634 return tt->setMediaTimeTransform(
4635 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4636}
4637
Mathias Agopian65ab4712010-07-14 17:59:35 -07004638status_t AudioFlinger::TrackHandle::onTransact(
4639 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4640{
4641 return BnAudioTrack::onTransact(code, data, reply, flags);
4642}
4643
4644// ----------------------------------------------------------------------------
4645
4646sp<IAudioRecord> AudioFlinger::openRecord(
4647 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004648 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004649 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004650 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004651 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004652 int frameCount,
4653 uint32_t flags,
4654 int *sessionId,
4655 status_t *status)
4656{
4657 sp<RecordThread::RecordTrack> recordTrack;
4658 sp<RecordHandle> recordHandle;
4659 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004660 status_t lStatus;
4661 RecordThread *thread;
4662 size_t inFrameCount;
4663 int lSessionId;
4664
4665 // check calling permissions
4666 if (!recordingAllowed()) {
4667 lStatus = PERMISSION_DENIED;
4668 goto Exit;
4669 }
4670
4671 // add client to list
4672 { // scope for mLock
4673 Mutex::Autolock _l(mLock);
4674 thread = checkRecordThread_l(input);
4675 if (thread == NULL) {
4676 lStatus = BAD_VALUE;
4677 goto Exit;
4678 }
4679
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004680 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004681
4682 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004683 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004684 lSessionId = *sessionId;
4685 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004686 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004687 if (sessionId != NULL) {
4688 *sessionId = lSessionId;
4689 }
4690 }
4691 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004692 recordTrack = thread->createRecordTrack_l(client,
4693 sampleRate,
4694 format,
4695 channelMask,
4696 frameCount,
4697 flags,
4698 lSessionId,
4699 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004700 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004701 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004702 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4703 // destructor is called by the TrackBase destructor with mLock held
4704 client.clear();
4705 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004706 goto Exit;
4707 }
4708
4709 // return to handle to client
4710 recordHandle = new RecordHandle(recordTrack);
4711 lStatus = NO_ERROR;
4712
4713Exit:
4714 if (status) {
4715 *status = lStatus;
4716 }
4717 return recordHandle;
4718}
4719
4720// ----------------------------------------------------------------------------
4721
4722AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4723 : BnAudioRecord(),
4724 mRecordTrack(recordTrack)
4725{
4726}
4727
4728AudioFlinger::RecordHandle::~RecordHandle() {
4729 stop();
4730}
4731
Glenn Kasten90716c52012-01-26 13:40:12 -08004732sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4733 return mRecordTrack->getCblk();
4734}
4735
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004736status_t AudioFlinger::RecordHandle::start(pid_t tid) {
Steve Block3856b092011-10-20 11:56:00 +01004737 ALOGV("RecordHandle::start()");
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004738 return mRecordTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004739}
4740
4741void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004742 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004743 mRecordTrack->stop();
4744}
4745
Mathias Agopian65ab4712010-07-14 17:59:35 -07004746status_t AudioFlinger::RecordHandle::onTransact(
4747 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4748{
4749 return BnAudioRecord::onTransact(code, data, reply, flags);
4750}
4751
4752// ----------------------------------------------------------------------------
4753
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004754AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4755 AudioStreamIn *input,
4756 uint32_t sampleRate,
4757 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004758 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004759 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004760 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004761 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4762 // mRsmpInIndex and mInputBytes set by readInputParameters()
4763 mReqChannelCount(popcount(channels)),
4764 mReqSampleRate(sampleRate)
4765 // mBytesRead is only meaningful while active, and so is cleared in start()
4766 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004767{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004768 snprintf(mName, kNameLength, "AudioIn_%d", id);
4769
Mathias Agopian65ab4712010-07-14 17:59:35 -07004770 readInputParameters();
4771}
4772
4773
4774AudioFlinger::RecordThread::~RecordThread()
4775{
4776 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004777 delete mResampler;
4778 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004779}
4780
4781void AudioFlinger::RecordThread::onFirstRef()
4782{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004783 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004784}
4785
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004786status_t AudioFlinger::RecordThread::readyToRun()
4787{
4788 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004789 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004790 return status;
4791}
4792
Mathias Agopian65ab4712010-07-14 17:59:35 -07004793bool AudioFlinger::RecordThread::threadLoop()
4794{
4795 AudioBufferProvider::Buffer buffer;
4796 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004797 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004798
Eric Laurent44d98482010-09-30 16:12:31 -07004799 nsecs_t lastWarning = 0;
4800
Eric Laurentfeb0db62011-07-22 09:04:31 -07004801 acquireWakeLock();
4802
Mathias Agopian65ab4712010-07-14 17:59:35 -07004803 // start recording
4804 while (!exitPending()) {
4805
4806 processConfigEvents();
4807
4808 { // scope for mLock
4809 Mutex::Autolock _l(mLock);
4810 checkForNewParameters_l();
4811 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4812 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004813 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004814 mStandby = true;
4815 }
4816
4817 if (exitPending()) break;
4818
Eric Laurentfeb0db62011-07-22 09:04:31 -07004819 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004820 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004821 // go to sleep
4822 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004823 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004824 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004825 continue;
4826 }
4827 if (mActiveTrack != 0) {
4828 if (mActiveTrack->mState == TrackBase::PAUSING) {
4829 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004830 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004831 mStandby = true;
4832 }
4833 mActiveTrack.clear();
4834 mStartStopCond.broadcast();
4835 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4836 if (mReqChannelCount != mActiveTrack->channelCount()) {
4837 mActiveTrack.clear();
4838 mStartStopCond.broadcast();
4839 } else if (mBytesRead != 0) {
4840 // record start succeeds only if first read from audio input
4841 // succeeds
4842 if (mBytesRead > 0) {
4843 mActiveTrack->mState = TrackBase::ACTIVE;
4844 } else {
4845 mActiveTrack.clear();
4846 }
4847 mStartStopCond.broadcast();
4848 }
4849 mStandby = false;
4850 }
4851 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004852 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004853 }
4854
4855 if (mActiveTrack != 0) {
4856 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4857 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004858 unlockEffectChains(effectChains);
4859 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004860 continue;
4861 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004862 for (size_t i = 0; i < effectChains.size(); i ++) {
4863 effectChains[i]->process_l();
4864 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004865
Mathias Agopian65ab4712010-07-14 17:59:35 -07004866 buffer.frameCount = mFrameCount;
John Grossman4ff14ba2012-02-08 16:37:41 -08004867 if (CC_LIKELY(mActiveTrack->getNextBuffer(
4868 &buffer, AudioBufferProvider::kInvalidPTS) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004869 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004870 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004871 // no resampling
4872 while (framesOut) {
4873 size_t framesIn = mFrameCount - mRsmpInIndex;
4874 if (framesIn) {
4875 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4876 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4877 if (framesIn > framesOut)
4878 framesIn = framesOut;
4879 mRsmpInIndex += framesIn;
4880 framesOut -= framesIn;
4881 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004882 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004883 memcpy(dst, src, framesIn * mFrameSize);
4884 } else {
4885 int16_t *src16 = (int16_t *)src;
4886 int16_t *dst16 = (int16_t *)dst;
4887 if (mChannelCount == 1) {
4888 while (framesIn--) {
4889 *dst16++ = *src16;
4890 *dst16++ = *src16++;
4891 }
4892 } else {
4893 while (framesIn--) {
4894 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4895 src16 += 2;
4896 }
4897 }
4898 }
4899 }
4900 if (framesOut && mFrameCount == mRsmpInIndex) {
4901 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004902 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004903 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004904 framesOut = 0;
4905 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004906 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004907 mRsmpInIndex = 0;
4908 }
4909 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004910 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004911 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4912 // Force input into standby so that it tries to
4913 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004914 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004915 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004916 }
4917 mRsmpInIndex = mFrameCount;
4918 framesOut = 0;
4919 buffer.frameCount = 0;
4920 }
4921 }
4922 }
4923 } else {
4924 // resampling
4925
4926 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4927 // alter output frame count as if we were expecting stereo samples
4928 if (mChannelCount == 1 && mReqChannelCount == 1) {
4929 framesOut >>= 1;
4930 }
4931 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4932 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4933 // are 32 bit aligned which should be always true.
4934 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004935 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004936 // the resampler always outputs stereo samples: do post stereo to mono conversion
4937 int16_t *src = (int16_t *)mRsmpOutBuffer;
4938 int16_t *dst = buffer.i16;
4939 while (framesOut--) {
4940 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4941 src += 2;
4942 }
4943 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004944 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004945 }
4946
4947 }
4948 mActiveTrack->releaseBuffer(&buffer);
4949 mActiveTrack->overflow();
4950 }
4951 // client isn't retrieving buffers fast enough
4952 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004953 if (!mActiveTrack->setOverflow()) {
4954 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004955 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004956 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004957 lastWarning = now;
4958 }
4959 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004960 // Release the processor for a while before asking for a new buffer.
4961 // This will give the application more chance to read from the buffer and
4962 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004963 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004964 }
4965 }
Eric Laurentec437d82011-07-26 20:54:46 -07004966 // enable changes in effect chain
4967 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004968 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004969 }
4970
4971 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004972 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004973 }
4974 mActiveTrack.clear();
4975
4976 mStartStopCond.broadcast();
4977
Eric Laurentfeb0db62011-07-22 09:04:31 -07004978 releaseWakeLock();
4979
Steve Block3856b092011-10-20 11:56:00 +01004980 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004981 return false;
4982}
4983
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004984
4985sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4986 const sp<AudioFlinger::Client>& client,
4987 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004988 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004989 int channelMask,
4990 int frameCount,
4991 uint32_t flags,
4992 int sessionId,
4993 status_t *status)
4994{
4995 sp<RecordTrack> track;
4996 status_t lStatus;
4997
4998 lStatus = initCheck();
4999 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005000 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005001 goto Exit;
5002 }
5003
5004 { // scope for mLock
5005 Mutex::Autolock _l(mLock);
5006
5007 track = new RecordTrack(this, client, sampleRate,
5008 format, channelMask, frameCount, flags, sessionId);
5009
Glenn Kasten7378ca52012-01-20 13:44:40 -08005010 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005011 lStatus = NO_MEMORY;
5012 goto Exit;
5013 }
5014
5015 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005016 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5017 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005018 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005019 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5020 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005021 }
5022 lStatus = NO_ERROR;
5023
5024Exit:
5025 if (status) {
5026 *status = lStatus;
5027 }
5028 return track;
5029}
5030
Glenn Kasten6dbc1352012-02-02 10:56:47 -08005031status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005032{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08005033 ALOGV("RecordThread::start tid=%d", tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005034 sp <ThreadBase> strongMe = this;
5035 status_t status = NO_ERROR;
5036 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005037 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005038 if (mActiveTrack != 0) {
5039 if (recordTrack != mActiveTrack.get()) {
5040 status = -EBUSY;
5041 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5042 mActiveTrack->mState = TrackBase::ACTIVE;
5043 }
5044 return status;
5045 }
5046
5047 recordTrack->mState = TrackBase::IDLE;
5048 mActiveTrack = recordTrack;
5049 mLock.unlock();
5050 status_t status = AudioSystem::startInput(mId);
5051 mLock.lock();
5052 if (status != NO_ERROR) {
5053 mActiveTrack.clear();
5054 return status;
5055 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005056 mRsmpInIndex = mFrameCount;
5057 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005058 if (mResampler != NULL) {
5059 mResampler->reset();
5060 }
5061 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005062 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005063 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005064 mWaitWorkCV.signal();
5065 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005066 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005067 mActiveTrack.clear();
5068 status = INVALID_OPERATION;
5069 goto startError;
5070 }
5071 mStartStopCond.wait(mLock);
5072 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005073 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005074 status = BAD_VALUE;
5075 goto startError;
5076 }
Steve Block3856b092011-10-20 11:56:00 +01005077 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005078 return status;
5079 }
5080startError:
5081 AudioSystem::stopInput(mId);
5082 return status;
5083}
5084
5085void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005086 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005087 sp <ThreadBase> strongMe = this;
5088 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005089 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005090 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5091 mActiveTrack->mState = TrackBase::PAUSING;
5092 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005093 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005094 return;
5095 }
5096 mStartStopCond.wait(mLock);
5097 // if we have been restarted, recordTrack == mActiveTrack.get() here
5098 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5099 mLock.unlock();
5100 AudioSystem::stopInput(mId);
5101 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005102 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005103 }
5104 }
5105 }
5106}
5107
5108status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5109{
5110 const size_t SIZE = 256;
5111 char buffer[SIZE];
5112 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005113
5114 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5115 result.append(buffer);
5116
5117 if (mActiveTrack != 0) {
5118 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005119 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005120 mActiveTrack->dump(buffer, SIZE);
5121 result.append(buffer);
5122
5123 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5124 result.append(buffer);
5125 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5126 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005127 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005128 result.append(buffer);
5129 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5130 result.append(buffer);
5131 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5132 result.append(buffer);
5133
5134
5135 } else {
5136 result.append("No record client\n");
5137 }
5138 write(fd, result.string(), result.size());
5139
5140 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005141 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005142
5143 return NO_ERROR;
5144}
5145
John Grossman4ff14ba2012-02-08 16:37:41 -08005146status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005147{
5148 size_t framesReq = buffer->frameCount;
5149 size_t framesReady = mFrameCount - mRsmpInIndex;
5150 int channelCount;
5151
5152 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005153 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005154 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005155 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005156 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5157 // Force input into standby so that it tries to
5158 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005159 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005160 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005161 }
Glenn Kastene0feee32011-12-13 11:53:26 -08005162 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005163 buffer->frameCount = 0;
5164 return NOT_ENOUGH_DATA;
5165 }
5166 mRsmpInIndex = 0;
5167 framesReady = mFrameCount;
5168 }
5169
5170 if (framesReq > framesReady) {
5171 framesReq = framesReady;
5172 }
5173
5174 if (mChannelCount == 1 && mReqChannelCount == 2) {
5175 channelCount = 1;
5176 } else {
5177 channelCount = 2;
5178 }
5179 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5180 buffer->frameCount = framesReq;
5181 return NO_ERROR;
5182}
5183
5184void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5185{
5186 mRsmpInIndex += buffer->frameCount;
5187 buffer->frameCount = 0;
5188}
5189
5190bool AudioFlinger::RecordThread::checkForNewParameters_l()
5191{
5192 bool reconfig = false;
5193
5194 while (!mNewParameters.isEmpty()) {
5195 status_t status = NO_ERROR;
5196 String8 keyValuePair = mNewParameters[0];
5197 AudioParameter param = AudioParameter(keyValuePair);
5198 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08005199 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005200 int reqSamplingRate = mReqSampleRate;
5201 int reqChannelCount = mReqChannelCount;
5202
5203 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5204 reqSamplingRate = value;
5205 reconfig = true;
5206 }
5207 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08005208 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005209 reconfig = true;
5210 }
5211 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005212 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005213 reconfig = true;
5214 }
5215 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5216 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08005217 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005218 // if frame count is changed after track creation
5219 if (mActiveTrack != 0) {
5220 status = INVALID_OPERATION;
5221 } else {
5222 reconfig = true;
5223 }
5224 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005225 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5226 // forward device change to effects that have requested to be
5227 // aware of attached audio device.
5228 for (size_t i = 0; i < mEffectChains.size(); i++) {
5229 mEffectChains[i]->setDevice_l(value);
5230 }
5231 // store input device and output device but do not forward output device to audio HAL.
5232 // Note that status is ignored by the caller for output device
5233 // (see AudioFlinger::setParameters()
5234 if (value & AUDIO_DEVICE_OUT_ALL) {
5235 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5236 status = BAD_VALUE;
5237 } else {
5238 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07005239 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5240 if (mTrack != NULL) {
5241 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005242 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005243 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5244 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5245 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005246 }
5247 mDevice |= (uint32_t)value;
5248 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005249 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005250 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005251 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005252 mInput->stream->common.standby(&mInput->stream->common);
5253 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005254 }
5255 if (reconfig) {
5256 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005257 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005258 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005259 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
5260 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005261 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005262 status = NO_ERROR;
5263 }
5264 if (status == NO_ERROR) {
5265 readInputParameters();
5266 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5267 }
5268 }
5269 }
5270
5271 mNewParameters.removeAt(0);
5272
5273 mParamStatus = status;
5274 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07005275 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5276 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08005277 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005278 }
5279 return reconfig;
5280}
5281
5282String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5283{
Dima Zavinfce7a472011-04-19 22:30:36 -07005284 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005285 String8 out_s8 = String8();
5286
5287 Mutex::Autolock _l(mLock);
5288 if (initCheck() != NO_ERROR) {
5289 return out_s8;
5290 }
Dima Zavinfce7a472011-04-19 22:30:36 -07005291
Dima Zavin799a70e2011-04-18 16:57:27 -07005292 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07005293 out_s8 = String8(s);
5294 free(s);
5295 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005296}
5297
5298void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5299 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08005300 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005301
5302 switch (event) {
5303 case AudioSystem::INPUT_OPENED:
5304 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005305 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005306 desc.samplingRate = mSampleRate;
5307 desc.format = mFormat;
5308 desc.frameCount = mFrameCount;
5309 desc.latency = 0;
5310 param2 = &desc;
5311 break;
5312
5313 case AudioSystem::INPUT_CLOSED:
5314 default:
5315 break;
5316 }
5317 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5318}
5319
5320void AudioFlinger::RecordThread::readInputParameters()
5321{
Glenn Kastene9dd0172012-01-27 18:08:45 -08005322 delete mRsmpInBuffer;
5323 // mRsmpInBuffer is always assigned a new[] below
5324 delete mRsmpOutBuffer;
5325 mRsmpOutBuffer = NULL;
5326 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08005327 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005328
Dima Zavin799a70e2011-04-18 16:57:27 -07005329 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005330 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5331 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07005332 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08005333 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07005334 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005335 mFrameCount = mInputBytes / mFrameSize;
5336 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5337
5338 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
5339 {
5340 int channelCount;
5341 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5342 // stereo to mono post process as the resampler always outputs stereo.
5343 if (mChannelCount == 1 && mReqChannelCount == 2) {
5344 channelCount = 1;
5345 } else {
5346 channelCount = 2;
5347 }
5348 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5349 mResampler->setSampleRate(mSampleRate);
5350 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5351 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5352
5353 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5354 if (mChannelCount == 1 && mReqChannelCount == 1) {
5355 mFrameCount >>= 1;
5356 }
5357
5358 }
5359 mRsmpInIndex = mFrameCount;
5360}
5361
5362unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5363{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005364 Mutex::Autolock _l(mLock);
5365 if (initCheck() != NO_ERROR) {
5366 return 0;
5367 }
5368
Dima Zavin799a70e2011-04-18 16:57:27 -07005369 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005370}
5371
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005372uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5373{
5374 Mutex::Autolock _l(mLock);
5375 uint32_t result = 0;
5376 if (getEffectChain_l(sessionId) != 0) {
5377 result = EFFECT_SESSION;
5378 }
5379
5380 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5381 result |= TRACK_SESSION;
5382 }
5383
5384 return result;
5385}
5386
Eric Laurent59bd0da2011-08-01 09:52:20 -07005387AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5388{
5389 Mutex::Autolock _l(mLock);
5390 return mTrack;
5391}
5392
Glenn Kastenaed850d2012-01-26 09:46:34 -08005393AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005394{
5395 Mutex::Autolock _l(mLock);
5396 return mInput;
5397}
5398
5399AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5400{
5401 Mutex::Autolock _l(mLock);
5402 AudioStreamIn *input = mInput;
5403 mInput = NULL;
5404 return input;
5405}
5406
5407// this method must always be called either with ThreadBase mLock held or inside the thread loop
5408audio_stream_t* AudioFlinger::RecordThread::stream()
5409{
5410 if (mInput == NULL) {
5411 return NULL;
5412 }
5413 return &mInput->stream->common;
5414}
5415
5416
Mathias Agopian65ab4712010-07-14 17:59:35 -07005417// ----------------------------------------------------------------------------
5418
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005419audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005420 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005421 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005422 uint32_t *pChannels,
5423 uint32_t *pLatencyMs,
5424 uint32_t flags)
5425{
5426 status_t status;
5427 PlaybackThread *thread = NULL;
5428 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
5429 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005430 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005431 uint32_t channels = pChannels ? *pChannels : 0;
5432 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07005433 audio_stream_out_t *outStream;
5434 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005435
Steve Block3856b092011-10-20 11:56:00 +01005436 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07005437 pDevices ? *pDevices : 0,
5438 samplingRate,
5439 format,
5440 channels,
5441 flags);
5442
5443 if (pDevices == NULL || *pDevices == 0) {
5444 return 0;
5445 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005446
Mathias Agopian65ab4712010-07-14 17:59:35 -07005447 Mutex::Autolock _l(mLock);
5448
Dima Zavin799a70e2011-04-18 16:57:27 -07005449 outHwDev = findSuitableHwDev_l(*pDevices);
5450 if (outHwDev == NULL)
5451 return 0;
5452
Glenn Kasten58f30212012-01-12 12:27:51 -08005453 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005454 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01005455 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005456 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005457 samplingRate,
5458 format,
5459 channels,
5460 status);
5461
5462 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07005463 if (outStream != NULL) {
5464 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005465 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07005466
Dima Zavinfce7a472011-04-19 22:30:36 -07005467 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5468 (format != AUDIO_FORMAT_PCM_16_BIT) ||
5469 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005470 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005471 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005472 } else {
5473 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005474 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005475 }
5476 mPlaybackThreads.add(id, thread);
5477
Glenn Kastena0d68332012-01-27 16:47:15 -08005478 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5479 if (pFormat != NULL) *pFormat = format;
5480 if (pChannels != NULL) *pChannels = channels;
5481 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005482
5483 // notify client processes of the new output creation
5484 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5485 return id;
5486 }
5487
5488 return 0;
5489}
5490
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005491audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
5492 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005493{
5494 Mutex::Autolock _l(mLock);
5495 MixerThread *thread1 = checkMixerThread_l(output1);
5496 MixerThread *thread2 = checkMixerThread_l(output2);
5497
5498 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005499 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005500 return 0;
5501 }
5502
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005503 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005504 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5505 thread->addOutputTrack(thread2);
5506 mPlaybackThreads.add(id, thread);
5507 // notify client processes of the new output creation
5508 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5509 return id;
5510}
5511
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005512status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005513{
5514 // keep strong reference on the playback thread so that
5515 // it is not destroyed while exit() is executed
5516 sp <PlaybackThread> thread;
5517 {
5518 Mutex::Autolock _l(mLock);
5519 thread = checkPlaybackThread_l(output);
5520 if (thread == NULL) {
5521 return BAD_VALUE;
5522 }
5523
Steve Block3856b092011-10-20 11:56:00 +01005524 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005525
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005526 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005527 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005528 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005529 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5530 dupThread->removeOutputTrack((MixerThread *)thread.get());
5531 }
5532 }
5533 }
Glenn Kastena1117922012-01-26 10:53:32 -08005534 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005535 mPlaybackThreads.removeItem(output);
5536 }
5537 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005538 // The thread entity (active unit of execution) is no longer running here,
5539 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005540
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005541 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005542 AudioStreamOut *out = thread->clearOutput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005543 assert(out != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005544 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005545 out->hwDev->close_output_stream(out->hwDev, out->stream);
5546 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005547 }
5548 return NO_ERROR;
5549}
5550
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005551status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005552{
5553 Mutex::Autolock _l(mLock);
5554 PlaybackThread *thread = checkPlaybackThread_l(output);
5555
5556 if (thread == NULL) {
5557 return BAD_VALUE;
5558 }
5559
Steve Block3856b092011-10-20 11:56:00 +01005560 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005561 thread->suspend();
5562
5563 return NO_ERROR;
5564}
5565
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005566status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005567{
5568 Mutex::Autolock _l(mLock);
5569 PlaybackThread *thread = checkPlaybackThread_l(output);
5570
5571 if (thread == NULL) {
5572 return BAD_VALUE;
5573 }
5574
Steve Block3856b092011-10-20 11:56:00 +01005575 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005576
5577 thread->restore();
5578
5579 return NO_ERROR;
5580}
5581
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005582audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005583 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005584 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005585 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005586 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005587{
5588 status_t status;
5589 RecordThread *thread = NULL;
5590 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005591 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005592 uint32_t channels = pChannels ? *pChannels : 0;
5593 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005594 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005595 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005596 audio_stream_in_t *inStream;
5597 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005598
5599 if (pDevices == NULL || *pDevices == 0) {
5600 return 0;
5601 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005602
Mathias Agopian65ab4712010-07-14 17:59:35 -07005603 Mutex::Autolock _l(mLock);
5604
Dima Zavin799a70e2011-04-18 16:57:27 -07005605 inHwDev = findSuitableHwDev_l(*pDevices);
5606 if (inHwDev == NULL)
5607 return 0;
5608
Glenn Kasten58f30212012-01-12 12:27:51 -08005609 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005610 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005611 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005612 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005613 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005614 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005615 samplingRate,
5616 format,
5617 channels,
5618 acoustics,
5619 status);
5620
5621 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5622 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5623 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005624 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005625 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005626 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005627 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005628 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005629 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005630 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005631 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005632 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005633 }
5634
Dima Zavin799a70e2011-04-18 16:57:27 -07005635 if (inStream != NULL) {
5636 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5637
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005638 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005639 // Start record thread
5640 // RecorThread require both input and output device indication to forward to audio
5641 // pre processing modules
5642 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5643 thread = new RecordThread(this,
5644 input,
5645 reqSamplingRate,
5646 reqChannels,
5647 id,
5648 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005649 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005650 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005651 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5652 if (pFormat != NULL) *pFormat = format;
5653 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005654
Dima Zavin799a70e2011-04-18 16:57:27 -07005655 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005656
5657 // notify client processes of the new input creation
5658 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5659 return id;
5660 }
5661
5662 return 0;
5663}
5664
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005665status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005666{
5667 // keep strong reference on the record thread so that
5668 // it is not destroyed while exit() is executed
5669 sp <RecordThread> thread;
5670 {
5671 Mutex::Autolock _l(mLock);
5672 thread = checkRecordThread_l(input);
5673 if (thread == NULL) {
5674 return BAD_VALUE;
5675 }
5676
Steve Block3856b092011-10-20 11:56:00 +01005677 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08005678 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005679 mRecordThreads.removeItem(input);
5680 }
5681 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005682 // The thread entity (active unit of execution) is no longer running here,
5683 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005684
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005685 AudioStreamIn *in = thread->clearInput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005686 assert(in != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005687 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005688 in->hwDev->close_input_stream(in->hwDev, in->stream);
5689 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005690
5691 return NO_ERROR;
5692}
5693
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005694status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005695{
5696 Mutex::Autolock _l(mLock);
5697 MixerThread *dstThread = checkMixerThread_l(output);
5698 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005699 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005700 return BAD_VALUE;
5701 }
5702
Steve Block3856b092011-10-20 11:56:00 +01005703 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005704 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5705
Eric Laurent9f6530f2011-08-30 10:18:54 -07005706 dstThread->setStreamValid(stream, true);
5707
Mathias Agopian65ab4712010-07-14 17:59:35 -07005708 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5709 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08005710 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005711 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005712 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005713 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005714 }
Eric Laurentde070132010-07-13 04:45:46 -07005715 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005716
5717 return NO_ERROR;
5718}
5719
5720
5721int AudioFlinger::newAudioSessionId()
5722{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005723 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005724}
5725
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005726void AudioFlinger::acquireAudioSessionId(int audioSession)
5727{
5728 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005729 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005730 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005731 size_t num = mAudioSessionRefs.size();
5732 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005733 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5734 if (ref->sessionid == audioSession && ref->pid == caller) {
5735 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005736 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005737 return;
5738 }
5739 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005740 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5741 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005742}
5743
5744void AudioFlinger::releaseAudioSessionId(int audioSession)
5745{
5746 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005747 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005748 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005749 size_t num = mAudioSessionRefs.size();
5750 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005751 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5752 if (ref->sessionid == audioSession && ref->pid == caller) {
5753 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005754 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005755 if (ref->cnt == 0) {
5756 mAudioSessionRefs.removeAt(i);
5757 delete ref;
5758 purgeStaleEffects_l();
5759 }
5760 return;
5761 }
5762 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005763 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005764}
5765
5766void AudioFlinger::purgeStaleEffects_l() {
5767
Steve Block3856b092011-10-20 11:56:00 +01005768 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005769
5770 Vector< sp<EffectChain> > chains;
5771
5772 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5773 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5774 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5775 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005776 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5777 chains.push(ec);
5778 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005779 }
5780 }
5781 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5782 sp<RecordThread> t = mRecordThreads.valueAt(i);
5783 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5784 sp<EffectChain> ec = t->mEffectChains[j];
5785 chains.push(ec);
5786 }
5787 }
5788
5789 for (size_t i = 0; i < chains.size(); i++) {
5790 sp<EffectChain> ec = chains[i];
5791 int sessionid = ec->sessionId();
5792 sp<ThreadBase> t = ec->mThread.promote();
5793 if (t == 0) {
5794 continue;
5795 }
5796 size_t numsessionrefs = mAudioSessionRefs.size();
5797 bool found = false;
5798 for (size_t k = 0; k < numsessionrefs; k++) {
5799 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5800 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005801 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005802 sessionid, ref->pid, ref->cnt);
5803 found = true;
5804 break;
5805 }
5806 }
5807 if (!found) {
5808 // remove all effects from the chain
5809 while (ec->mEffects.size()) {
5810 sp<EffectModule> effect = ec->mEffects[0];
5811 effect->unPin();
5812 Mutex::Autolock _l (t->mLock);
5813 t->removeEffect_l(effect);
5814 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5815 sp<EffectHandle> handle = effect->mHandles[j].promote();
5816 if (handle != 0) {
5817 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005818 if (handle->mHasControl && handle->mEnabled) {
5819 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5820 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005821 }
5822 }
5823 AudioSystem::unregisterEffect(effect->id());
5824 }
5825 }
5826 }
5827 return;
5828}
5829
Mathias Agopian65ab4712010-07-14 17:59:35 -07005830// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005831AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005832{
Glenn Kastena1117922012-01-26 10:53:32 -08005833 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005834}
5835
5836// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005837AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005838{
5839 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08005840 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005841}
5842
5843// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005844AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005845{
Glenn Kastena1117922012-01-26 10:53:32 -08005846 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005847}
5848
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005849uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005850{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005851 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005852}
5853
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005854AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5855{
5856 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5857 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005858 AudioStreamOut *output = thread->getOutput();
5859 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005860 return thread;
5861 }
5862 }
5863 return NULL;
5864}
5865
5866uint32_t AudioFlinger::primaryOutputDevice_l()
5867{
5868 PlaybackThread *thread = primaryPlaybackThread_l();
5869
5870 if (thread == NULL) {
5871 return 0;
5872 }
5873
5874 return thread->device();
5875}
5876
5877
Mathias Agopian65ab4712010-07-14 17:59:35 -07005878// ----------------------------------------------------------------------------
5879// Effect management
5880// ----------------------------------------------------------------------------
5881
5882
Glenn Kastenf587ba52012-01-26 16:25:10 -08005883status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005884{
5885 Mutex::Autolock _l(mLock);
5886 return EffectQueryNumberEffects(numEffects);
5887}
5888
Glenn Kastenf587ba52012-01-26 16:25:10 -08005889status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005890{
5891 Mutex::Autolock _l(mLock);
5892 return EffectQueryEffect(index, descriptor);
5893}
5894
Glenn Kasten5e92a782012-01-30 07:40:52 -08005895status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08005896 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005897{
5898 Mutex::Autolock _l(mLock);
5899 return EffectGetDescriptor(pUuid, descriptor);
5900}
5901
5902
Mathias Agopian65ab4712010-07-14 17:59:35 -07005903sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5904 effect_descriptor_t *pDesc,
5905 const sp<IEffectClient>& effectClient,
5906 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005907 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005908 int sessionId,
5909 status_t *status,
5910 int *id,
5911 int *enabled)
5912{
5913 status_t lStatus = NO_ERROR;
5914 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005915 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005916
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005917 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005918 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005919
5920 if (pDesc == NULL) {
5921 lStatus = BAD_VALUE;
5922 goto Exit;
5923 }
5924
Eric Laurent84e9a102010-09-23 16:10:16 -07005925 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005926 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005927 lStatus = PERMISSION_DENIED;
5928 goto Exit;
5929 }
5930
Dima Zavinfce7a472011-04-19 22:30:36 -07005931 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005932 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08005933 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005934 lStatus = PERMISSION_DENIED;
5935 goto Exit;
5936 }
5937
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005938 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005939 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005940 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005941 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005942 lStatus = BAD_VALUE;
5943 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005944 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005945 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005946 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005947 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005948 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005949 }
5950 }
5951
Mathias Agopian65ab4712010-07-14 17:59:35 -07005952 {
5953 Mutex::Autolock _l(mLock);
5954
Mathias Agopian65ab4712010-07-14 17:59:35 -07005955
5956 if (!EffectIsNullUuid(&pDesc->uuid)) {
5957 // if uuid is specified, request effect descriptor
5958 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5959 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005960 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005961 goto Exit;
5962 }
5963 } else {
5964 // if uuid is not specified, look for an available implementation
5965 // of the required type in effect factory
5966 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005967 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005968 lStatus = BAD_VALUE;
5969 goto Exit;
5970 }
5971 uint32_t numEffects = 0;
5972 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005973 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005974 bool found = false;
5975
5976 lStatus = EffectQueryNumberEffects(&numEffects);
5977 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005978 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005979 goto Exit;
5980 }
5981 for (uint32_t i = 0; i < numEffects; i++) {
5982 lStatus = EffectQueryEffect(i, &desc);
5983 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005984 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005985 continue;
5986 }
5987 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5988 // If matching type found save effect descriptor. If the session is
5989 // 0 and the effect is not auxiliary, continue enumeration in case
5990 // an auxiliary version of this effect type is available
5991 found = true;
5992 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005993 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005994 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5995 break;
5996 }
5997 }
5998 }
5999 if (!found) {
6000 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00006001 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006002 goto Exit;
6003 }
6004 // For same effect type, chose auxiliary version over insert version if
6005 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07006006 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006007 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
6008 memcpy(&desc, &d, sizeof(effect_descriptor_t));
6009 }
6010 }
6011
6012 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07006013 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006014 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6015 lStatus = INVALID_OPERATION;
6016 goto Exit;
6017 }
6018
Eric Laurent59255e42011-07-27 19:49:51 -07006019 // check recording permission for visualizer
6020 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
6021 !recordingAllowed()) {
6022 lStatus = PERMISSION_DENIED;
6023 goto Exit;
6024 }
6025
Mathias Agopian65ab4712010-07-14 17:59:35 -07006026 // return effect descriptor
6027 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
6028
6029 // If output is not specified try to find a matching audio session ID in one of the
6030 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07006031 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
6032 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006033 // Note: io is never 0 when creating an effect on an input
6034 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006035 // look for the thread where the specified audio session is present
6036 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6037 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006038 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07006039 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07006040 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006041 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006042 if (io == 0) {
6043 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6044 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6045 io = mRecordThreads.keyAt(i);
6046 break;
6047 }
6048 }
6049 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006050 // If no output thread contains the requested session ID, default to
6051 // first output. The effect chain will be moved to the correct output
6052 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006053 if (io == 0 && mPlaybackThreads.size()) {
6054 io = mPlaybackThreads.keyAt(0);
6055 }
Steve Block3856b092011-10-20 11:56:00 +01006056 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006057 }
6058 ThreadBase *thread = checkRecordThread_l(io);
6059 if (thread == NULL) {
6060 thread = checkPlaybackThread_l(io);
6061 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00006062 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006063 lStatus = BAD_VALUE;
6064 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07006065 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006066 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006067
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006068 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006069
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006070 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07006071 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6072 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006073 if (handle != 0 && id != NULL) {
6074 *id = handle->id();
6075 }
6076 }
6077
6078Exit:
6079 if(status) {
6080 *status = lStatus;
6081 }
6082 return handle;
6083}
6084
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006085status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
6086 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07006087{
Steve Block3856b092011-10-20 11:56:00 +01006088 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07006089 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006090 Mutex::Autolock _l(mLock);
6091 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006092 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006093 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006094 }
Eric Laurentde070132010-07-13 04:45:46 -07006095 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6096 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006097 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006098 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006099 }
Eric Laurentde070132010-07-13 04:45:46 -07006100 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6101 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006102 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006103 return BAD_VALUE;
6104 }
6105
6106 Mutex::Autolock _dl(dstThread->mLock);
6107 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07006108 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07006109
Mathias Agopian65ab4712010-07-14 17:59:35 -07006110 return NO_ERROR;
6111}
6112
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006113// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07006114status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07006115 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07006116 AudioFlinger::PlaybackThread *dstThread,
6117 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07006118{
Steve Block3856b092011-10-20 11:56:00 +01006119 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006120 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07006121
Eric Laurent59255e42011-07-27 19:49:51 -07006122 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006123 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006124 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006125 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07006126 return INVALID_OPERATION;
6127 }
6128
Eric Laurent39e94f82010-07-28 01:32:47 -07006129 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07006130 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07006131 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07006132 // removed.
6133 srcThread->removeEffectChain_l(chain);
6134
6135 // transfer all effects one by one so that new effect chain is created on new thread with
6136 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006137 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07006138 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006139 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07006140 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6141 while (effect != 0) {
6142 srcThread->removeEffect_l(effect);
6143 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07006144 // removeEffect_l() has stopped the effect if it was active so it must be restarted
6145 if (effect->state() == EffectModule::ACTIVE ||
6146 effect->state() == EffectModule::STOPPING) {
6147 effect->start();
6148 }
Eric Laurent39e94f82010-07-28 01:32:47 -07006149 // if the move request is not received from audio policy manager, the effect must be
6150 // re-registered with the new strategy and output
6151 if (dstChain == 0) {
6152 dstChain = effect->chain().promote();
6153 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006154 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07006155 srcThread->addEffect_l(effect);
6156 return NO_INIT;
6157 }
6158 strategy = dstChain->strategy();
6159 }
6160 if (reRegister) {
6161 AudioSystem::unregisterEffect(effect->id());
6162 AudioSystem::registerEffect(&effect->desc(),
6163 dstOutput,
6164 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07006165 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07006166 effect->id());
6167 }
Eric Laurentde070132010-07-13 04:45:46 -07006168 effect = chain->getEffectFromId_l(0);
6169 }
6170
6171 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006172}
6173
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006174
Mathias Agopian65ab4712010-07-14 17:59:35 -07006175// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006176sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07006177 const sp<AudioFlinger::Client>& client,
6178 const sp<IEffectClient>& effectClient,
6179 int32_t priority,
6180 int sessionId,
6181 effect_descriptor_t *desc,
6182 int *enabled,
6183 status_t *status
6184 )
6185{
6186 sp<EffectModule> effect;
6187 sp<EffectHandle> handle;
6188 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006189 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07006190 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006191 bool effectCreated = false;
6192 bool effectRegistered = false;
6193
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006194 lStatus = initCheck();
6195 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006196 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006197 goto Exit;
6198 }
6199
6200 // Do not allow effects with session ID 0 on direct output or duplicating threads
6201 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07006202 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006203 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07006204 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006205 lStatus = BAD_VALUE;
6206 goto Exit;
6207 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006208 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08006209 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006210 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006211 desc->name, desc->flags, mType);
6212 lStatus = BAD_VALUE;
6213 goto Exit;
6214 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006215
Steve Block3856b092011-10-20 11:56:00 +01006216 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006217
6218 { // scope for mLock
6219 Mutex::Autolock _l(mLock);
6220
6221 // check for existing effect chain with the requested audio session
6222 chain = getEffectChain_l(sessionId);
6223 if (chain == 0) {
6224 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006225 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006226 chain = new EffectChain(this, sessionId);
6227 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07006228 chain->setStrategy(getStrategyForSession_l(sessionId));
6229 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006230 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07006231 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006232 }
6233
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08006234 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006235
6236 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006237 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006238 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07006239 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006240 if (lStatus != NO_ERROR) {
6241 goto Exit;
6242 }
6243 effectRegistered = true;
6244 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07006245 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006246 lStatus = effect->status();
6247 if (lStatus != NO_ERROR) {
6248 goto Exit;
6249 }
Eric Laurentcab11242010-07-15 12:50:15 -07006250 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006251 if (lStatus != NO_ERROR) {
6252 goto Exit;
6253 }
6254 effectCreated = true;
6255
6256 effect->setDevice(mDevice);
6257 effect->setMode(mAudioFlinger->getMode());
6258 }
6259 // create effect handle and connect it to effect module
6260 handle = new EffectHandle(effect, client, effectClient, priority);
6261 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08006262 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006263 *enabled = (int)effect->isEnabled();
6264 }
6265 }
6266
6267Exit:
6268 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07006269 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006270 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07006271 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006272 }
6273 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07006274 AudioSystem::unregisterEffect(effect->id());
6275 }
6276 if (chainCreated) {
6277 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006278 }
6279 handle.clear();
6280 }
6281
6282 if(status) {
6283 *status = lStatus;
6284 }
6285 return handle;
6286}
6287
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006288sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6289{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006290 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08006291 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006292}
6293
Eric Laurentde070132010-07-13 04:45:46 -07006294// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6295// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006296status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07006297{
6298 // check for existing effect chain with the requested audio session
6299 int sessionId = effect->sessionId();
6300 sp<EffectChain> chain = getEffectChain_l(sessionId);
6301 bool chainCreated = false;
6302
6303 if (chain == 0) {
6304 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006305 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006306 chain = new EffectChain(this, sessionId);
6307 addEffectChain_l(chain);
6308 chain->setStrategy(getStrategyForSession_l(sessionId));
6309 chainCreated = true;
6310 }
Steve Block3856b092011-10-20 11:56:00 +01006311 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006312
6313 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006314 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07006315 this, effect->desc().name, chain.get());
6316 return BAD_VALUE;
6317 }
6318
6319 status_t status = chain->addEffect_l(effect);
6320 if (status != NO_ERROR) {
6321 if (chainCreated) {
6322 removeEffectChain_l(chain);
6323 }
6324 return status;
6325 }
6326
6327 effect->setDevice(mDevice);
6328 effect->setMode(mAudioFlinger->getMode());
6329 return NO_ERROR;
6330}
6331
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006332void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07006333
Steve Block3856b092011-10-20 11:56:00 +01006334 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006335 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07006336 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6337 detachAuxEffect_l(effect->id());
6338 }
6339
6340 sp<EffectChain> chain = effect->chain().promote();
6341 if (chain != 0) {
6342 // remove effect chain if removing last effect
6343 if (chain->removeEffect_l(effect) == 0) {
6344 removeEffectChain_l(chain);
6345 }
6346 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00006347 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006348 }
6349}
6350
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006351void AudioFlinger::ThreadBase::lockEffectChains_l(
6352 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
6353{
6354 effectChains = mEffectChains;
6355 for (size_t i = 0; i < mEffectChains.size(); i++) {
6356 mEffectChains[i]->lock();
6357 }
6358}
6359
6360void AudioFlinger::ThreadBase::unlockEffectChains(
6361 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
6362{
6363 for (size_t i = 0; i < effectChains.size(); i++) {
6364 effectChains[i]->unlock();
6365 }
6366}
6367
6368sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6369{
6370 Mutex::Autolock _l(mLock);
6371 return getEffectChain_l(sessionId);
6372}
6373
6374sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6375{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006376 size_t size = mEffectChains.size();
6377 for (size_t i = 0; i < size; i++) {
6378 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08006379 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006380 }
6381 }
Glenn Kasten090f0192012-01-30 13:00:02 -08006382 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006383}
6384
Glenn Kastenf78aee72012-01-04 11:00:47 -08006385void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006386{
6387 Mutex::Autolock _l(mLock);
6388 size_t size = mEffectChains.size();
6389 for (size_t i = 0; i < size; i++) {
6390 mEffectChains[i]->setMode_l(mode);
6391 }
6392}
6393
6394void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006395 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08006396 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07006397
Mathias Agopian65ab4712010-07-14 17:59:35 -07006398 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006399 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006400 // delete the effect module if removing last handle on it
6401 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006402 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006403 removeEffect_l(effect);
6404 AudioSystem::unregisterEffect(effect->id());
6405 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006406 }
6407}
6408
6409status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6410{
6411 int session = chain->sessionId();
6412 int16_t *buffer = mMixBuffer;
6413 bool ownsBuffer = false;
6414
Steve Block3856b092011-10-20 11:56:00 +01006415 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006416 if (session > 0) {
6417 // Only one effect chain can be present in direct output thread and it uses
6418 // the mix buffer as input
6419 if (mType != DIRECT) {
6420 size_t numSamples = mFrameCount * mChannelCount;
6421 buffer = new int16_t[numSamples];
6422 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01006423 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006424 ownsBuffer = true;
6425 }
6426
6427 // Attach all tracks with same session ID to this chain.
6428 for (size_t i = 0; i < mTracks.size(); ++i) {
6429 sp<Track> track = mTracks[i];
6430 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006431 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006432 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006433 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006434 }
6435 }
6436
6437 // indicate all active tracks in the chain
6438 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6439 sp<Track> track = mActiveTracks[i].promote();
6440 if (track == 0) continue;
6441 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006442 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07006443 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006444 }
6445 }
6446 }
6447
6448 chain->setInBuffer(buffer, ownsBuffer);
6449 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006450 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006451 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006452 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6453 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006454 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006455 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6456 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006457 // Effect chain for other sessions are inserted at beginning of effect
6458 // chains list to be processed before output mix effects. Relative order between other
6459 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006460 size_t size = mEffectChains.size();
6461 size_t i = 0;
6462 for (i = 0; i < size; i++) {
6463 if (mEffectChains[i]->sessionId() < session) break;
6464 }
6465 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006466 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006467
6468 return NO_ERROR;
6469}
6470
6471size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6472{
6473 int session = chain->sessionId();
6474
Steve Block3856b092011-10-20 11:56:00 +01006475 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006476
6477 for (size_t i = 0; i < mEffectChains.size(); i++) {
6478 if (chain == mEffectChains[i]) {
6479 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006480 // detach all active tracks from 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("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006486 chain.get(), session);
6487 chain->decActiveTrackCnt();
6488 }
6489 }
6490
Mathias Agopian65ab4712010-07-14 17:59:35 -07006491 // detach all tracks with same session ID from this chain
6492 for (size_t i = 0; i < mTracks.size(); ++i) {
6493 sp<Track> track = mTracks[i];
6494 if (session == track->sessionId()) {
6495 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006496 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006497 }
6498 }
Eric Laurentde070132010-07-13 04:45:46 -07006499 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006500 }
6501 }
6502 return mEffectChains.size();
6503}
6504
Eric Laurentde070132010-07-13 04:45:46 -07006505status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6506 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006507{
6508 Mutex::Autolock _l(mLock);
6509 return attachAuxEffect_l(track, EffectId);
6510}
6511
Eric Laurentde070132010-07-13 04:45:46 -07006512status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6513 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006514{
6515 status_t status = NO_ERROR;
6516
6517 if (EffectId == 0) {
6518 track->setAuxBuffer(0, NULL);
6519 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006520 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6521 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006522 if (effect != 0) {
6523 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6524 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6525 } else {
6526 status = INVALID_OPERATION;
6527 }
6528 } else {
6529 status = BAD_VALUE;
6530 }
6531 }
6532 return status;
6533}
6534
6535void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6536{
6537 for (size_t i = 0; i < mTracks.size(); ++i) {
6538 sp<Track> track = mTracks[i];
6539 if (track->auxEffectId() == effectId) {
6540 attachAuxEffect_l(track, 0);
6541 }
6542 }
6543}
6544
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006545status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6546{
6547 // only one chain per input thread
6548 if (mEffectChains.size() != 0) {
6549 return INVALID_OPERATION;
6550 }
Steve Block3856b092011-10-20 11:56:00 +01006551 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006552
6553 chain->setInBuffer(NULL);
6554 chain->setOutBuffer(NULL);
6555
Eric Laurent59255e42011-07-27 19:49:51 -07006556 checkSuspendOnAddEffectChain_l(chain);
6557
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006558 mEffectChains.add(chain);
6559
6560 return NO_ERROR;
6561}
6562
6563size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6564{
Steve Block3856b092011-10-20 11:56:00 +01006565 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006566 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006567 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6568 chain.get(), mEffectChains.size(), this);
6569 if (mEffectChains.size() == 1) {
6570 mEffectChains.removeAt(0);
6571 }
6572 return 0;
6573}
6574
Mathias Agopian65ab4712010-07-14 17:59:35 -07006575// ----------------------------------------------------------------------------
6576// EffectModule implementation
6577// ----------------------------------------------------------------------------
6578
6579#undef LOG_TAG
6580#define LOG_TAG "AudioFlinger::EffectModule"
6581
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006582AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006583 const wp<AudioFlinger::EffectChain>& chain,
6584 effect_descriptor_t *desc,
6585 int id,
6586 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006587 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006588 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006589{
Steve Block3856b092011-10-20 11:56:00 +01006590 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006591 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006592 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006593 return;
6594 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006595
6596 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6597
6598 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006599 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006600
6601 if (mStatus != NO_ERROR) {
6602 return;
6603 }
6604 lStatus = init();
6605 if (lStatus < 0) {
6606 mStatus = lStatus;
6607 goto Error;
6608 }
6609
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006610 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6611 mPinned = true;
6612 }
Steve Block3856b092011-10-20 11:56:00 +01006613 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006614 return;
6615Error:
6616 EffectRelease(mEffectInterface);
6617 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006618 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006619}
6620
6621AudioFlinger::EffectModule::~EffectModule()
6622{
Steve Block3856b092011-10-20 11:56:00 +01006623 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006624 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006625 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6626 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6627 sp<ThreadBase> thread = mThread.promote();
6628 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006629 audio_stream_t *stream = thread->stream();
6630 if (stream != NULL) {
6631 stream->remove_audio_effect(stream, mEffectInterface);
6632 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006633 }
6634 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006635 // release effect engine
6636 EffectRelease(mEffectInterface);
6637 }
6638}
6639
Glenn Kasten435dbe62012-01-30 10:15:48 -08006640status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006641{
6642 status_t status;
6643
6644 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006645 int priority = handle->priority();
6646 size_t size = mHandles.size();
6647 sp<EffectHandle> h;
6648 size_t i;
6649 for (i = 0; i < size; i++) {
6650 h = mHandles[i].promote();
6651 if (h == 0) continue;
6652 if (h->priority() <= priority) break;
6653 }
6654 // if inserted in first place, move effect control from previous owner to this handle
6655 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006656 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006657 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006658 enabled = h->enabled();
6659 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006660 }
Eric Laurent59255e42011-07-27 19:49:51 -07006661 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006662 status = NO_ERROR;
6663 } else {
6664 status = ALREADY_EXISTS;
6665 }
Steve Block3856b092011-10-20 11:56:00 +01006666 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006667 mHandles.insertAt(handle, i);
6668 return status;
6669}
6670
6671size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6672{
6673 Mutex::Autolock _l(mLock);
6674 size_t size = mHandles.size();
6675 size_t i;
6676 for (i = 0; i < size; i++) {
6677 if (mHandles[i] == handle) break;
6678 }
6679 if (i == size) {
6680 return size;
6681 }
Steve Block3856b092011-10-20 11:56:00 +01006682 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006683
6684 bool enabled = false;
6685 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006686 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006687 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006688 enabled = hdl->enabled();
6689 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006690 mHandles.removeAt(i);
6691 size = mHandles.size();
6692 // if removed from first place, move effect control from this handle to next in line
6693 if (i == 0 && size != 0) {
6694 sp<EffectHandle> h = mHandles[0].promote();
6695 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006696 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006697 }
6698 }
6699
Eric Laurentec437d82011-07-26 20:54:46 -07006700 // Prevent calls to process() and other functions on effect interface from now on.
6701 // The effect engine will be released by the destructor when the last strong reference on
6702 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006703 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006704 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006705 }
6706
Mathias Agopian65ab4712010-07-14 17:59:35 -07006707 return size;
6708}
6709
Eric Laurent59255e42011-07-27 19:49:51 -07006710sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6711{
6712 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08006713 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07006714}
6715
Glenn Kasten58123c32012-02-03 10:32:24 -08006716void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006717{
Glenn Kasten90bebef2012-01-27 15:24:38 -08006718 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006719 // keep a strong reference on this EffectModule to avoid calling the
6720 // destructor before we exit
6721 sp<EffectModule> keep(this);
6722 {
6723 sp<ThreadBase> thread = mThread.promote();
6724 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006725 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006726 }
6727 }
6728}
6729
6730void AudioFlinger::EffectModule::updateState() {
6731 Mutex::Autolock _l(mLock);
6732
6733 switch (mState) {
6734 case RESTART:
6735 reset_l();
6736 // FALL THROUGH
6737
6738 case STARTING:
6739 // clear auxiliary effect input buffer for next accumulation
6740 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6741 memset(mConfig.inputCfg.buffer.raw,
6742 0,
6743 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6744 }
6745 start_l();
6746 mState = ACTIVE;
6747 break;
6748 case STOPPING:
6749 stop_l();
6750 mDisableWaitCnt = mMaxDisableWaitCnt;
6751 mState = STOPPED;
6752 break;
6753 case STOPPED:
6754 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6755 // turn off sequence.
6756 if (--mDisableWaitCnt == 0) {
6757 reset_l();
6758 mState = IDLE;
6759 }
6760 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006761 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006762 break;
6763 }
6764}
6765
6766void AudioFlinger::EffectModule::process()
6767{
6768 Mutex::Autolock _l(mLock);
6769
Eric Laurentec437d82011-07-26 20:54:46 -07006770 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006771 mConfig.inputCfg.buffer.raw == NULL ||
6772 mConfig.outputCfg.buffer.raw == NULL) {
6773 return;
6774 }
6775
Eric Laurent8f45bd72010-08-31 13:50:07 -07006776 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006777 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6778 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006779 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006780 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006781 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006782 }
6783
6784 // do the actual processing in the effect engine
6785 int ret = (*mEffectInterface)->process(mEffectInterface,
6786 &mConfig.inputCfg.buffer,
6787 &mConfig.outputCfg.buffer);
6788
6789 // force transition to IDLE state when engine is ready
6790 if (mState == STOPPED && ret == -ENODATA) {
6791 mDisableWaitCnt = 1;
6792 }
6793
6794 // clear auxiliary effect input buffer for next accumulation
6795 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006796 memset(mConfig.inputCfg.buffer.raw, 0,
6797 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006798 }
6799 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006800 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6801 // If an insert effect is idle and input buffer is different from output buffer,
6802 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006803 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006804 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006805 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6806 int16_t *in = mConfig.inputCfg.buffer.s16;
6807 int16_t *out = mConfig.outputCfg.buffer.s16;
6808 for (size_t i = 0; i < frameCnt; i++) {
6809 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006810 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006811 }
6812 }
6813}
6814
6815void AudioFlinger::EffectModule::reset_l()
6816{
6817 if (mEffectInterface == NULL) {
6818 return;
6819 }
6820 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6821}
6822
6823status_t AudioFlinger::EffectModule::configure()
6824{
6825 uint32_t channels;
6826 if (mEffectInterface == NULL) {
6827 return NO_INIT;
6828 }
6829
6830 sp<ThreadBase> thread = mThread.promote();
6831 if (thread == 0) {
6832 return DEAD_OBJECT;
6833 }
6834
6835 // TODO: handle configuration of effects replacing track process
6836 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006837 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006838 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006839 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006840 }
6841
6842 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006843 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006844 } else {
6845 mConfig.inputCfg.channels = channels;
6846 }
6847 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006848 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6849 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006850 mConfig.inputCfg.samplingRate = thread->sampleRate();
6851 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6852 mConfig.inputCfg.bufferProvider.cookie = NULL;
6853 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6854 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6855 mConfig.outputCfg.bufferProvider.cookie = NULL;
6856 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6857 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6858 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6859 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006860 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006861 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006862 // - in other sessions:
6863 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6864 // other effect: overwrites output buffer: input buffer == output buffer
6865 // Auxiliary effect:
6866 // accumulates in output buffer: input buffer != output buffer
6867 // Therefore: accumulate <=> input buffer != output buffer
6868 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6869 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6870 } else {
6871 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6872 }
6873 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6874 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6875 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6876 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6877
Steve Block3856b092011-10-20 11:56:00 +01006878 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006879 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6880
Mathias Agopian65ab4712010-07-14 17:59:35 -07006881 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006882 uint32_t size = sizeof(int);
6883 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006884 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006885 sizeof(effect_config_t),
6886 &mConfig,
6887 &size,
6888 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006889 if (status == 0) {
6890 status = cmdStatus;
6891 }
6892
6893 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6894 (1000 * mConfig.outputCfg.buffer.frameCount);
6895
6896 return status;
6897}
6898
6899status_t AudioFlinger::EffectModule::init()
6900{
6901 Mutex::Autolock _l(mLock);
6902 if (mEffectInterface == NULL) {
6903 return NO_INIT;
6904 }
6905 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006906 uint32_t size = sizeof(status_t);
6907 status_t status = (*mEffectInterface)->command(mEffectInterface,
6908 EFFECT_CMD_INIT,
6909 0,
6910 NULL,
6911 &size,
6912 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006913 if (status == 0) {
6914 status = cmdStatus;
6915 }
6916 return status;
6917}
6918
Eric Laurentec35a142011-10-05 17:42:25 -07006919status_t AudioFlinger::EffectModule::start()
6920{
6921 Mutex::Autolock _l(mLock);
6922 return start_l();
6923}
6924
Mathias Agopian65ab4712010-07-14 17:59:35 -07006925status_t AudioFlinger::EffectModule::start_l()
6926{
6927 if (mEffectInterface == NULL) {
6928 return NO_INIT;
6929 }
6930 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006931 uint32_t size = sizeof(status_t);
6932 status_t status = (*mEffectInterface)->command(mEffectInterface,
6933 EFFECT_CMD_ENABLE,
6934 0,
6935 NULL,
6936 &size,
6937 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006938 if (status == 0) {
6939 status = cmdStatus;
6940 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006941 if (status == 0 &&
6942 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6943 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6944 sp<ThreadBase> thread = mThread.promote();
6945 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006946 audio_stream_t *stream = thread->stream();
6947 if (stream != NULL) {
6948 stream->add_audio_effect(stream, mEffectInterface);
6949 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006950 }
6951 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006952 return status;
6953}
6954
Eric Laurentec437d82011-07-26 20:54:46 -07006955status_t AudioFlinger::EffectModule::stop()
6956{
6957 Mutex::Autolock _l(mLock);
6958 return stop_l();
6959}
6960
Mathias Agopian65ab4712010-07-14 17:59:35 -07006961status_t AudioFlinger::EffectModule::stop_l()
6962{
6963 if (mEffectInterface == NULL) {
6964 return NO_INIT;
6965 }
6966 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006967 uint32_t size = sizeof(status_t);
6968 status_t status = (*mEffectInterface)->command(mEffectInterface,
6969 EFFECT_CMD_DISABLE,
6970 0,
6971 NULL,
6972 &size,
6973 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006974 if (status == 0) {
6975 status = cmdStatus;
6976 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006977 if (status == 0 &&
6978 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6979 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6980 sp<ThreadBase> thread = mThread.promote();
6981 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006982 audio_stream_t *stream = thread->stream();
6983 if (stream != NULL) {
6984 stream->remove_audio_effect(stream, mEffectInterface);
6985 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006986 }
6987 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006988 return status;
6989}
6990
Eric Laurent25f43952010-07-28 05:40:18 -07006991status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6992 uint32_t cmdSize,
6993 void *pCmdData,
6994 uint32_t *replySize,
6995 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006996{
6997 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006998// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006999
Eric Laurentec437d82011-07-26 20:54:46 -07007000 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007001 return NO_INIT;
7002 }
Eric Laurent25f43952010-07-28 05:40:18 -07007003 status_t status = (*mEffectInterface)->command(mEffectInterface,
7004 cmdCode,
7005 cmdSize,
7006 pCmdData,
7007 replySize,
7008 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007009 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07007010 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007011 for (size_t i = 1; i < mHandles.size(); i++) {
7012 sp<EffectHandle> h = mHandles[i].promote();
7013 if (h != 0) {
7014 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
7015 }
7016 }
7017 }
7018 return status;
7019}
7020
7021status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
7022{
Eric Laurentdb7c0792011-08-10 10:37:50 -07007023
Mathias Agopian65ab4712010-07-14 17:59:35 -07007024 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007025 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007026
7027 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007028 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
7029 if (enabled && status != NO_ERROR) {
7030 return status;
7031 }
7032
Mathias Agopian65ab4712010-07-14 17:59:35 -07007033 switch (mState) {
7034 // going from disabled to enabled
7035 case IDLE:
7036 mState = STARTING;
7037 break;
7038 case STOPPED:
7039 mState = RESTART;
7040 break;
7041 case STOPPING:
7042 mState = ACTIVE;
7043 break;
7044
7045 // going from enabled to disabled
7046 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007047 mState = STOPPED;
7048 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007049 case STARTING:
7050 mState = IDLE;
7051 break;
7052 case ACTIVE:
7053 mState = STOPPING;
7054 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007055 case DESTROYED:
7056 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007057 }
7058 for (size_t i = 1; i < mHandles.size(); i++) {
7059 sp<EffectHandle> h = mHandles[i].promote();
7060 if (h != 0) {
7061 h->setEnabled(enabled);
7062 }
7063 }
7064 }
7065 return NO_ERROR;
7066}
7067
Glenn Kastenc59c0042012-02-02 14:06:11 -08007068bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007069{
7070 switch (mState) {
7071 case RESTART:
7072 case STARTING:
7073 case ACTIVE:
7074 return true;
7075 case IDLE:
7076 case STOPPING:
7077 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07007078 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07007079 default:
7080 return false;
7081 }
7082}
7083
Glenn Kastenc59c0042012-02-02 14:06:11 -08007084bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07007085{
7086 switch (mState) {
7087 case RESTART:
7088 case ACTIVE:
7089 case STOPPING:
7090 case STOPPED:
7091 return true;
7092 case IDLE:
7093 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07007094 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007095 default:
7096 return false;
7097 }
7098}
7099
Mathias Agopian65ab4712010-07-14 17:59:35 -07007100status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7101{
7102 Mutex::Autolock _l(mLock);
7103 status_t status = NO_ERROR;
7104
7105 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7106 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07007107 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07007108 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7109 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007110 status_t cmdStatus;
7111 uint32_t volume[2];
7112 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07007113 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007114 volume[0] = *left;
7115 volume[1] = *right;
7116 if (controller) {
7117 pVolume = volume;
7118 }
Eric Laurent25f43952010-07-28 05:40:18 -07007119 status = (*mEffectInterface)->command(mEffectInterface,
7120 EFFECT_CMD_SET_VOLUME,
7121 size,
7122 volume,
7123 &size,
7124 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007125 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7126 *left = volume[0];
7127 *right = volume[1];
7128 }
7129 }
7130 return status;
7131}
7132
7133status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7134{
7135 Mutex::Autolock _l(mLock);
7136 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007137 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7138 // audio pre processing modules on RecordThread can receive both output and
7139 // input device indication in the same call
7140 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7141 if (dev) {
7142 status_t cmdStatus;
7143 uint32_t size = sizeof(status_t);
7144
7145 status = (*mEffectInterface)->command(mEffectInterface,
7146 EFFECT_CMD_SET_DEVICE,
7147 sizeof(uint32_t),
7148 &dev,
7149 &size,
7150 &cmdStatus);
7151 if (status == NO_ERROR) {
7152 status = cmdStatus;
7153 }
7154 }
7155 dev = device & AUDIO_DEVICE_IN_ALL;
7156 if (dev) {
7157 status_t cmdStatus;
7158 uint32_t size = sizeof(status_t);
7159
7160 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7161 EFFECT_CMD_SET_INPUT_DEVICE,
7162 sizeof(uint32_t),
7163 &dev,
7164 &size,
7165 &cmdStatus);
7166 if (status2 == NO_ERROR) {
7167 status2 = cmdStatus;
7168 }
7169 if (status == NO_ERROR) {
7170 status = status2;
7171 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007172 }
7173 }
7174 return status;
7175}
7176
Glenn Kastenf78aee72012-01-04 11:00:47 -08007177status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007178{
7179 Mutex::Autolock _l(mLock);
7180 status_t status = NO_ERROR;
7181 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007182 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007183 uint32_t size = sizeof(status_t);
7184 status = (*mEffectInterface)->command(mEffectInterface,
7185 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08007186 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07007187 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07007188 &size,
7189 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007190 if (status == NO_ERROR) {
7191 status = cmdStatus;
7192 }
7193 }
7194 return status;
7195}
7196
Eric Laurent59255e42011-07-27 19:49:51 -07007197void AudioFlinger::EffectModule::setSuspended(bool suspended)
7198{
7199 Mutex::Autolock _l(mLock);
7200 mSuspended = suspended;
7201}
Glenn Kastena3a85482012-01-04 11:01:11 -08007202
7203bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07007204{
7205 Mutex::Autolock _l(mLock);
7206 return mSuspended;
7207}
7208
Mathias Agopian65ab4712010-07-14 17:59:35 -07007209status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7210{
7211 const size_t SIZE = 256;
7212 char buffer[SIZE];
7213 String8 result;
7214
7215 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7216 result.append(buffer);
7217
7218 bool locked = tryLock(mLock);
7219 // failed to lock - AudioFlinger is probably deadlocked
7220 if (!locked) {
7221 result.append("\t\tCould not lock Fx mutex:\n");
7222 }
7223
7224 result.append("\t\tSession Status State Engine:\n");
7225 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7226 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7227 result.append(buffer);
7228
7229 result.append("\t\tDescriptor:\n");
7230 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7231 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7232 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7233 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7234 result.append(buffer);
7235 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7236 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7237 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7238 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7239 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07007240 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007241 mDescriptor.apiVersion,
7242 mDescriptor.flags);
7243 result.append(buffer);
7244 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7245 mDescriptor.name);
7246 result.append(buffer);
7247 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7248 mDescriptor.implementor);
7249 result.append(buffer);
7250
7251 result.append("\t\t- Input configuration:\n");
7252 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7253 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7254 (uint32_t)mConfig.inputCfg.buffer.raw,
7255 mConfig.inputCfg.buffer.frameCount,
7256 mConfig.inputCfg.samplingRate,
7257 mConfig.inputCfg.channels,
7258 mConfig.inputCfg.format);
7259 result.append(buffer);
7260
7261 result.append("\t\t- Output configuration:\n");
7262 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7263 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7264 (uint32_t)mConfig.outputCfg.buffer.raw,
7265 mConfig.outputCfg.buffer.frameCount,
7266 mConfig.outputCfg.samplingRate,
7267 mConfig.outputCfg.channels,
7268 mConfig.outputCfg.format);
7269 result.append(buffer);
7270
7271 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7272 result.append(buffer);
7273 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7274 for (size_t i = 0; i < mHandles.size(); ++i) {
7275 sp<EffectHandle> handle = mHandles[i].promote();
7276 if (handle != 0) {
7277 handle->dump(buffer, SIZE);
7278 result.append(buffer);
7279 }
7280 }
7281
7282 result.append("\n");
7283
7284 write(fd, result.string(), result.length());
7285
7286 if (locked) {
7287 mLock.unlock();
7288 }
7289
7290 return NO_ERROR;
7291}
7292
7293// ----------------------------------------------------------------------------
7294// EffectHandle implementation
7295// ----------------------------------------------------------------------------
7296
7297#undef LOG_TAG
7298#define LOG_TAG "AudioFlinger::EffectHandle"
7299
7300AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7301 const sp<AudioFlinger::Client>& client,
7302 const sp<IEffectClient>& effectClient,
7303 int32_t priority)
7304 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007305 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007306 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007307{
Steve Block3856b092011-10-20 11:56:00 +01007308 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007309
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007310 if (client == 0) {
7311 return;
7312 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007313 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7314 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7315 if (mCblkMemory != 0) {
7316 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7317
Glenn Kastena0d68332012-01-27 16:47:15 -08007318 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007319 new(mCblk) effect_param_cblk_t();
7320 mBuffer = (uint8_t *)mCblk + bufOffset;
7321 }
7322 } else {
Steve Block29357bc2012-01-06 19:20:56 +00007323 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007324 return;
7325 }
7326}
7327
7328AudioFlinger::EffectHandle::~EffectHandle()
7329{
Steve Block3856b092011-10-20 11:56:00 +01007330 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007331 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01007332 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007333}
7334
7335status_t AudioFlinger::EffectHandle::enable()
7336{
Steve Block3856b092011-10-20 11:56:00 +01007337 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007338 if (!mHasControl) return INVALID_OPERATION;
7339 if (mEffect == 0) return DEAD_OBJECT;
7340
Eric Laurentdb7c0792011-08-10 10:37:50 -07007341 if (mEnabled) {
7342 return NO_ERROR;
7343 }
7344
Eric Laurent59255e42011-07-27 19:49:51 -07007345 mEnabled = true;
7346
7347 sp<ThreadBase> thread = mEffect->thread().promote();
7348 if (thread != 0) {
7349 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7350 }
7351
7352 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7353 if (mEffect->suspended()) {
7354 return NO_ERROR;
7355 }
7356
Eric Laurentdb7c0792011-08-10 10:37:50 -07007357 status_t status = mEffect->setEnabled(true);
7358 if (status != NO_ERROR) {
7359 if (thread != 0) {
7360 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7361 }
7362 mEnabled = false;
7363 }
7364 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007365}
7366
7367status_t AudioFlinger::EffectHandle::disable()
7368{
Steve Block3856b092011-10-20 11:56:00 +01007369 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007370 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07007371 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007372
Eric Laurentdb7c0792011-08-10 10:37:50 -07007373 if (!mEnabled) {
7374 return NO_ERROR;
7375 }
Eric Laurent59255e42011-07-27 19:49:51 -07007376 mEnabled = false;
7377
7378 if (mEffect->suspended()) {
7379 return NO_ERROR;
7380 }
7381
7382 status_t status = mEffect->setEnabled(false);
7383
7384 sp<ThreadBase> thread = mEffect->thread().promote();
7385 if (thread != 0) {
7386 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7387 }
7388
7389 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007390}
7391
7392void AudioFlinger::EffectHandle::disconnect()
7393{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007394 disconnect(true);
7395}
7396
Glenn Kasten58123c32012-02-03 10:32:24 -08007397void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007398{
Glenn Kasten58123c32012-02-03 10:32:24 -08007399 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007400 if (mEffect == 0) {
7401 return;
7402 }
Glenn Kasten58123c32012-02-03 10:32:24 -08007403 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07007404
Eric Laurenta85a74a2011-10-19 11:44:54 -07007405 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007406 sp<ThreadBase> thread = mEffect->thread().promote();
7407 if (thread != 0) {
7408 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7409 }
Eric Laurent59255e42011-07-27 19:49:51 -07007410 }
7411
Mathias Agopian65ab4712010-07-14 17:59:35 -07007412 // release sp on module => module destructor can be called now
7413 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007414 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08007415 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08007416 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007417 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7418 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08007419 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007420 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07007421 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7422 mClient.clear();
7423 }
7424}
7425
Eric Laurent25f43952010-07-28 05:40:18 -07007426status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7427 uint32_t cmdSize,
7428 void *pCmdData,
7429 uint32_t *replySize,
7430 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007431{
Steve Block3856b092011-10-20 11:56:00 +01007432// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07007433// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007434
7435 // only get parameter command is permitted for applications not controlling the effect
7436 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7437 return INVALID_OPERATION;
7438 }
7439 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007440 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007441
7442 // handle commands that are not forwarded transparently to effect engine
7443 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7444 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7445 // no risk to block the whole media server process or mixer threads is we are stuck here
7446 Mutex::Autolock _l(mCblk->lock);
7447 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7448 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7449 mCblk->serverIndex = 0;
7450 mCblk->clientIndex = 0;
7451 return BAD_VALUE;
7452 }
7453 status_t status = NO_ERROR;
7454 while (mCblk->serverIndex < mCblk->clientIndex) {
7455 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007456 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007457 int *p = (int *)(mBuffer + mCblk->serverIndex);
7458 int size = *p++;
7459 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007460 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007461 break;
7462 }
7463 effect_param_t *param = (effect_param_t *)p;
7464 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007465 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007466 mCblk->serverIndex += size;
7467 continue;
7468 }
Eric Laurent25f43952010-07-28 05:40:18 -07007469 uint32_t psize = sizeof(effect_param_t) +
7470 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7471 param->vsize;
7472 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7473 psize,
7474 p,
7475 &rsize,
7476 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007477 // stop at first error encountered
7478 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007479 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007480 *(int *)pReplyData = reply;
7481 break;
7482 } else if (reply != NO_ERROR) {
7483 *(int *)pReplyData = reply;
7484 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007485 }
7486 mCblk->serverIndex += size;
7487 }
7488 mCblk->serverIndex = 0;
7489 mCblk->clientIndex = 0;
7490 return status;
7491 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007492 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007493 return enable();
7494 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007495 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007496 return disable();
7497 }
7498
7499 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7500}
7501
Eric Laurent59255e42011-07-27 19:49:51 -07007502void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007503{
Steve Block3856b092011-10-20 11:56:00 +01007504 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007505
7506 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007507 mEnabled = enabled;
7508
Mathias Agopian65ab4712010-07-14 17:59:35 -07007509 if (signal && mEffectClient != 0) {
7510 mEffectClient->controlStatusChanged(hasControl);
7511 }
7512}
7513
Eric Laurent25f43952010-07-28 05:40:18 -07007514void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7515 uint32_t cmdSize,
7516 void *pCmdData,
7517 uint32_t replySize,
7518 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007519{
7520 if (mEffectClient != 0) {
7521 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7522 }
7523}
7524
7525
7526
7527void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7528{
7529 if (mEffectClient != 0) {
7530 mEffectClient->enableStatusChanged(enabled);
7531 }
7532}
7533
7534status_t AudioFlinger::EffectHandle::onTransact(
7535 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7536{
7537 return BnEffect::onTransact(code, data, reply, flags);
7538}
7539
7540
7541void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7542{
Glenn Kastena0d68332012-01-27 16:47:15 -08007543 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007544
7545 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08007546 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007547 mPriority,
7548 mHasControl,
7549 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007550 mCblk ? mCblk->clientIndex : 0,
7551 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007552 );
7553
7554 if (locked) {
7555 mCblk->lock.unlock();
7556 }
7557}
7558
7559#undef LOG_TAG
7560#define LOG_TAG "AudioFlinger::EffectChain"
7561
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007562AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007563 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007564 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007565 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7566 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007567{
Dima Zavinfce7a472011-04-19 22:30:36 -07007568 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007569 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007570 return;
7571 }
7572 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7573 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007574}
7575
7576AudioFlinger::EffectChain::~EffectChain()
7577{
7578 if (mOwnInBuffer) {
7579 delete mInBuffer;
7580 }
7581
7582}
7583
Eric Laurent59255e42011-07-27 19:49:51 -07007584// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007585sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007586{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007587 size_t size = mEffects.size();
7588
7589 for (size_t i = 0; i < size; i++) {
7590 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007591 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007592 }
7593 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007594 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007595}
7596
Eric Laurent59255e42011-07-27 19:49:51 -07007597// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007598sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007599{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007600 size_t size = mEffects.size();
7601
7602 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007603 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7604 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007605 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007606 }
7607 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007608 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007609}
7610
Eric Laurent59255e42011-07-27 19:49:51 -07007611// getEffectFromType_l() must be called with ThreadBase::mLock held
7612sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7613 const effect_uuid_t *type)
7614{
Eric Laurent59255e42011-07-27 19:49:51 -07007615 size_t size = mEffects.size();
7616
7617 for (size_t i = 0; i < size; i++) {
7618 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007619 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007620 }
7621 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007622 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007623}
7624
Mathias Agopian65ab4712010-07-14 17:59:35 -07007625// Must be called with EffectChain::mLock locked
7626void AudioFlinger::EffectChain::process_l()
7627{
Eric Laurentdac69112010-09-28 14:09:57 -07007628 sp<ThreadBase> thread = mThread.promote();
7629 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007630 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007631 return;
7632 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007633 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7634 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007635 // always process effects unless no more tracks are on the session and the effect tail
7636 // has been rendered
7637 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007638 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007639 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007640
Eric Laurent544fe9b2011-11-11 15:42:52 -08007641 if (!tracksOnSession && mTailBufferCount == 0) {
7642 doProcess = false;
7643 }
7644
7645 if (activeTrackCnt() == 0) {
7646 // if no track is active and the effect tail has not been rendered,
7647 // the input buffer must be cleared here as the mixer process will not do it
7648 if (tracksOnSession || mTailBufferCount > 0) {
7649 size_t numSamples = thread->frameCount() * thread->channelCount();
7650 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7651 if (mTailBufferCount > 0) {
7652 mTailBufferCount--;
7653 }
7654 }
7655 }
Eric Laurentdac69112010-09-28 14:09:57 -07007656 }
7657
Mathias Agopian65ab4712010-07-14 17:59:35 -07007658 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007659 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007660 for (size_t i = 0; i < size; i++) {
7661 mEffects[i]->process();
7662 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007663 }
7664 for (size_t i = 0; i < size; i++) {
7665 mEffects[i]->updateState();
7666 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007667}
7668
Eric Laurentcab11242010-07-15 12:50:15 -07007669// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007670status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007671{
7672 effect_descriptor_t desc = effect->desc();
7673 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7674
7675 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007676 effect->setChain(this);
7677 sp<ThreadBase> thread = mThread.promote();
7678 if (thread == 0) {
7679 return NO_INIT;
7680 }
7681 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007682
7683 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7684 // Auxiliary effects are inserted at the beginning of mEffects vector as
7685 // they are processed first and accumulated in chain input buffer
7686 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007687
Mathias Agopian65ab4712010-07-14 17:59:35 -07007688 // the input buffer for auxiliary effect contains mono samples in
7689 // 32 bit format. This is to avoid saturation in AudoMixer
7690 // accumulation stage. Saturation is done in EffectModule::process() before
7691 // calling the process in effect engine
7692 size_t numSamples = thread->frameCount();
7693 int32_t *buffer = new int32_t[numSamples];
7694 memset(buffer, 0, numSamples * sizeof(int32_t));
7695 effect->setInBuffer((int16_t *)buffer);
7696 // auxiliary effects output samples to chain input buffer for further processing
7697 // by insert effects
7698 effect->setOutBuffer(mInBuffer);
7699 } else {
7700 // Insert effects are inserted at the end of mEffects vector as they are processed
7701 // after track and auxiliary effects.
7702 // Insert effect order as a function of indicated preference:
7703 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7704 // another effect is present
7705 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7706 // last effect claiming first position
7707 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7708 // first effect claiming last position
7709 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7710 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7711 // already present
7712
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007713 size_t size = mEffects.size();
7714 size_t idx_insert = size;
7715 ssize_t idx_insert_first = -1;
7716 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007717
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007718 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007719 effect_descriptor_t d = mEffects[i]->desc();
7720 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7721 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7722 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7723 // check invalid effect chaining combinations
7724 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7725 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007726 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007727 return INVALID_OPERATION;
7728 }
7729 // remember position of first insert effect and by default
7730 // select this as insert position for new effect
7731 if (idx_insert == size) {
7732 idx_insert = i;
7733 }
7734 // remember position of last insert effect claiming
7735 // first position
7736 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7737 idx_insert_first = i;
7738 }
7739 // remember position of first insert effect claiming
7740 // last position
7741 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7742 idx_insert_last == -1) {
7743 idx_insert_last = i;
7744 }
7745 }
7746 }
7747
7748 // modify idx_insert from first position if needed
7749 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7750 if (idx_insert_last != -1) {
7751 idx_insert = idx_insert_last;
7752 } else {
7753 idx_insert = size;
7754 }
7755 } else {
7756 if (idx_insert_first != -1) {
7757 idx_insert = idx_insert_first + 1;
7758 }
7759 }
7760
7761 // always read samples from chain input buffer
7762 effect->setInBuffer(mInBuffer);
7763
7764 // if last effect in the chain, output samples to chain
7765 // output buffer, otherwise to chain input buffer
7766 if (idx_insert == size) {
7767 if (idx_insert != 0) {
7768 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7769 mEffects[idx_insert-1]->configure();
7770 }
7771 effect->setOutBuffer(mOutBuffer);
7772 } else {
7773 effect->setOutBuffer(mInBuffer);
7774 }
7775 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007776
Steve Block3856b092011-10-20 11:56:00 +01007777 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007778 }
7779 effect->configure();
7780 return NO_ERROR;
7781}
7782
Eric Laurentcab11242010-07-15 12:50:15 -07007783// removeEffect_l() must be called with PlaybackThread::mLock held
7784size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007785{
7786 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007787 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007788 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7789
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007790 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007791 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007792 // calling stop here will remove pre-processing effect from the audio HAL.
7793 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7794 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007795 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7796 mEffects[i]->state() == EffectModule::STOPPING) {
7797 mEffects[i]->stop();
7798 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007799 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7800 delete[] effect->inBuffer();
7801 } else {
7802 if (i == size - 1 && i != 0) {
7803 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7804 mEffects[i - 1]->configure();
7805 }
7806 }
7807 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007808 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007809 break;
7810 }
7811 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007812
7813 return mEffects.size();
7814}
7815
Eric Laurentcab11242010-07-15 12:50:15 -07007816// setDevice_l() must be called with PlaybackThread::mLock held
7817void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007818{
7819 size_t size = mEffects.size();
7820 for (size_t i = 0; i < size; i++) {
7821 mEffects[i]->setDevice(device);
7822 }
7823}
7824
Eric Laurentcab11242010-07-15 12:50:15 -07007825// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007826void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007827{
7828 size_t size = mEffects.size();
7829 for (size_t i = 0; i < size; i++) {
7830 mEffects[i]->setMode(mode);
7831 }
7832}
7833
Eric Laurentcab11242010-07-15 12:50:15 -07007834// setVolume_l() must be called with PlaybackThread::mLock held
7835bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007836{
7837 uint32_t newLeft = *left;
7838 uint32_t newRight = *right;
7839 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007840 int ctrlIdx = -1;
7841 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007842
Eric Laurentcab11242010-07-15 12:50:15 -07007843 // first update volume controller
7844 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007845 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007846 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7847 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007848 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007849 break;
7850 }
7851 }
7852
7853 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007854 if (hasControl) {
7855 *left = mNewLeftVolume;
7856 *right = mNewRightVolume;
7857 }
7858 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007859 }
7860
7861 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007862 mLeftVolume = newLeft;
7863 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007864
7865 // second get volume update from volume controller
7866 if (ctrlIdx >= 0) {
7867 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007868 mNewLeftVolume = newLeft;
7869 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007870 }
7871 // then indicate volume to all other effects in chain.
7872 // Pass altered volume to effects before volume controller
7873 // and requested volume to effects after controller
7874 uint32_t lVol = newLeft;
7875 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007876
Mathias Agopian65ab4712010-07-14 17:59:35 -07007877 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007878 if ((int)i == ctrlIdx) continue;
7879 // this also works for ctrlIdx == -1 when there is no volume controller
7880 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007881 lVol = *left;
7882 rVol = *right;
7883 }
7884 mEffects[i]->setVolume(&lVol, &rVol, false);
7885 }
7886 *left = newLeft;
7887 *right = newRight;
7888
7889 return hasControl;
7890}
7891
Mathias Agopian65ab4712010-07-14 17:59:35 -07007892status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7893{
7894 const size_t SIZE = 256;
7895 char buffer[SIZE];
7896 String8 result;
7897
7898 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7899 result.append(buffer);
7900
7901 bool locked = tryLock(mLock);
7902 // failed to lock - AudioFlinger is probably deadlocked
7903 if (!locked) {
7904 result.append("\tCould not lock mutex:\n");
7905 }
7906
Eric Laurentcab11242010-07-15 12:50:15 -07007907 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7908 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007909 mEffects.size(),
7910 (uint32_t)mInBuffer,
7911 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007912 mActiveTrackCnt);
7913 result.append(buffer);
7914 write(fd, result.string(), result.size());
7915
7916 for (size_t i = 0; i < mEffects.size(); ++i) {
7917 sp<EffectModule> effect = mEffects[i];
7918 if (effect != 0) {
7919 effect->dump(fd, args);
7920 }
7921 }
7922
7923 if (locked) {
7924 mLock.unlock();
7925 }
7926
7927 return NO_ERROR;
7928}
7929
Eric Laurent59255e42011-07-27 19:49:51 -07007930// must be called with ThreadBase::mLock held
7931void AudioFlinger::EffectChain::setEffectSuspended_l(
7932 const effect_uuid_t *type, bool suspend)
7933{
7934 sp<SuspendedEffectDesc> desc;
7935 // use effect type UUID timelow as key as there is no real risk of identical
7936 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007937 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007938 if (suspend) {
7939 if (index >= 0) {
7940 desc = mSuspendedEffects.valueAt(index);
7941 } else {
7942 desc = new SuspendedEffectDesc();
7943 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7944 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007945 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007946 }
7947 if (desc->mRefCount++ == 0) {
7948 sp<EffectModule> effect = getEffectIfEnabled(type);
7949 if (effect != 0) {
7950 desc->mEffect = effect;
7951 effect->setSuspended(true);
7952 effect->setEnabled(false);
7953 }
7954 }
7955 } else {
7956 if (index < 0) {
7957 return;
7958 }
7959 desc = mSuspendedEffects.valueAt(index);
7960 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007961 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007962 desc->mRefCount = 1;
7963 }
7964 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007965 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007966 if (desc->mEffect != 0) {
7967 sp<EffectModule> effect = desc->mEffect.promote();
7968 if (effect != 0) {
7969 effect->setSuspended(false);
7970 sp<EffectHandle> handle = effect->controlHandle();
7971 if (handle != 0) {
7972 effect->setEnabled(handle->enabled());
7973 }
7974 }
7975 desc->mEffect.clear();
7976 }
7977 mSuspendedEffects.removeItemsAt(index);
7978 }
7979 }
7980}
7981
7982// must be called with ThreadBase::mLock held
7983void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7984{
7985 sp<SuspendedEffectDesc> desc;
7986
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007987 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07007988 if (suspend) {
7989 if (index >= 0) {
7990 desc = mSuspendedEffects.valueAt(index);
7991 } else {
7992 desc = new SuspendedEffectDesc();
7993 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007994 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007995 }
7996 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08007997 Vector< sp<EffectModule> > effects;
7998 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07007999 for (size_t i = 0; i < effects.size(); i++) {
8000 setEffectSuspended_l(&effects[i]->desc().type, true);
8001 }
8002 }
8003 } else {
8004 if (index < 0) {
8005 return;
8006 }
8007 desc = mSuspendedEffects.valueAt(index);
8008 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008009 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008010 desc->mRefCount = 1;
8011 }
8012 if (--desc->mRefCount == 0) {
8013 Vector<const effect_uuid_t *> types;
8014 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
8015 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
8016 continue;
8017 }
8018 types.add(&mSuspendedEffects.valueAt(i)->mType);
8019 }
8020 for (size_t i = 0; i < types.size(); i++) {
8021 setEffectSuspended_l(types[i], false);
8022 }
Steve Block3856b092011-10-20 11:56:00 +01008023 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008024 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
8025 }
8026 }
8027}
8028
Eric Laurent6bffdb82011-09-23 08:40:41 -07008029
8030// The volume effect is used for automated tests only
8031#ifndef OPENSL_ES_H_
8032static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
8033 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
8034const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
8035#endif //OPENSL_ES_H_
8036
Eric Laurentdb7c0792011-08-10 10:37:50 -07008037bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
8038{
8039 // auxiliary effects and visualizer are never suspended on output mix
8040 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8041 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07008042 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8043 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008044 return false;
8045 }
8046 return true;
8047}
8048
Glenn Kastend0539712012-01-30 12:56:03 -08008049void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07008050{
Glenn Kastend0539712012-01-30 12:56:03 -08008051 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07008052 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08008053 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8054 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07008055 }
Eric Laurent59255e42011-07-27 19:49:51 -07008056 }
Eric Laurent59255e42011-07-27 19:49:51 -07008057}
8058
8059sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8060 const effect_uuid_t *type)
8061{
Glenn Kasten090f0192012-01-30 13:00:02 -08008062 sp<EffectModule> effect = getEffectFromType_l(type);
8063 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008064}
8065
8066void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8067 bool enabled)
8068{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008069 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008070 if (enabled) {
8071 if (index < 0) {
8072 // if the effect is not suspend check if all effects are suspended
8073 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8074 if (index < 0) {
8075 return;
8076 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07008077 if (!isEffectEligibleForSuspend(effect->desc())) {
8078 return;
8079 }
Eric Laurent59255e42011-07-27 19:49:51 -07008080 setEffectSuspended_l(&effect->desc().type, enabled);
8081 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07008082 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008083 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07008084 return;
8085 }
Eric Laurent59255e42011-07-27 19:49:51 -07008086 }
Steve Block3856b092011-10-20 11:56:00 +01008087 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07008088 effect->desc().type.timeLow);
8089 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8090 // if effect is requested to suspended but was not yet enabled, supend it now.
8091 if (desc->mEffect == 0) {
8092 desc->mEffect = effect;
8093 effect->setEnabled(false);
8094 effect->setSuspended(true);
8095 }
8096 } else {
8097 if (index < 0) {
8098 return;
8099 }
Steve Block3856b092011-10-20 11:56:00 +01008100 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07008101 effect->desc().type.timeLow);
8102 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8103 desc->mEffect.clear();
8104 effect->setSuspended(false);
8105 }
8106}
8107
Mathias Agopian65ab4712010-07-14 17:59:35 -07008108#undef LOG_TAG
8109#define LOG_TAG "AudioFlinger"
8110
8111// ----------------------------------------------------------------------------
8112
8113status_t AudioFlinger::onTransact(
8114 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8115{
8116 return BnAudioFlinger::onTransact(code, data, reply, flags);
8117}
8118
Mathias Agopian65ab4712010-07-14 17:59:35 -07008119}; // namespace android