blob: e3dbe01583b6dc1b2a3e683514d1d0807dcaaa56 [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
Eric Laurentfeb0db62011-07-22 09:04:31 -070060#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080061
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070062// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080063#ifdef DEBUG_CPU_USAGE
64#include <cpustats/CentralTendencyStatistics.h>
65#include <cpustats/ThreadCpuUsage.h>
66#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070067
John Grossman4ff14ba2012-02-08 16:37:41 -080068#include <common_time/cc_helper.h>
69#include <common_time/local_clock.h>
70
Mathias Agopian65ab4712010-07-14 17:59:35 -070071// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070072
Eric Laurentde070132010-07-13 04:45:46 -070073
Mathias Agopian65ab4712010-07-14 17:59:35 -070074namespace android {
75
Glenn Kastenec1d6b52011-12-12 09:04:45 -080076static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
77static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070078
Mathias Agopian65ab4712010-07-14 17:59:35 -070079static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -080080static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070081
82// retry counts for buffer fill timeout
83// 50 * ~20msecs = 1 second
84static const int8_t kMaxTrackRetries = 50;
85static const int8_t kMaxTrackStartupRetries = 50;
86// allow less retry attempts on direct output thread.
87// direct outputs can be a scarce resource in audio hardware and should
88// be released as quickly as possible.
89static const int8_t kMaxTrackRetriesDirect = 2;
90
91static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -080092static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070093
Glenn Kasten7dede872011-12-13 11:04:14 -080094// don't warn about blocked writes or record buffer overflows more often than this
95static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -070096
Eric Laurent7c7f10b2011-06-17 21:29:58 -070097// RecordThread loop sleep time upon application overrun or audio HAL read error
98static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070099
Glenn Kasten7dede872011-12-13 11:04:14 -0800100// maximum time to wait for setParameters to complete
101static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700102
Eric Laurent7cafbb32011-11-22 18:50:29 -0800103// minimum sleep time for the mixer thread loop when tracks are active but in underrun
104static const uint32_t kMinThreadSleepTimeUs = 5000;
105// maximum divider applied to the active sleep time in the mixer thread loop
106static const uint32_t kMaxThreadSleepTimeShift = 2;
107
John Grossman4ff14ba2012-02-08 16:37:41 -0800108nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800109
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110// ----------------------------------------------------------------------------
111
Gloria Wang9ee159b2011-02-24 14:51:45 -0800112// To collect the amplifier usage
113static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800114 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
115 if (service == NULL) {
116 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800117 return;
118 }
119
120 service->addBatteryData(params);
121}
122
Dima Zavin799a70e2011-04-18 16:57:27 -0700123static int load_audio_interface(const char *if_name, const hw_module_t **mod,
124 audio_hw_device_t **dev)
125{
126 int rc;
127
128 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
129 if (rc)
130 goto out;
131
132 rc = audio_hw_device_open(*mod, dev);
Steve Block29357bc2012-01-06 19:20:56 +0000133 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin799a70e2011-04-18 16:57:27 -0700134 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
135 if (rc)
136 goto out;
137
138 return 0;
139
140out:
141 *mod = NULL;
142 *dev = NULL;
143 return rc;
144}
145
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800146static const char * const audio_interfaces[] = {
Dima Zavin799a70e2011-04-18 16:57:27 -0700147 "primary",
148 "a2dp",
149 "usb",
150};
151#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
152
Mathias Agopian65ab4712010-07-14 17:59:35 -0700153// ----------------------------------------------------------------------------
154
155AudioFlinger::AudioFlinger()
156 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800157 mPrimaryHardwareDev(NULL),
158 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
159 mMasterVolume(1.0f),
160 mMasterVolumeSupportLvl(MVS_NONE),
161 mMasterMute(false),
162 mNextUniqueId(1),
163 mMode(AUDIO_MODE_INVALID),
164 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700165{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700166}
167
168void AudioFlinger::onFirstRef()
169{
Dima Zavin799a70e2011-04-18 16:57:27 -0700170 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700171
Eric Laurent93575202011-01-18 18:39:02 -0800172 Mutex::Autolock _l(mLock);
173
Dima Zavin799a70e2011-04-18 16:57:27 -0700174 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800175 char val_str[PROPERTY_VALUE_MAX] = { 0 };
176 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
177 uint32_t int_val;
178 if (1 == sscanf(val_str, "%u", &int_val)) {
179 mStandbyTimeInNsecs = milliseconds(int_val);
180 ALOGI("Using %u mSec as standby time.", int_val);
181 } else {
182 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
183 ALOGI("Using default %u mSec as standby time.",
184 (uint32_t)(mStandbyTimeInNsecs / 1000000));
185 }
186 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700187
Dima Zavin799a70e2011-04-18 16:57:27 -0700188 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
189 const hw_module_t *mod;
190 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700191
Dima Zavin799a70e2011-04-18 16:57:27 -0700192 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
193 if (rc)
194 continue;
195
Steve Blockdf64d152012-01-04 20:05:49 +0000196 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700197 mod->name, mod->id);
Dima Zavin799a70e2011-04-18 16:57:27 -0700198 mAudioHwDevs.push(dev);
199
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800200 if (mPrimaryHardwareDev == NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700201 mPrimaryHardwareDev = dev;
Steve Blockdf64d152012-01-04 20:05:49 +0000202 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700203 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700204 }
205 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700206
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800207 if (mPrimaryHardwareDev == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000208 ALOGE("Primary audio interface not found");
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800209 // proceed, all later accesses to mPrimaryHardwareDev verify it's safe with initCheck()
Dima Zavin799a70e2011-04-18 16:57:27 -0700210 }
211
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800212 // Currently (mPrimaryHardwareDev == NULL) == (mAudioHwDevs.size() == 0), but the way the
213 // primary HW dev is selected can change so these conditions might not always be equivalent.
214 // When that happens, re-visit all the code that assumes this.
215
216 AutoMutex lock(mHardwareLock);
217
John Grossman4ff14ba2012-02-08 16:37:41 -0800218 // Determine the level of master volume support the primary audio HAL has,
219 // and set the initial master volume at the same time.
220 float initialVolume = 1.0;
221 mMasterVolumeSupportLvl = MVS_NONE;
222 if (0 == mPrimaryHardwareDev->init_check(mPrimaryHardwareDev)) {
223 audio_hw_device_t *dev = mPrimaryHardwareDev;
224
225 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
226 if ((NULL != dev->get_master_volume) &&
227 (NO_ERROR == dev->get_master_volume(dev, &initialVolume))) {
228 mMasterVolumeSupportLvl = MVS_FULL;
229 } else {
230 mMasterVolumeSupportLvl = MVS_SETONLY;
231 initialVolume = 1.0;
232 }
233
234 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
235 if ((NULL == dev->set_master_volume) ||
236 (NO_ERROR != dev->set_master_volume(dev, initialVolume))) {
237 mMasterVolumeSupportLvl = MVS_NONE;
238 }
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800239 mHardwareStatus = AUDIO_HW_IDLE;
John Grossman4ff14ba2012-02-08 16:37:41 -0800240 }
241
242 // Set the mode for each audio HAL, and try to set the initial volume (if
243 // supported) for all of the non-primary audio HALs.
Dima Zavin799a70e2011-04-18 16:57:27 -0700244 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
245 audio_hw_device_t *dev = mAudioHwDevs[i];
246
247 mHardwareStatus = AUDIO_HW_INIT;
248 rc = dev->init_check(dev);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800249 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700250 if (rc == 0) {
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800251 mMode = AUDIO_MODE_NORMAL; // assigned multiple times with same value
Dima Zavin799a70e2011-04-18 16:57:27 -0700252 mHardwareStatus = AUDIO_HW_SET_MODE;
253 dev->set_mode(dev, mMode);
John Grossman4ff14ba2012-02-08 16:37:41 -0800254
255 if ((dev != mPrimaryHardwareDev) &&
256 (NULL != dev->set_master_volume)) {
257 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
258 dev->set_master_volume(dev, initialVolume);
259 }
260
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800261 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700262 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700263 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800264
265 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
266 ? initialVolume
267 : 1.0;
268 mMasterVolume = initialVolume;
269 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700270}
271
272AudioFlinger::~AudioFlinger()
273{
Dima Zavin799a70e2011-04-18 16:57:27 -0700274
Mathias Agopian65ab4712010-07-14 17:59:35 -0700275 while (!mRecordThreads.isEmpty()) {
276 // closeInput() will remove first entry from mRecordThreads
277 closeInput(mRecordThreads.keyAt(0));
278 }
279 while (!mPlaybackThreads.isEmpty()) {
280 // closeOutput() will remove first entry from mPlaybackThreads
281 closeOutput(mPlaybackThreads.keyAt(0));
282 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700283
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800284 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
285 // no mHardwareLock needed, as there are no other references to this
286 audio_hw_device_close(mAudioHwDevs[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700287 }
288}
289
Dima Zavin799a70e2011-04-18 16:57:27 -0700290audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
291{
292 /* first matching HW device is returned */
293 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
294 audio_hw_device_t *dev = mAudioHwDevs[i];
295 if ((dev->get_supported_devices(dev) & devices) == devices)
296 return dev;
297 }
298 return NULL;
299}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700300
301status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
302{
303 const size_t SIZE = 256;
304 char buffer[SIZE];
305 String8 result;
306
307 result.append("Clients:\n");
308 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800309 sp<Client> client = mClients.valueAt(i).promote();
310 if (client != 0) {
311 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
312 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700313 }
314 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700315
316 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800317 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700318 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
319 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800320 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700321 result.append(buffer);
322 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700323 write(fd, result.string(), result.size());
324 return NO_ERROR;
325}
326
327
328status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
329{
330 const size_t SIZE = 256;
331 char buffer[SIZE];
332 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800333 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700334
John Grossman4ff14ba2012-02-08 16:37:41 -0800335 snprintf(buffer, SIZE, "Hardware status: %d\n"
336 "Standby Time mSec: %u\n",
337 hardwareStatus,
338 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700339 result.append(buffer);
340 write(fd, result.string(), result.size());
341 return NO_ERROR;
342}
343
344status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
345{
346 const size_t SIZE = 256;
347 char buffer[SIZE];
348 String8 result;
349 snprintf(buffer, SIZE, "Permission Denial: "
350 "can't dump AudioFlinger from pid=%d, uid=%d\n",
351 IPCThreadState::self()->getCallingPid(),
352 IPCThreadState::self()->getCallingUid());
353 result.append(buffer);
354 write(fd, result.string(), result.size());
355 return NO_ERROR;
356}
357
358static bool tryLock(Mutex& mutex)
359{
360 bool locked = false;
361 for (int i = 0; i < kDumpLockRetries; ++i) {
362 if (mutex.tryLock() == NO_ERROR) {
363 locked = true;
364 break;
365 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800366 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700367 }
368 return locked;
369}
370
371status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
372{
Glenn Kasten44deb052012-02-05 18:09:08 -0800373 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700374 dumpPermissionDenial(fd, args);
375 } else {
376 // get state of hardware lock
377 bool hardwareLocked = tryLock(mHardwareLock);
378 if (!hardwareLocked) {
379 String8 result(kHardwareLockedString);
380 write(fd, result.string(), result.size());
381 } else {
382 mHardwareLock.unlock();
383 }
384
385 bool locked = tryLock(mLock);
386
387 // failed to lock - AudioFlinger is probably deadlocked
388 if (!locked) {
389 String8 result(kDeadlockedString);
390 write(fd, result.string(), result.size());
391 }
392
393 dumpClients(fd, args);
394 dumpInternals(fd, args);
395
396 // dump playback threads
397 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
398 mPlaybackThreads.valueAt(i)->dump(fd, args);
399 }
400
401 // dump record threads
402 for (size_t i = 0; i < mRecordThreads.size(); i++) {
403 mRecordThreads.valueAt(i)->dump(fd, args);
404 }
405
Dima Zavin799a70e2011-04-18 16:57:27 -0700406 // dump all hardware devs
407 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
408 audio_hw_device_t *dev = mAudioHwDevs[i];
409 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700410 }
411 if (locked) mLock.unlock();
412 }
413 return NO_ERROR;
414}
415
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800416sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
417{
418 // If pid is already in the mClients wp<> map, then use that entry
419 // (for which promote() is always != 0), otherwise create a new entry and Client.
420 sp<Client> client = mClients.valueFor(pid).promote();
421 if (client == 0) {
422 client = new Client(this, pid);
423 mClients.add(pid, client);
424 }
425
426 return client;
427}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700428
429// IAudioFlinger interface
430
431
432sp<IAudioTrack> AudioFlinger::createTrack(
433 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800434 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700435 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800436 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700437 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700438 int frameCount,
Glenn Kasten5cf034d2012-02-21 10:35:56 -0800439 // FIXME dead, remove from IAudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700440 uint32_t flags,
441 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800442 audio_io_handle_t output,
John Grossman4ff14ba2012-02-08 16:37:41 -0800443 bool isTimed,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444 int *sessionId,
445 status_t *status)
446{
447 sp<PlaybackThread::Track> track;
448 sp<TrackHandle> trackHandle;
449 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700450 status_t lStatus;
451 int lSessionId;
452
Glenn Kasten263709e2012-01-06 08:40:01 -0800453 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
454 // but if someone uses binder directly they could bypass that and cause us to crash
455 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000456 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700457 lStatus = BAD_VALUE;
458 goto Exit;
459 }
460
461 {
462 Mutex::Autolock _l(mLock);
463 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700464 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700465 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000466 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700467 lStatus = BAD_VALUE;
468 goto Exit;
469 }
470
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800471 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700472
Steve Block3856b092011-10-20 11:56:00 +0100473 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700474 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700475 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700476 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
477 if (mPlaybackThreads.keyAt(i) != output) {
478 // prevent same audio session on different output threads
479 uint32_t sessions = t->hasAudioSession(*sessionId);
480 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000481 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700482 lStatus = BAD_VALUE;
483 goto Exit;
484 }
485 // check if an effect with same session ID is waiting for a track to be created
486 if (sessions & PlaybackThread::EFFECT_SESSION) {
487 effectThread = t.get();
488 }
Eric Laurentde070132010-07-13 04:45:46 -0700489 }
490 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700491 lSessionId = *sessionId;
492 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700493 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700494 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700495 if (sessionId != NULL) {
496 *sessionId = lSessionId;
497 }
498 }
Steve Block3856b092011-10-20 11:56:00 +0100499 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700500
501 track = thread->createTrack_l(client, streamType, sampleRate, format,
John Grossman4ff14ba2012-02-08 16:37:41 -0800502 channelMask, frameCount, sharedBuffer, lSessionId, isTimed, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700503
504 // move effect chain to this output thread if an effect on same session was waiting
505 // for a track to be created
506 if (lStatus == NO_ERROR && effectThread != NULL) {
507 Mutex::Autolock _dl(thread->mLock);
508 Mutex::Autolock _sl(effectThread->mLock);
509 moveEffectChain_l(lSessionId, effectThread, thread, true);
510 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700511 }
512 if (lStatus == NO_ERROR) {
513 trackHandle = new TrackHandle(track);
514 } else {
515 // remove local strong reference to Client before deleting the Track so that the Client
516 // destructor is called by the TrackBase destructor with mLock held
517 client.clear();
518 track.clear();
519 }
520
521Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700522 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700523 *status = lStatus;
524 }
525 return trackHandle;
526}
527
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800528uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700529{
530 Mutex::Autolock _l(mLock);
531 PlaybackThread *thread = checkPlaybackThread_l(output);
532 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000533 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700534 return 0;
535 }
536 return thread->sampleRate();
537}
538
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800539int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700540{
541 Mutex::Autolock _l(mLock);
542 PlaybackThread *thread = checkPlaybackThread_l(output);
543 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000544 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700545 return 0;
546 }
547 return thread->channelCount();
548}
549
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800550audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700551{
552 Mutex::Autolock _l(mLock);
553 PlaybackThread *thread = checkPlaybackThread_l(output);
554 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000555 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800556 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700557 }
558 return thread->format();
559}
560
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800561size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700562{
563 Mutex::Autolock _l(mLock);
564 PlaybackThread *thread = checkPlaybackThread_l(output);
565 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000566 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700567 return 0;
568 }
569 return thread->frameCount();
570}
571
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800572uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700573{
574 Mutex::Autolock _l(mLock);
575 PlaybackThread *thread = checkPlaybackThread_l(output);
576 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000577 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700578 return 0;
579 }
580 return thread->latency();
581}
582
583status_t AudioFlinger::setMasterVolume(float value)
584{
Eric Laurenta1884f92011-08-23 08:25:03 -0700585 status_t ret = initCheck();
586 if (ret != NO_ERROR) {
587 return ret;
588 }
589
Mathias Agopian65ab4712010-07-14 17:59:35 -0700590 // check calling permissions
591 if (!settingsAllowed()) {
592 return PERMISSION_DENIED;
593 }
594
John Grossman4ff14ba2012-02-08 16:37:41 -0800595 float swmv = value;
596
Mathias Agopian65ab4712010-07-14 17:59:35 -0700597 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800598 if (MVS_NONE != mMasterVolumeSupportLvl) {
599 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
600 AutoMutex lock(mHardwareLock);
601 audio_hw_device_t *dev = mAudioHwDevs[i];
602
603 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
604 if (NULL != dev->set_master_volume) {
605 dev->set_master_volume(dev, value);
606 }
607 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800608 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800609
610 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700611 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700612
Eric Laurent93575202011-01-18 18:39:02 -0800613 Mutex::Autolock _l(mLock);
John Grossman4ff14ba2012-02-08 16:37:41 -0800614 mMasterVolume = value;
615 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800616 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700617 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700618
619 return NO_ERROR;
620}
621
Glenn Kastenf78aee72012-01-04 11:00:47 -0800622status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700623{
Eric Laurenta1884f92011-08-23 08:25:03 -0700624 status_t ret = initCheck();
625 if (ret != NO_ERROR) {
626 return ret;
627 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700628
629 // check calling permissions
630 if (!settingsAllowed()) {
631 return PERMISSION_DENIED;
632 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800633 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000634 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700635 return BAD_VALUE;
636 }
637
638 { // scope for the lock
639 AutoMutex lock(mHardwareLock);
640 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700641 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700642 mHardwareStatus = AUDIO_HW_IDLE;
643 }
644
645 if (NO_ERROR == ret) {
646 Mutex::Autolock _l(mLock);
647 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800648 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700649 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700650 }
651
652 return ret;
653}
654
655status_t AudioFlinger::setMicMute(bool state)
656{
Eric Laurenta1884f92011-08-23 08:25:03 -0700657 status_t ret = initCheck();
658 if (ret != NO_ERROR) {
659 return ret;
660 }
661
Mathias Agopian65ab4712010-07-14 17:59:35 -0700662 // check calling permissions
663 if (!settingsAllowed()) {
664 return PERMISSION_DENIED;
665 }
666
667 AutoMutex lock(mHardwareLock);
668 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700669 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700670 mHardwareStatus = AUDIO_HW_IDLE;
671 return ret;
672}
673
674bool AudioFlinger::getMicMute() const
675{
Eric Laurenta1884f92011-08-23 08:25:03 -0700676 status_t ret = initCheck();
677 if (ret != NO_ERROR) {
678 return false;
679 }
680
Dima Zavinfce7a472011-04-19 22:30:36 -0700681 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800682 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700683 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700684 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700685 mHardwareStatus = AUDIO_HW_IDLE;
686 return state;
687}
688
689status_t AudioFlinger::setMasterMute(bool muted)
690{
691 // check calling permissions
692 if (!settingsAllowed()) {
693 return PERMISSION_DENIED;
694 }
695
Eric Laurent93575202011-01-18 18:39:02 -0800696 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800697 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700698 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800699 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700700 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700701
702 return NO_ERROR;
703}
704
705float AudioFlinger::masterVolume() const
706{
Glenn Kasten98067102011-12-13 11:47:54 -0800707 Mutex::Autolock _l(mLock);
708 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700709}
710
John Grossman4ff14ba2012-02-08 16:37:41 -0800711float AudioFlinger::masterVolumeSW() const
712{
713 Mutex::Autolock _l(mLock);
714 return masterVolumeSW_l();
715}
716
Mathias Agopian65ab4712010-07-14 17:59:35 -0700717bool AudioFlinger::masterMute() const
718{
Glenn Kasten98067102011-12-13 11:47:54 -0800719 Mutex::Autolock _l(mLock);
720 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700721}
722
John Grossman4ff14ba2012-02-08 16:37:41 -0800723float AudioFlinger::masterVolume_l() const
724{
725 if (MVS_FULL == mMasterVolumeSupportLvl) {
726 float ret_val;
727 AutoMutex lock(mHardwareLock);
728
729 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800730 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
731 (NULL != mPrimaryHardwareDev->get_master_volume),
732 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800733
734 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
735 mHardwareStatus = AUDIO_HW_IDLE;
736 return ret_val;
737 }
738
739 return mMasterVolume;
740}
741
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800742status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
743 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700744{
745 // check calling permissions
746 if (!settingsAllowed()) {
747 return PERMISSION_DENIED;
748 }
749
Glenn Kasten263709e2012-01-06 08:40:01 -0800750 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000751 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700752 return BAD_VALUE;
753 }
754
755 AutoMutex lock(mLock);
756 PlaybackThread *thread = NULL;
757 if (output) {
758 thread = checkPlaybackThread_l(output);
759 if (thread == NULL) {
760 return BAD_VALUE;
761 }
762 }
763
764 mStreamTypes[stream].volume = value;
765
766 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800767 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700768 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700769 }
770 } else {
771 thread->setStreamVolume(stream, value);
772 }
773
774 return NO_ERROR;
775}
776
Glenn Kastenfff6d712012-01-12 16:38:12 -0800777status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700778{
779 // check calling permissions
780 if (!settingsAllowed()) {
781 return PERMISSION_DENIED;
782 }
783
Glenn Kasten263709e2012-01-06 08:40:01 -0800784 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700785 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000786 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700787 return BAD_VALUE;
788 }
789
Eric Laurent93575202011-01-18 18:39:02 -0800790 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700791 mStreamTypes[stream].mute = muted;
792 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700793 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700794
795 return NO_ERROR;
796}
797
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800798float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700799{
Glenn Kasten263709e2012-01-06 08:40:01 -0800800 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700801 return 0.0f;
802 }
803
804 AutoMutex lock(mLock);
805 float volume;
806 if (output) {
807 PlaybackThread *thread = checkPlaybackThread_l(output);
808 if (thread == NULL) {
809 return 0.0f;
810 }
811 volume = thread->streamVolume(stream);
812 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800813 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814 }
815
816 return volume;
817}
818
Glenn Kastenfff6d712012-01-12 16:38:12 -0800819bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700820{
Glenn Kasten263709e2012-01-06 08:40:01 -0800821 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700822 return true;
823 }
824
Glenn Kasten6637baa2012-01-09 09:40:36 -0800825 AutoMutex lock(mLock);
826 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700827}
828
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800829status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700830{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800831 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700832 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
833 // check calling permissions
834 if (!settingsAllowed()) {
835 return PERMISSION_DENIED;
836 }
837
Mathias Agopian65ab4712010-07-14 17:59:35 -0700838 // ioHandle == 0 means the parameters are global to the audio hardware interface
839 if (ioHandle == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700840 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800841 {
842 AutoMutex lock(mHardwareLock);
843 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700844 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
845 audio_hw_device_t *dev = mAudioHwDevs[i];
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800846 status_t result = dev->set_parameters(dev, keyValuePairs.string());
Dima Zavin799a70e2011-04-18 16:57:27 -0700847 final_result = result ?: final_result;
848 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700849 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800850 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700851 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
852 AudioParameter param = AudioParameter(keyValuePairs);
853 String8 value;
854 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
855 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700856 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
857 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700858 for (size_t i = 0; i < mRecordThreads.size(); i++) {
859 sp<RecordThread> thread = mRecordThreads.valueAt(i);
860 RecordThread::RecordTrack *track = thread->track();
861 if (track != NULL) {
862 audio_devices_t device = (audio_devices_t)(
863 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700864 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700865 thread->setEffectSuspended(FX_IID_AEC,
866 suspend,
867 track->sessionId());
868 thread->setEffectSuspended(FX_IID_NS,
869 suspend,
870 track->sessionId());
871 }
872 }
Eric Laurentbee53372011-08-29 12:42:48 -0700873 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700874 }
875 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700876 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700877 }
878
879 // hold a strong ref on thread in case closeOutput() or closeInput() is called
880 // and the thread is exited once the lock is released
881 sp<ThreadBase> thread;
882 {
883 Mutex::Autolock _l(mLock);
884 thread = checkPlaybackThread_l(ioHandle);
885 if (thread == NULL) {
886 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800887 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700888 // indicate output device change to all input threads for pre processing
889 AudioParameter param = AudioParameter(keyValuePairs);
890 int value;
891 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
892 for (size_t i = 0; i < mRecordThreads.size(); i++) {
893 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
894 }
895 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700896 }
897 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800898 if (thread != 0) {
899 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700900 }
901 return BAD_VALUE;
902}
903
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800904String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700905{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800906// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700907// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
908
909 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700910 String8 out_s8;
911
Dima Zavin799a70e2011-04-18 16:57:27 -0700912 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800913 char *s;
914 {
915 AutoMutex lock(mHardwareLock);
916 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700917 audio_hw_device_t *dev = mAudioHwDevs[i];
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800918 s = dev->get_parameters(dev, keys.string());
919 mHardwareStatus = AUDIO_HW_IDLE;
920 }
John Grossmanef7740b2012-02-09 11:28:36 -0800921 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700922 free(s);
923 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700924 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700925 }
926
927 Mutex::Autolock _l(mLock);
928
929 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
930 if (playbackThread != NULL) {
931 return playbackThread->getParameters(keys);
932 }
933 RecordThread *recordThread = checkRecordThread_l(ioHandle);
934 if (recordThread != NULL) {
935 return recordThread->getParameters(keys);
936 }
937 return String8("");
938}
939
Glenn Kastenf587ba52012-01-26 16:25:10 -0800940size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700941{
Eric Laurenta1884f92011-08-23 08:25:03 -0700942 status_t ret = initCheck();
943 if (ret != NO_ERROR) {
944 return 0;
945 }
946
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800947 AutoMutex lock(mHardwareLock);
948 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
949 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
950 mHardwareStatus = AUDIO_HW_IDLE;
951 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700952}
953
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800954unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700955{
956 if (ioHandle == 0) {
957 return 0;
958 }
959
960 Mutex::Autolock _l(mLock);
961
962 RecordThread *recordThread = checkRecordThread_l(ioHandle);
963 if (recordThread != NULL) {
964 return recordThread->getInputFramesLost();
965 }
966 return 0;
967}
968
969status_t AudioFlinger::setVoiceVolume(float value)
970{
Eric Laurenta1884f92011-08-23 08:25:03 -0700971 status_t ret = initCheck();
972 if (ret != NO_ERROR) {
973 return ret;
974 }
975
Mathias Agopian65ab4712010-07-14 17:59:35 -0700976 // check calling permissions
977 if (!settingsAllowed()) {
978 return PERMISSION_DENIED;
979 }
980
981 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800982 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700983 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700984 mHardwareStatus = AUDIO_HW_IDLE;
985
986 return ret;
987}
988
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800989status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
990 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700991{
992 status_t status;
993
994 Mutex::Autolock _l(mLock);
995
996 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
997 if (playbackThread != NULL) {
998 return playbackThread->getRenderPosition(halFrames, dspFrames);
999 }
1000
1001 return BAD_VALUE;
1002}
1003
1004void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1005{
1006
1007 Mutex::Autolock _l(mLock);
1008
Glenn Kastenbb001922012-02-03 11:10:26 -08001009 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001010 if (mNotificationClients.indexOfKey(pid) < 0) {
1011 sp<NotificationClient> notificationClient = new NotificationClient(this,
1012 client,
1013 pid);
Steve Block3856b092011-10-20 11:56:00 +01001014 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001015
1016 mNotificationClients.add(pid, notificationClient);
1017
1018 sp<IBinder> binder = client->asBinder();
1019 binder->linkToDeath(notificationClient);
1020
1021 // the config change is always sent from playback or record threads to avoid deadlock
1022 // with AudioSystem::gLock
1023 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1024 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1025 }
1026
1027 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1028 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1029 }
1030 }
1031}
1032
1033void AudioFlinger::removeNotificationClient(pid_t pid)
1034{
1035 Mutex::Autolock _l(mLock);
1036
Glenn Kastena3b09252012-01-20 09:19:01 -08001037 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001038
Steve Block3856b092011-10-20 11:56:00 +01001039 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001040 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001041 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001042 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001043 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001044 ALOGV(" pid %d @ %d", ref->mPid, i);
1045 if (ref->mPid == pid) {
1046 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001047 mAudioSessionRefs.removeAt(i);
1048 delete ref;
1049 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001050 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001051 } else {
1052 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001053 }
1054 }
1055 if (removed) {
1056 purgeStaleEffects_l();
1057 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001058}
1059
1060// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001061void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001062{
1063 size_t size = mNotificationClients.size();
1064 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001065 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1066 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001067 }
1068}
1069
1070// removeClient_l() must be called with AudioFlinger::mLock held
1071void AudioFlinger::removeClient_l(pid_t pid)
1072{
Steve Block3856b092011-10-20 11:56:00 +01001073 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001074 mClients.removeItem(pid);
1075}
1076
1077
1078// ----------------------------------------------------------------------------
1079
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001080AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1081 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001082 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001083 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001084 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
1085 // mChannelMask
1086 mChannelCount(0),
1087 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1088 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001089 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001090 mDevice(device),
1091 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001092{
1093}
1094
1095AudioFlinger::ThreadBase::~ThreadBase()
1096{
1097 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001098 // do not lock the mutex in destructor
1099 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001100 if (mPowerManager != 0) {
1101 sp<IBinder> binder = mPowerManager->asBinder();
1102 binder->unlinkToDeath(mDeathRecipient);
1103 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001104}
1105
1106void AudioFlinger::ThreadBase::exit()
1107{
Steve Block3856b092011-10-20 11:56:00 +01001108 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001109 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001110 // This lock prevents the following race in thread (uniprocessor for illustration):
1111 // if (!exitPending()) {
1112 // // context switch from here to exit()
1113 // // exit() calls requestExit(), what exitPending() observes
1114 // // exit() calls signal(), which is dropped since no waiters
1115 // // context switch back from exit() to here
1116 // mWaitWorkCV.wait(...);
1117 // // now thread is hung
1118 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001119 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001120 requestExit();
1121 mWaitWorkCV.signal();
1122 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001123 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1124 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001125 requestExitAndWait();
1126}
1127
Mathias Agopian65ab4712010-07-14 17:59:35 -07001128status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1129{
1130 status_t status;
1131
Steve Block3856b092011-10-20 11:56:00 +01001132 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001133 Mutex::Autolock _l(mLock);
1134
1135 mNewParameters.add(keyValuePairs);
1136 mWaitWorkCV.signal();
1137 // wait condition with timeout in case the thread loop has exited
1138 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001139 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001140 status = mParamStatus;
1141 mWaitWorkCV.signal();
1142 } else {
1143 status = TIMED_OUT;
1144 }
1145 return status;
1146}
1147
1148void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1149{
1150 Mutex::Autolock _l(mLock);
1151 sendConfigEvent_l(event, param);
1152}
1153
1154// sendConfigEvent_l() must be called with ThreadBase::mLock held
1155void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1156{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001157 ConfigEvent configEvent;
1158 configEvent.mEvent = event;
1159 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001160 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001161 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001162 mWaitWorkCV.signal();
1163}
1164
1165void AudioFlinger::ThreadBase::processConfigEvents()
1166{
1167 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001168 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001169 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001170 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001171 mConfigEvents.removeAt(0);
1172 // release mLock before locking AudioFlinger mLock: lock order is always
1173 // AudioFlinger then ThreadBase to avoid cross deadlock
1174 mLock.unlock();
1175 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001176 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001177 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001178 mLock.lock();
1179 }
1180 mLock.unlock();
1181}
1182
1183status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1184{
1185 const size_t SIZE = 256;
1186 char buffer[SIZE];
1187 String8 result;
1188
1189 bool locked = tryLock(mLock);
1190 if (!locked) {
1191 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1192 write(fd, buffer, strlen(buffer));
1193 }
1194
1195 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1196 result.append(buffer);
1197 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1198 result.append(buffer);
1199 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1200 result.append(buffer);
1201 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1202 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001203 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1204 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001205 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1206 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001207 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001208 result.append(buffer);
1209
1210 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1211 result.append(buffer);
1212 result.append(" Index Command");
1213 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1214 snprintf(buffer, SIZE, "\n %02d ", i);
1215 result.append(buffer);
1216 result.append(mNewParameters[i]);
1217 }
1218
1219 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1220 result.append(buffer);
1221 snprintf(buffer, SIZE, " Index event param\n");
1222 result.append(buffer);
1223 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001224 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001225 result.append(buffer);
1226 }
1227 result.append("\n");
1228
1229 write(fd, result.string(), result.size());
1230
1231 if (locked) {
1232 mLock.unlock();
1233 }
1234 return NO_ERROR;
1235}
1236
Eric Laurent1d2bff02011-07-24 17:49:51 -07001237status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1238{
1239 const size_t SIZE = 256;
1240 char buffer[SIZE];
1241 String8 result;
1242
1243 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1244 write(fd, buffer, strlen(buffer));
1245
1246 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1247 sp<EffectChain> chain = mEffectChains[i];
1248 if (chain != 0) {
1249 chain->dump(fd, args);
1250 }
1251 }
1252 return NO_ERROR;
1253}
1254
Eric Laurentfeb0db62011-07-22 09:04:31 -07001255void AudioFlinger::ThreadBase::acquireWakeLock()
1256{
1257 Mutex::Autolock _l(mLock);
1258 acquireWakeLock_l();
1259}
1260
1261void AudioFlinger::ThreadBase::acquireWakeLock_l()
1262{
1263 if (mPowerManager == 0) {
1264 // use checkService() to avoid blocking if power service is not up yet
1265 sp<IBinder> binder =
1266 defaultServiceManager()->checkService(String16("power"));
1267 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001268 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001269 } else {
1270 mPowerManager = interface_cast<IPowerManager>(binder);
1271 binder->linkToDeath(mDeathRecipient);
1272 }
1273 }
1274 if (mPowerManager != 0) {
1275 sp<IBinder> binder = new BBinder();
1276 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1277 binder,
1278 String16(mName));
1279 if (status == NO_ERROR) {
1280 mWakeLockToken = binder;
1281 }
Steve Block3856b092011-10-20 11:56:00 +01001282 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001283 }
1284}
1285
1286void AudioFlinger::ThreadBase::releaseWakeLock()
1287{
1288 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001289 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001290}
1291
1292void AudioFlinger::ThreadBase::releaseWakeLock_l()
1293{
1294 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001295 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001296 if (mPowerManager != 0) {
1297 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1298 }
1299 mWakeLockToken.clear();
1300 }
1301}
1302
1303void AudioFlinger::ThreadBase::clearPowerManager()
1304{
1305 Mutex::Autolock _l(mLock);
1306 releaseWakeLock_l();
1307 mPowerManager.clear();
1308}
1309
1310void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1311{
1312 sp<ThreadBase> thread = mThread.promote();
1313 if (thread != 0) {
1314 thread->clearPowerManager();
1315 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001316 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001317}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001318
Eric Laurent59255e42011-07-27 19:49:51 -07001319void AudioFlinger::ThreadBase::setEffectSuspended(
1320 const effect_uuid_t *type, bool suspend, int sessionId)
1321{
1322 Mutex::Autolock _l(mLock);
1323 setEffectSuspended_l(type, suspend, sessionId);
1324}
1325
1326void AudioFlinger::ThreadBase::setEffectSuspended_l(
1327 const effect_uuid_t *type, bool suspend, int sessionId)
1328{
Glenn Kasten090f0192012-01-30 13:00:02 -08001329 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001330 if (chain != 0) {
1331 if (type != NULL) {
1332 chain->setEffectSuspended_l(type, suspend);
1333 } else {
1334 chain->setEffectSuspendedAll_l(suspend);
1335 }
1336 }
1337
1338 updateSuspendedSessions_l(type, suspend, sessionId);
1339}
1340
1341void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1342{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001343 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001344 if (index < 0) {
1345 return;
1346 }
1347
1348 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1349 mSuspendedSessions.editValueAt(index);
1350
1351 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001352 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001353 for (int j = 0; j < desc->mRefCount; j++) {
1354 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1355 chain->setEffectSuspendedAll_l(true);
1356 } else {
Steve Block3856b092011-10-20 11:56:00 +01001357 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001358 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001359 chain->setEffectSuspended_l(&desc->mType, true);
1360 }
1361 }
1362 }
1363}
1364
Eric Laurent59255e42011-07-27 19:49:51 -07001365void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1366 bool suspend,
1367 int sessionId)
1368{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001369 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001370
1371 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1372
1373 if (suspend) {
1374 if (index >= 0) {
1375 sessionEffects = mSuspendedSessions.editValueAt(index);
1376 } else {
1377 mSuspendedSessions.add(sessionId, sessionEffects);
1378 }
1379 } else {
1380 if (index < 0) {
1381 return;
1382 }
1383 sessionEffects = mSuspendedSessions.editValueAt(index);
1384 }
1385
1386
1387 int key = EffectChain::kKeyForSuspendAll;
1388 if (type != NULL) {
1389 key = type->timeLow;
1390 }
1391 index = sessionEffects.indexOfKey(key);
1392
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001393 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001394 if (suspend) {
1395 if (index >= 0) {
1396 desc = sessionEffects.valueAt(index);
1397 } else {
1398 desc = new SuspendedSessionDesc();
1399 if (type != NULL) {
1400 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1401 }
1402 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001403 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001404 }
1405 desc->mRefCount++;
1406 } else {
1407 if (index < 0) {
1408 return;
1409 }
1410 desc = sessionEffects.valueAt(index);
1411 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001412 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001413 sessionEffects.removeItemsAt(index);
1414 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001415 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001416 sessionId);
1417 mSuspendedSessions.removeItem(sessionId);
1418 }
1419 }
1420 }
1421 if (!sessionEffects.isEmpty()) {
1422 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1423 }
1424}
1425
1426void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1427 bool enabled,
1428 int sessionId)
1429{
1430 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001431 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1432}
Eric Laurent59255e42011-07-27 19:49:51 -07001433
Eric Laurenta85a74a2011-10-19 11:44:54 -07001434void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1435 bool enabled,
1436 int sessionId)
1437{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001438 if (mType != RECORD) {
1439 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1440 // another session. This gives the priority to well behaved effect control panels
1441 // and applications not using global effects.
1442 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1443 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1444 }
1445 }
Eric Laurent59255e42011-07-27 19:49:51 -07001446
1447 sp<EffectChain> chain = getEffectChain_l(sessionId);
1448 if (chain != 0) {
1449 chain->checkSuspendOnEffectEnabled(effect, enabled);
1450 }
1451}
1452
Mathias Agopian65ab4712010-07-14 17:59:35 -07001453// ----------------------------------------------------------------------------
1454
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001455AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1456 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001457 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001458 uint32_t device,
1459 type_t type)
1460 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001461 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1462 // Assumes constructor is called by AudioFlinger with it's mLock held,
1463 // but it would be safer to explicitly pass initial masterMute as parameter
1464 mMasterMute(audioFlinger->masterMute_l()),
1465 // mStreamTypes[] initialized in constructor body
1466 mOutput(output),
1467 // Assumes constructor is called by AudioFlinger with it's mLock held,
1468 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001469 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001470 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001471 mMixerStatus(MIXER_IDLE),
Glenn Kasten66fcab92012-02-24 14:59:21 -08001472 mPrevMixerStatus(MIXER_IDLE),
1473 standbyDelay(AudioFlinger::mStandbyTimeInNsecs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001474{
Glenn Kasten480b4682012-02-28 12:30:08 -08001475 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001476
Mathias Agopian65ab4712010-07-14 17:59:35 -07001477 readOutputParameters();
1478
Glenn Kasten263709e2012-01-06 08:40:01 -08001479 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001480 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1481 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1482 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001483 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1484 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001485 // initialized by stream_type_t default constructor
1486 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001487 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001488 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1489 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001490}
1491
1492AudioFlinger::PlaybackThread::~PlaybackThread()
1493{
1494 delete [] mMixBuffer;
1495}
1496
1497status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1498{
1499 dumpInternals(fd, args);
1500 dumpTracks(fd, args);
1501 dumpEffectChains(fd, args);
1502 return NO_ERROR;
1503}
1504
1505status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1506{
1507 const size_t SIZE = 256;
1508 char buffer[SIZE];
1509 String8 result;
1510
1511 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1512 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001513 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 -07001514 for (size_t i = 0; i < mTracks.size(); ++i) {
1515 sp<Track> track = mTracks[i];
1516 if (track != 0) {
1517 track->dump(buffer, SIZE);
1518 result.append(buffer);
1519 }
1520 }
1521
1522 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1523 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001524 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 -07001525 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001526 sp<Track> track = mActiveTracks[i].promote();
1527 if (track != 0) {
1528 track->dump(buffer, SIZE);
1529 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001530 }
1531 }
1532 write(fd, result.string(), result.size());
1533 return NO_ERROR;
1534}
1535
Mathias Agopian65ab4712010-07-14 17:59:35 -07001536status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1537{
1538 const size_t SIZE = 256;
1539 char buffer[SIZE];
1540 String8 result;
1541
1542 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1543 result.append(buffer);
1544 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1545 result.append(buffer);
1546 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1547 result.append(buffer);
1548 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1549 result.append(buffer);
1550 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1551 result.append(buffer);
1552 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1553 result.append(buffer);
1554 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1555 result.append(buffer);
1556 write(fd, result.string(), result.size());
1557
1558 dumpBase(fd, args);
1559
1560 return NO_ERROR;
1561}
1562
1563// Thread virtuals
1564status_t AudioFlinger::PlaybackThread::readyToRun()
1565{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001566 status_t status = initCheck();
1567 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001568 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001569 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001570 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001571 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001572 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001573}
1574
1575void AudioFlinger::PlaybackThread::onFirstRef()
1576{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001577 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001578}
1579
1580// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1581sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1582 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001583 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001584 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001585 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001586 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001587 int frameCount,
1588 const sp<IMemory>& sharedBuffer,
1589 int sessionId,
John Grossman4ff14ba2012-02-08 16:37:41 -08001590 bool isTimed,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001591 status_t *status)
1592{
1593 sp<Track> track;
1594 status_t lStatus;
1595
1596 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001597 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1598 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001599 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001600 "for output %p with format %d",
1601 sampleRate, format, channelMask, mOutput, mFormat);
1602 lStatus = BAD_VALUE;
1603 goto Exit;
1604 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001605 }
1606 } else {
1607 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1608 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001609 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610 lStatus = BAD_VALUE;
1611 goto Exit;
1612 }
1613 }
1614
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001615 lStatus = initCheck();
1616 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001617 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001618 goto Exit;
1619 }
1620
1621 { // scope for mLock
1622 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001623
1624 // all tracks in same audio session must share the same routing strategy otherwise
1625 // conflicts will happen when tracks are moved from one output to another by audio policy
1626 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001627 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001628 for (size_t i = 0; i < mTracks.size(); ++i) {
1629 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001630 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001631 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001632 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001633 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001634 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001635 lStatus = BAD_VALUE;
1636 goto Exit;
1637 }
1638 }
1639 }
1640
John Grossman4ff14ba2012-02-08 16:37:41 -08001641 if (!isTimed) {
1642 track = new Track(this, client, streamType, sampleRate, format,
1643 channelMask, frameCount, sharedBuffer, sessionId);
1644 } else {
1645 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1646 channelMask, frameCount, sharedBuffer, sessionId);
1647 }
1648 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001649 lStatus = NO_MEMORY;
1650 goto Exit;
1651 }
1652 mTracks.add(track);
1653
1654 sp<EffectChain> chain = getEffectChain_l(sessionId);
1655 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001656 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001657 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001658 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001659 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001660 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001661
1662 // invalidate track immediately if the stream type was moved to another thread since
1663 // createTrack() was called by the client process.
1664 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001665 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001666 this, streamType);
Eric Laurent9f6530f2011-08-30 10:18:54 -07001667 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1668 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001669 }
1670 lStatus = NO_ERROR;
1671
1672Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001673 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001674 *status = lStatus;
1675 }
1676 return track;
1677}
1678
1679uint32_t AudioFlinger::PlaybackThread::latency() const
1680{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001681 Mutex::Autolock _l(mLock);
1682 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001683 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001684 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685 return 0;
1686 }
1687}
1688
Glenn Kasten6637baa2012-01-09 09:40:36 -08001689void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001690{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001691 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001692 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001693}
1694
Glenn Kasten6637baa2012-01-09 09:40:36 -08001695void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001696{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001697 Mutex::Autolock _l(mLock);
1698 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001699}
1700
Glenn Kasten6637baa2012-01-09 09:40:36 -08001701void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001702{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001703 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001704 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001705}
1706
Glenn Kasten6637baa2012-01-09 09:40:36 -08001707void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001708{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001709 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001710 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001711}
1712
Glenn Kastenfff6d712012-01-12 16:38:12 -08001713float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001714{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001715 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001716 return mStreamTypes[stream].volume;
1717}
1718
Mathias Agopian65ab4712010-07-14 17:59:35 -07001719// addTrack_l() must be called with ThreadBase::mLock held
1720status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1721{
1722 status_t status = ALREADY_EXISTS;
1723
1724 // set retry count for buffer fill
1725 track->mRetryCount = kMaxTrackStartupRetries;
1726 if (mActiveTracks.indexOf(track) < 0) {
1727 // the track is newly added, make sure it fills up all its
1728 // buffers before playing. This is to ensure the client will
1729 // effectively get the latency it requested.
1730 track->mFillingUpStatus = Track::FS_FILLING;
1731 track->mResetDone = false;
1732 mActiveTracks.add(track);
1733 if (track->mainBuffer() != mMixBuffer) {
1734 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1735 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001736 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001737 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001738 }
1739 }
1740
1741 status = NO_ERROR;
1742 }
1743
Steve Block3856b092011-10-20 11:56:00 +01001744 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001745 mWaitWorkCV.broadcast();
1746
1747 return status;
1748}
1749
1750// destroyTrack_l() must be called with ThreadBase::mLock held
1751void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1752{
1753 track->mState = TrackBase::TERMINATED;
1754 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001755 removeTrack_l(track);
1756 }
1757}
1758
1759void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1760{
1761 mTracks.remove(track);
1762 deleteTrackName_l(track->name());
1763 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1764 if (chain != 0) {
1765 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001766 }
1767}
1768
1769String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1770{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001771 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001772 char *s;
1773
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001774 Mutex::Autolock _l(mLock);
1775 if (initCheck() != NO_ERROR) {
1776 return out_s8;
1777 }
1778
Dima Zavin799a70e2011-04-18 16:57:27 -07001779 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001780 out_s8 = String8(s);
1781 free(s);
1782 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001783}
1784
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001785// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001786void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1787 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001788 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001789
Steve Block3856b092011-10-20 11:56:00 +01001790 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001791
1792 switch (event) {
1793 case AudioSystem::OUTPUT_OPENED:
1794 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001795 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001796 desc.samplingRate = mSampleRate;
1797 desc.format = mFormat;
1798 desc.frameCount = mFrameCount;
1799 desc.latency = latency();
1800 param2 = &desc;
1801 break;
1802
1803 case AudioSystem::STREAM_CONFIG_CHANGED:
1804 param2 = &param;
1805 case AudioSystem::OUTPUT_CLOSED:
1806 default:
1807 break;
1808 }
1809 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1810}
1811
1812void AudioFlinger::PlaybackThread::readOutputParameters()
1813{
Dima Zavin799a70e2011-04-18 16:57:27 -07001814 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001815 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1816 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001817 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001818 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001819 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001820
1821 // FIXME - Current mixer implementation only supports stereo output: Always
1822 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001823 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001824 mMixBuffer = new int16_t[mFrameCount * 2];
1825 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1826
Eric Laurentde070132010-07-13 04:45:46 -07001827 // force reconfiguration of effect chains and engines to take new buffer size and audio
1828 // parameters into account
1829 // Note that mLock is not held when readOutputParameters() is called from the constructor
1830 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1831 // matter.
1832 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1833 Vector< sp<EffectChain> > effectChains = mEffectChains;
1834 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001835 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001836 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001837}
1838
1839status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1840{
Glenn Kastena0d68332012-01-27 16:47:15 -08001841 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001842 return BAD_VALUE;
1843 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001844 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001845 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001846 return INVALID_OPERATION;
1847 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001848 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001849
Dima Zavin799a70e2011-04-18 16:57:27 -07001850 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001851}
1852
Eric Laurent39e94f82010-07-28 01:32:47 -07001853uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001854{
1855 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001856 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001857 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001858 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001859 }
1860
1861 for (size_t i = 0; i < mTracks.size(); ++i) {
1862 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001863 if (sessionId == track->sessionId() &&
1864 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001865 result |= TRACK_SESSION;
1866 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001867 }
1868 }
1869
Eric Laurent39e94f82010-07-28 01:32:47 -07001870 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001871}
1872
Eric Laurentde070132010-07-13 04:45:46 -07001873uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1874{
Dima Zavinfce7a472011-04-19 22:30:36 -07001875 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001876 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001877 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1878 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001879 }
1880 for (size_t i = 0; i < mTracks.size(); i++) {
1881 sp<Track> track = mTracks[i];
1882 if (sessionId == track->sessionId() &&
1883 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001884 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07001885 }
1886 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001887 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001888}
1889
Mathias Agopian65ab4712010-07-14 17:59:35 -07001890
Glenn Kastenaed850d2012-01-26 09:46:34 -08001891AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001892{
1893 Mutex::Autolock _l(mLock);
1894 return mOutput;
1895}
1896
1897AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1898{
1899 Mutex::Autolock _l(mLock);
1900 AudioStreamOut *output = mOutput;
1901 mOutput = NULL;
1902 return output;
1903}
1904
1905// this method must always be called either with ThreadBase mLock held or inside the thread loop
1906audio_stream_t* AudioFlinger::PlaybackThread::stream()
1907{
1908 if (mOutput == NULL) {
1909 return NULL;
1910 }
1911 return &mOutput->stream->common;
1912}
1913
Eric Laurent162b40b2011-12-05 09:47:19 -08001914uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1915{
1916 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1917 // decoding and transfer time. So sleeping for half of the latency would likely cause
1918 // underruns
1919 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1920 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1921 } else {
1922 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1923 }
1924}
1925
Mathias Agopian65ab4712010-07-14 17:59:35 -07001926// ----------------------------------------------------------------------------
1927
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001928AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001929 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten000f0e32012-03-01 17:10:56 -08001930 : PlaybackThread(audioFlinger, output, id, device, type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001931{
Glenn Kasten000f0e32012-03-01 17:10:56 -08001932 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001933 // FIXME - Current mixer implementation only supports stereo output
1934 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001935 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001936 }
1937}
1938
1939AudioFlinger::MixerThread::~MixerThread()
1940{
1941 delete mAudioMixer;
1942}
1943
Glenn Kasten83efdd02012-02-24 07:21:32 -08001944class CpuStats {
1945public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08001946 CpuStats();
1947 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08001948#ifdef DEBUG_CPU_USAGE
1949private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08001950 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
1951 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
1952
1953 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
1954
1955 int mCpuNum; // thread's current CPU number
1956 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08001957#endif
1958};
1959
Glenn Kasten190a46f2012-03-06 11:27:10 -08001960CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08001961#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08001962 : mCpuNum(-1), mCpukHz(-1)
1963#endif
1964{
1965}
1966
1967void CpuStats::sample(const String8 &title) {
1968#ifdef DEBUG_CPU_USAGE
1969 // get current thread's delta CPU time in wall clock ns
1970 double wcNs;
1971 bool valid = mCpuUsage.sampleAndEnable(wcNs);
1972
1973 // record sample for wall clock statistics
1974 if (valid) {
1975 mWcStats.sample(wcNs);
1976 }
1977
1978 // get the current CPU number
1979 int cpuNum = sched_getcpu();
1980
1981 // get the current CPU frequency in kHz
1982 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
1983
1984 // check if either CPU number or frequency changed
1985 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
1986 mCpuNum = cpuNum;
1987 mCpukHz = cpukHz;
1988 // ignore sample for purposes of cycles
1989 valid = false;
1990 }
1991
1992 // if no change in CPU number or frequency, then record sample for cycle statistics
1993 if (valid && mCpukHz > 0) {
1994 double cycles = wcNs * cpukHz * 0.000001;
1995 mHzStats.sample(cycles);
1996 }
1997
1998 unsigned n = mWcStats.n();
1999 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002000 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002001 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002002 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2003 double perLoop = elapsed / (double) n;
2004 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002005 double perLoop1k = perLoop * 0.001;
2006 double mean = mWcStats.mean();
2007 double stddev = mWcStats.stddev();
2008 double minimum = mWcStats.minimum();
2009 double maximum = mWcStats.maximum();
2010 double meanCycles = mHzStats.mean();
2011 double stddevCycles = mHzStats.stddev();
2012 double minCycles = mHzStats.minimum();
2013 double maxCycles = mHzStats.maximum();
2014 mCpuUsage.resetElapsed();
2015 mWcStats.reset();
2016 mHzStats.reset();
2017 ALOGD("CPU usage for %s over past %.1f secs\n"
2018 " (%u mixer loops at %.1f mean ms per loop):\n"
2019 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2020 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2021 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2022 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002023 elapsed * .000000001, n, perLoop * .000001,
2024 mean * .001,
2025 stddev * .001,
2026 minimum * .001,
2027 maximum * .001,
2028 mean / perLoop100,
2029 stddev / perLoop100,
2030 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002031 maximum / perLoop100,
2032 meanCycles / perLoop1k,
2033 stddevCycles / perLoop1k,
2034 minCycles / perLoop1k,
2035 maxCycles / perLoop1k);
2036
Glenn Kasten83efdd02012-02-24 07:21:32 -08002037 }
2038 }
2039#endif
2040};
2041
Glenn Kasten37d825e2012-02-24 07:21:48 -08002042void AudioFlinger::PlaybackThread::checkSilentMode_l()
2043{
2044 if (!mMasterMute) {
2045 char value[PROPERTY_VALUE_MAX];
2046 if (property_get("ro.audio.silent", value, "0") > 0) {
2047 char *endptr;
2048 unsigned long ul = strtoul(value, &endptr, 0);
2049 if (*endptr == '\0' && ul != 0) {
2050 ALOGD("Silence is golden");
2051 // The setprop command will not allow a property to be changed after
2052 // the first time it is set, so we don't have to worry about un-muting.
2053 setMasterMute_l(true);
2054 }
2055 }
2056 }
2057}
2058
Glenn Kasten000f0e32012-03-01 17:10:56 -08002059bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002060{
2061 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002062
Glenn Kasten000f0e32012-03-01 17:10:56 -08002063 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002064
2065 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002066 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002067if (mType == MIXER) {
2068 longStandbyExit = false;
2069}
Glenn Kasten688a6402012-02-29 07:57:06 -08002070
Glenn Kasten000f0e32012-03-01 17:10:56 -08002071 // DUPLICATING
2072 // FIXME could this be made local to while loop?
2073 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002074
Glenn Kasten66fcab92012-02-24 14:59:21 -08002075 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002076 sleepTime = idleSleepTime;
2077
2078if (mType == MIXER) {
2079 sleepTimeShift = 0;
2080}
2081
Glenn Kasten83efdd02012-02-24 07:21:32 -08002082 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002083 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002084
Eric Laurentfeb0db62011-07-22 09:04:31 -07002085 acquireWakeLock();
2086
Mathias Agopian65ab4712010-07-14 17:59:35 -07002087 while (!exitPending())
2088 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002089 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002090
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002091 Vector< sp<EffectChain> > effectChains;
2092
Mathias Agopian65ab4712010-07-14 17:59:35 -07002093 processConfigEvents();
2094
Mathias Agopian65ab4712010-07-14 17:59:35 -07002095 { // scope for mLock
2096
2097 Mutex::Autolock _l(mLock);
2098
2099 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002100 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002101 }
2102
Glenn Kastenfa26a852012-03-06 11:28:04 -08002103 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002104
Mathias Agopian65ab4712010-07-14 17:59:35 -07002105 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002106 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002107 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002108 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002109
2110 threadLoop_standby();
2111
Mathias Agopian65ab4712010-07-14 17:59:35 -07002112 mStandby = true;
2113 mBytesWritten = 0;
2114 }
2115
Glenn Kasten3e074702012-02-28 18:40:35 -08002116 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002117 // we're about to wait, flush the binder command buffer
2118 IPCThreadState::self()->flushCommands();
2119
Glenn Kastenfa26a852012-03-06 11:28:04 -08002120 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002121
Mathias Agopian65ab4712010-07-14 17:59:35 -07002122 if (exitPending()) break;
2123
Eric Laurentfeb0db62011-07-22 09:04:31 -07002124 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002125 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002126 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002127 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002128 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002129 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002130
Eric Laurent27741442012-01-17 19:20:12 -08002131 mPrevMixerStatus = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002132
Glenn Kasten37d825e2012-02-24 07:21:48 -08002133 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002134
Glenn Kasten000f0e32012-03-01 17:10:56 -08002135 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002136 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002137 if (mType == MIXER) {
2138 sleepTimeShift = 0;
2139 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002140
Mathias Agopian65ab4712010-07-14 17:59:35 -07002141 continue;
2142 }
2143 }
2144
Glenn Kastenfec279f2012-03-08 07:47:15 -08002145 mixer_state newMixerStatus = prepareTracks_l(&tracksToRemove);
2146 // Shift in the new status; this could be a queue if it's
2147 // useful to filter the mixer status over several cycles.
2148 mPrevMixerStatus = mMixerStatus;
2149 mMixerStatus = newMixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002150
2151 // prevent any changes in effect chain list and in each effect chain
2152 // during mixing and effect process as the audio buffers could be deleted
2153 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002154 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002155 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002156
Glenn Kastenfec279f2012-03-08 07:47:15 -08002157 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002158 threadLoop_mix();
2159 } else {
2160 threadLoop_sleepTime();
2161 }
2162
2163 if (mSuspended > 0) {
2164 sleepTime = suspendSleepTimeUs();
2165 }
2166
2167 // only process effects if we're going to write
2168 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002169 for (size_t i = 0; i < effectChains.size(); i ++) {
2170 effectChains[i]->process_l();
2171 }
2172 }
2173
2174 // enable changes in effect chain
2175 unlockEffectChains(effectChains);
2176
2177 // sleepTime == 0 means we must write to audio hardware
2178 if (sleepTime == 0) {
2179
2180 threadLoop_write();
2181
2182if (mType == MIXER) {
2183 // write blocked detection
2184 nsecs_t now = systemTime();
2185 nsecs_t delta = now - mLastWriteTime;
2186 if (!mStandby && delta > maxPeriod) {
2187 mNumDelayedWrites++;
2188 if ((now - lastWarning) > kWarningThrottleNs) {
2189 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2190 ns2ms(delta), mNumDelayedWrites, this);
2191 lastWarning = now;
2192 }
2193 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2194 // a different threshold. Or completely removed for what it is worth anyway...
2195 if (mStandby) {
2196 longStandbyExit = true;
2197 }
2198 }
2199}
2200
2201 mStandby = false;
2202 } else {
2203 usleep(sleepTime);
2204 }
2205
2206 // finally let go of removed track(s), without the lock held
2207 // since we can't guarantee the destructors won't acquire that
2208 // same lock.
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002209 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002210
Glenn Kastenfa26a852012-03-06 11:28:04 -08002211 // FIXME I don't understand the need for this here;
2212 // it was in the original code but maybe the
2213 // assignment in saveOutputTracks() makes this unnecessary?
2214 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002215
2216 // Effect chains will be actually deleted here if they were removed from
2217 // mEffectChains list during mixing or effects processing
2218 effectChains.clear();
2219
2220 // FIXME Note that the above .clear() is no longer necessary since effectChains
2221 // is now local to this block, but will keep it for now (at least until merge done).
2222 }
2223
2224if (mType == MIXER || mType == DIRECT) {
2225 // put output stream into standby mode
2226 if (!mStandby) {
2227 mOutput->stream->common.standby(&mOutput->stream->common);
2228 }
2229}
2230if (mType == DUPLICATING) {
2231 // for DuplicatingThread, standby mode is handled by the outputTracks
2232}
2233
2234 releaseWakeLock();
2235
2236 ALOGV("Thread %p type %d exiting", this, mType);
2237 return false;
2238}
2239
2240// shared by MIXER and DIRECT, overridden by DUPLICATING
2241void AudioFlinger::PlaybackThread::threadLoop_write()
2242{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002243 // FIXME rewrite to reduce number of system calls
2244 mLastWriteTime = systemTime();
2245 mInWrite = true;
2246 mBytesWritten += mixBufferSize;
2247 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2248 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2249 mNumWrites++;
2250 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002251}
2252
2253// shared by MIXER and DIRECT, overridden by DUPLICATING
2254void AudioFlinger::PlaybackThread::threadLoop_standby()
2255{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002256 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2257 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002258}
2259
2260void AudioFlinger::MixerThread::threadLoop_mix()
2261{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002262 // obtain the presentation timestamp of the next output buffer
2263 int64_t pts;
2264 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002265
Glenn Kasten952eeb22012-03-06 11:30:57 -08002266 if (NULL != mOutput->stream->get_next_write_timestamp) {
2267 status = mOutput->stream->get_next_write_timestamp(
2268 mOutput->stream, &pts);
2269 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002270
Glenn Kasten952eeb22012-03-06 11:30:57 -08002271 if (status != NO_ERROR) {
2272 pts = AudioBufferProvider::kInvalidPTS;
2273 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002274
Glenn Kasten952eeb22012-03-06 11:30:57 -08002275 // mix buffers...
2276 mAudioMixer->process(pts);
2277 // increase sleep time progressively when application underrun condition clears.
2278 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2279 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2280 // such that we would underrun the audio HAL.
2281 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2282 sleepTimeShift--;
2283 }
2284 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002285 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002286 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002287}
2288
2289void AudioFlinger::MixerThread::threadLoop_sleepTime()
2290{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002291 // If no tracks are ready, sleep once for the duration of an output
2292 // buffer size, then write 0s to the output
2293 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002294 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002295 sleepTime = activeSleepTime >> sleepTimeShift;
2296 if (sleepTime < kMinThreadSleepTimeUs) {
2297 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002298 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002299 // reduce sleep time in case of consecutive application underruns to avoid
2300 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2301 // duration we would end up writing less data than needed by the audio HAL if
2302 // the condition persists.
2303 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2304 sleepTimeShift++;
2305 }
2306 } else {
2307 sleepTime = idleSleepTime;
2308 }
2309 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002310 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002311 memset (mMixBuffer, 0, mixBufferSize);
2312 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002313 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002314 }
2315 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002316}
2317
2318// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002319AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002320 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002321{
2322
Glenn Kasten29c23c32012-01-26 13:37:52 -08002323 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002324 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002325 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002326 size_t mixedTracks = 0;
2327 size_t tracksWithEffect = 0;
2328
2329 float masterVolume = mMasterVolume;
2330 bool masterMute = mMasterMute;
2331
Eric Laurent571d49c2010-08-11 05:20:11 -07002332 if (masterMute) {
2333 masterVolume = 0;
2334 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002335 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002336 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002337 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002338 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002339 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002340 masterVolume = (float)((v + (1 << 23)) >> 24);
2341 chain.clear();
2342 }
2343
2344 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002345 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002346 if (t == 0) continue;
2347
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002348 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002349 Track* const track = t.get();
2350 audio_track_cblk_t* cblk = track->cblk();
2351
2352 // The first time a track is added we wait
2353 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002354 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002355 // make sure that we have enough frames to mix one full buffer.
2356 // enforce this condition only once to enable draining the buffer in case the client
2357 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002358 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002359 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002360 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002361 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002362 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002363 if (t->sampleRate() == (int)mSampleRate) {
2364 minFrames = mFrameCount;
2365 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002366 // +1 for rounding and +1 for additional sample needed for interpolation
2367 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2368 // add frames already consumed but not yet released by the resampler
2369 // because cblk->framesReady() will include these frames
2370 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2371 // the minimum track buffer size is normally twice the number of frames necessary
2372 // to fill one buffer and the resampler should not leave more than one buffer worth
2373 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002374 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002375 }
2376 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002377 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002378 !track->isPaused() && !track->isTerminated())
2379 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002380 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002381
2382 mixedTracks++;
2383
2384 // track->mainBuffer() != mMixBuffer means there is an effect chain
2385 // connected to the track
2386 chain.clear();
2387 if (track->mainBuffer() != mMixBuffer) {
2388 chain = getEffectChain_l(track->sessionId());
2389 // Delegate volume control to effect in track effect chain if needed
2390 if (chain != 0) {
2391 tracksWithEffect++;
2392 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002393 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002394 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002395 }
2396 }
2397
2398
2399 int param = AudioMixer::VOLUME;
2400 if (track->mFillingUpStatus == Track::FS_FILLED) {
2401 // no ramp for the first volume setting
2402 track->mFillingUpStatus = Track::FS_ACTIVE;
2403 if (track->mState == TrackBase::RESUMING) {
2404 track->mState = TrackBase::ACTIVE;
2405 param = AudioMixer::RAMP_VOLUME;
2406 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002407 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002408 } else if (cblk->server != 0) {
2409 // If the track is stopped before the first frame was mixed,
2410 // do not apply ramp
2411 param = AudioMixer::RAMP_VOLUME;
2412 }
2413
2414 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002415 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002416 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002417 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002418 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002419 if (track->isPausing()) {
2420 track->setPaused();
2421 }
2422 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002423
Mathias Agopian65ab4712010-07-14 17:59:35 -07002424 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002425 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002426 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002427 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002428 vl = vlr & 0xFFFF;
2429 vr = vlr >> 16;
2430 // track volumes come from shared memory, so can't be trusted and must be clamped
2431 if (vl > MAX_GAIN_INT) {
2432 ALOGV("Track left volume out of range: %04X", vl);
2433 vl = MAX_GAIN_INT;
2434 }
2435 if (vr > MAX_GAIN_INT) {
2436 ALOGV("Track right volume out of range: %04X", vr);
2437 vr = MAX_GAIN_INT;
2438 }
2439 // now apply the master volume and stream type volume
2440 vl = (uint32_t)(v * vl) << 12;
2441 vr = (uint32_t)(v * vr) << 12;
2442 // assuming master volume and stream type volume each go up to 1.0,
2443 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002444
Glenn Kasten05632a52012-01-03 14:22:33 -08002445 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2446 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002447 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002448 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002449 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002450 }
2451 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002452 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002453 // Delegate volume control to effect in track effect chain if needed
2454 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2455 // Do not ramp volume if volume is controlled by effect
2456 param = AudioMixer::VOLUME;
2457 track->mHasVolumeController = true;
2458 } else {
2459 // force no volume ramp when volume controller was just disabled or removed
2460 // from effect chain to avoid volume spike
2461 if (track->mHasVolumeController) {
2462 param = AudioMixer::VOLUME;
2463 }
2464 track->mHasVolumeController = false;
2465 }
2466
2467 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002468 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002469 vl = (vl + (1 << 11)) >> 12;
2470 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2471 vr = (vr + (1 << 11)) >> 12;
2472 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002473
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002474 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 -07002475
Mathias Agopian65ab4712010-07-14 17:59:35 -07002476 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002477 mAudioMixer->setBufferProvider(name, track);
2478 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002479
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002480 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2481 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2482 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002483 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002484 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485 AudioMixer::TRACK,
2486 AudioMixer::FORMAT, (void *)track->format());
2487 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002488 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002489 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002490 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002491 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002492 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002493 AudioMixer::RESAMPLE,
2494 AudioMixer::SAMPLE_RATE,
2495 (void *)(cblk->sampleRate));
2496 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002497 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002498 AudioMixer::TRACK,
2499 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2500 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002501 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002502 AudioMixer::TRACK,
2503 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2504
2505 // reset retry count
2506 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002507 // If one track is ready, set the mixer ready if:
2508 // - the mixer was not ready during previous round OR
2509 // - no other track is not ready
2510 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2511 mixerStatus != MIXER_TRACKS_ENABLED) {
2512 mixerStatus = MIXER_TRACKS_READY;
2513 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002514 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002515 //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 -07002516 if (track->isStopped()) {
2517 track->reset();
2518 }
2519 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2520 // We have consumed all the buffers of this track.
2521 // Remove it from the list of active tracks.
2522 tracksToRemove->add(track);
2523 } else {
2524 // No buffers for this track. Give it a few chances to
2525 // fill a buffer, then remove it from active list.
2526 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002527 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002528 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002529 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002530 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002531 // If one track is not ready, mark the mixer also not ready if:
2532 // - the mixer was ready during previous round OR
2533 // - no other track is ready
2534 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2535 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002536 mixerStatus = MIXER_TRACKS_ENABLED;
2537 }
2538 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002539 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002540 }
2541 }
2542
2543 // remove all the tracks that need to be...
2544 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002545 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002546 for (size_t i=0 ; i<count ; i++) {
2547 const sp<Track>& track = tracksToRemove->itemAt(i);
2548 mActiveTracks.remove(track);
2549 if (track->mainBuffer() != mMixBuffer) {
2550 chain = getEffectChain_l(track->sessionId());
2551 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002552 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002553 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002554 }
2555 }
2556 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002557 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002558 }
2559 }
2560 }
2561
2562 // mix buffer must be cleared if all tracks are connected to an
2563 // effect chain as in this case the mixer will not write to
2564 // mix buffer and track effects will accumulate into it
2565 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2566 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2567 }
2568
2569 return mixerStatus;
2570}
2571
Glenn Kasten66fcab92012-02-24 14:59:21 -08002572/*
2573The derived values that are cached:
2574 - mixBufferSize from frame count * frame size
2575 - activeSleepTime from activeSleepTimeUs()
2576 - idleSleepTime from idleSleepTimeUs()
2577 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2578 - maxPeriod from frame count and sample rate (MIXER only)
2579
2580The parameters that affect these derived values are:
2581 - frame count
2582 - frame size
2583 - sample rate
2584 - device type: A2DP or not
2585 - device latency
2586 - format: PCM or not
2587 - active sleep time
2588 - idle sleep time
2589*/
2590
2591void AudioFlinger::PlaybackThread::cacheParameters_l()
2592{
2593 mixBufferSize = mFrameCount * mFrameSize;
2594 activeSleepTime = activeSleepTimeUs();
2595 idleSleepTime = idleSleepTimeUs();
2596}
2597
Glenn Kastenfff6d712012-01-12 16:38:12 -08002598void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002599{
Steve Block3856b092011-10-20 11:56:00 +01002600 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002601 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002602 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002603
Mathias Agopian65ab4712010-07-14 17:59:35 -07002604 size_t size = mTracks.size();
2605 for (size_t i = 0; i < size; i++) {
2606 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08002607 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002608 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002609 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002610 }
2611 }
2612}
2613
Glenn Kastenfff6d712012-01-12 16:38:12 -08002614void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002615{
Steve Block3856b092011-10-20 11:56:00 +01002616 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002617 this, streamType, valid);
2618 Mutex::Autolock _l(mLock);
2619
2620 mStreamTypes[streamType].valid = valid;
2621}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002622
2623// getTrackName_l() must be called with ThreadBase::mLock held
2624int AudioFlinger::MixerThread::getTrackName_l()
2625{
2626 return mAudioMixer->getTrackName();
2627}
2628
2629// deleteTrackName_l() must be called with ThreadBase::mLock held
2630void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2631{
Steve Block3856b092011-10-20 11:56:00 +01002632 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002633 mAudioMixer->deleteTrackName(name);
2634}
2635
2636// checkForNewParameters_l() must be called with ThreadBase::mLock held
2637bool AudioFlinger::MixerThread::checkForNewParameters_l()
2638{
2639 bool reconfig = false;
2640
2641 while (!mNewParameters.isEmpty()) {
2642 status_t status = NO_ERROR;
2643 String8 keyValuePair = mNewParameters[0];
2644 AudioParameter param = AudioParameter(keyValuePair);
2645 int value;
2646
2647 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2648 reconfig = true;
2649 }
2650 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002651 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002652 status = BAD_VALUE;
2653 } else {
2654 reconfig = true;
2655 }
2656 }
2657 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002658 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002659 status = BAD_VALUE;
2660 } else {
2661 reconfig = true;
2662 }
2663 }
2664 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2665 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002666 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002667 // if frame count is changed after track creation
2668 if (!mTracks.isEmpty()) {
2669 status = INVALID_OPERATION;
2670 } else {
2671 reconfig = true;
2672 }
2673 }
2674 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002675 // when changing the audio output device, call addBatteryData to notify
2676 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002677 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002678 uint32_t params = 0;
2679 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002680 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002681 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2682 }
2683
2684 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002685 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002686 // check if any other device (except speaker) is on
2687 if (value & deviceWithoutSpeaker ) {
2688 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2689 }
2690
2691 if (params != 0) {
2692 addBatteryData(params);
2693 }
2694 }
2695
Mathias Agopian65ab4712010-07-14 17:59:35 -07002696 // forward device change to effects that have requested to be
2697 // aware of attached audio device.
2698 mDevice = (uint32_t)value;
2699 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002700 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002701 }
2702 }
2703
2704 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002705 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002706 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002707 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002708 mOutput->stream->common.standby(&mOutput->stream->common);
2709 mStandby = true;
2710 mBytesWritten = 0;
2711 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002712 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002713 }
2714 if (status == NO_ERROR && reconfig) {
2715 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002716 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2717 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002718 readOutputParameters();
2719 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2720 for (size_t i = 0; i < mTracks.size() ; i++) {
2721 int name = getTrackName_l();
2722 if (name < 0) break;
2723 mTracks[i]->mName = name;
2724 // limit track sample rate to 2 x new output sample rate
2725 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2726 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2727 }
2728 }
2729 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2730 }
2731 }
2732
2733 mNewParameters.removeAt(0);
2734
2735 mParamStatus = status;
2736 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002737 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2738 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002739 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002740 }
2741 return reconfig;
2742}
2743
2744status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2745{
2746 const size_t SIZE = 256;
2747 char buffer[SIZE];
2748 String8 result;
2749
2750 PlaybackThread::dumpInternals(fd, args);
2751
2752 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2753 result.append(buffer);
2754 write(fd, result.string(), result.size());
2755 return NO_ERROR;
2756}
2757
Mathias Agopian65ab4712010-07-14 17:59:35 -07002758uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2759{
Eric Laurent60e18242010-07-29 06:50:24 -07002760 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002761}
2762
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002763uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2764{
2765 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2766}
2767
Glenn Kasten66fcab92012-02-24 14:59:21 -08002768void AudioFlinger::MixerThread::cacheParameters_l()
2769{
2770 PlaybackThread::cacheParameters_l();
2771
2772 // FIXME: Relaxed timing because of a certain device that can't meet latency
2773 // Should be reduced to 2x after the vendor fixes the driver issue
2774 // increase threshold again due to low power audio mode. The way this warning
2775 // threshold is calculated and its usefulness should be reconsidered anyway.
2776 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
2777}
2778
Mathias Agopian65ab4712010-07-14 17:59:35 -07002779// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002780AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2781 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002782 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002783 // mLeftVolFloat, mRightVolFloat
2784 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002785{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002786}
2787
2788AudioFlinger::DirectOutputThread::~DirectOutputThread()
2789{
2790}
2791
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002792AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
2793 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08002794)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002795{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002796 sp<Track> trackToRemove;
2797
Glenn Kastenfec279f2012-03-08 07:47:15 -08002798 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002799
Glenn Kasten952eeb22012-03-06 11:30:57 -08002800 // find out which tracks need to be processed
2801 if (mActiveTracks.size() != 0) {
2802 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08002803 // The track died recently
2804 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002805
Glenn Kasten952eeb22012-03-06 11:30:57 -08002806 Track* const track = t.get();
2807 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002808
Glenn Kasten952eeb22012-03-06 11:30:57 -08002809 // The first time a track is added we wait
2810 // for all its buffers to be filled before processing it
2811 if (cblk->framesReady() && track->isReady() &&
2812 !track->isPaused() && !track->isTerminated())
2813 {
2814 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002815
Glenn Kasten952eeb22012-03-06 11:30:57 -08002816 if (track->mFillingUpStatus == Track::FS_FILLED) {
2817 track->mFillingUpStatus = Track::FS_ACTIVE;
2818 mLeftVolFloat = mRightVolFloat = 0;
2819 mLeftVolShort = mRightVolShort = 0;
2820 if (track->mState == TrackBase::RESUMING) {
2821 track->mState = TrackBase::ACTIVE;
2822 rampVolume = true;
2823 }
2824 } else if (cblk->server != 0) {
2825 // If the track is stopped before the first frame was mixed,
2826 // do not apply ramp
2827 rampVolume = true;
2828 }
2829 // compute volume for this track
2830 float left, right;
2831 if (track->isMuted() || mMasterMute || track->isPausing() ||
2832 mStreamTypes[track->streamType()].mute) {
2833 left = right = 0;
2834 if (track->isPausing()) {
2835 track->setPaused();
2836 }
2837 } else {
2838 float typeVolume = mStreamTypes[track->streamType()].volume;
2839 float v = mMasterVolume * typeVolume;
2840 uint32_t vlr = cblk->getVolumeLR();
2841 float v_clamped = v * (vlr & 0xFFFF);
2842 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2843 left = v_clamped/MAX_GAIN;
2844 v_clamped = v * (vlr >> 16);
2845 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2846 right = v_clamped/MAX_GAIN;
2847 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002848
Glenn Kasten952eeb22012-03-06 11:30:57 -08002849 if (left != mLeftVolFloat || right != mRightVolFloat) {
2850 mLeftVolFloat = left;
2851 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002852
Glenn Kasten952eeb22012-03-06 11:30:57 -08002853 // If audio HAL implements volume control,
2854 // force software volume to nominal value
2855 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
2856 left = 1.0f;
2857 right = 1.0f;
2858 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002859
Glenn Kasten952eeb22012-03-06 11:30:57 -08002860 // Convert volumes from float to 8.24
2861 uint32_t vl = (uint32_t)(left * (1 << 24));
2862 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002863
Glenn Kasten952eeb22012-03-06 11:30:57 -08002864 // Delegate volume control to effect in track effect chain if needed
2865 // only one effect chain can be present on DirectOutputThread, so if
2866 // there is one, the track is connected to it
2867 if (!mEffectChains.isEmpty()) {
2868 // Do not ramp volume if volume is controlled by effect
2869 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002870 rampVolume = false;
2871 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002872 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002873
Glenn Kasten952eeb22012-03-06 11:30:57 -08002874 // Convert volumes from 8.24 to 4.12 format
2875 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2876 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2877 leftVol = (uint16_t)v_clamped;
2878 v_clamped = (vr + (1 << 11)) >> 12;
2879 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2880 rightVol = (uint16_t)v_clamped;
2881 } else {
2882 leftVol = mLeftVolShort;
2883 rightVol = mRightVolShort;
2884 rampVolume = false;
2885 }
2886
2887 // reset retry count
2888 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002889 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002890 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002891 } else {
2892 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2893 if (track->isStopped()) {
2894 track->reset();
2895 }
2896 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2897 // We have consumed all the buffers of this track.
2898 // Remove it from the list of active tracks.
2899 trackToRemove = track;
2900 } else {
2901 // No buffers for this track. Give it a few chances to
2902 // fill a buffer, then remove it from active list.
2903 if (--(track->mRetryCount) <= 0) {
2904 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2905 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002906 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002907 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002908 }
2909 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002910 }
2911 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002912
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002913 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08002914 // remove all the tracks that need to be...
2915 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002916 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002917 mActiveTracks.remove(trackToRemove);
2918 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002919 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08002920 trackToRemove->sessionId());
2921 mEffectChains[0]->decActiveTrackCnt();
2922 }
2923 if (trackToRemove->isTerminated()) {
2924 removeTrack_l(trackToRemove);
2925 }
2926 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002927
Glenn Kastenfec279f2012-03-08 07:47:15 -08002928 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002929}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002930
Glenn Kasten000f0e32012-03-01 17:10:56 -08002931void AudioFlinger::DirectOutputThread::threadLoop_mix()
2932{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002933 AudioBufferProvider::Buffer buffer;
2934 size_t frameCount = mFrameCount;
2935 int8_t *curBuf = (int8_t *)mMixBuffer;
2936 // output audio to hardware
2937 while (frameCount) {
2938 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002939 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002940 if (CC_UNLIKELY(buffer.raw == NULL)) {
2941 memset(curBuf, 0, frameCount * mFrameSize);
2942 break;
2943 }
2944 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2945 frameCount -= buffer.frameCount;
2946 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002947 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002948 }
2949 sleepTime = 0;
2950 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002951 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08002952
2953 // apply volume
2954
2955 // Do not apply volume on compressed audio
2956 if (!audio_is_linear_pcm(mFormat)) {
2957 return;
2958 }
2959
2960 // convert to signed 16 bit before volume calculation
2961 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
2962 size_t count = mFrameCount * mChannelCount;
2963 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2964 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002965 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08002966 *dst-- = (int16_t)(*src--^0x80) << 8;
2967 }
2968 }
2969
2970 frameCount = mFrameCount;
2971 int16_t *out = mMixBuffer;
2972 if (rampVolume) {
2973 if (mChannelCount == 1) {
2974 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2975 int32_t vlInc = d / (int32_t)frameCount;
2976 int32_t vl = ((int32_t)mLeftVolShort << 16);
2977 do {
2978 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2979 out++;
2980 vl += vlInc;
2981 } while (--frameCount);
2982
2983 } else {
2984 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2985 int32_t vlInc = d / (int32_t)frameCount;
2986 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2987 int32_t vrInc = d / (int32_t)frameCount;
2988 int32_t vl = ((int32_t)mLeftVolShort << 16);
2989 int32_t vr = ((int32_t)mRightVolShort << 16);
2990 do {
2991 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2992 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2993 out += 2;
2994 vl += vlInc;
2995 vr += vrInc;
2996 } while (--frameCount);
2997 }
2998 } else {
2999 if (mChannelCount == 1) {
3000 do {
3001 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3002 out++;
3003 } while (--frameCount);
3004 } else {
3005 do {
3006 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3007 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3008 out += 2;
3009 } while (--frameCount);
3010 }
3011 }
3012
3013 // convert back to unsigned 8 bit after volume calculation
3014 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3015 size_t count = mFrameCount * mChannelCount;
3016 int16_t *src = mMixBuffer;
3017 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003018 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003019 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3020 }
3021 }
3022
3023 mLeftVolShort = leftVol;
3024 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003025}
3026
3027void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3028{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003029 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003030 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003031 sleepTime = activeSleepTime;
3032 } else {
3033 sleepTime = idleSleepTime;
3034 }
3035 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3036 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
3037 sleepTime = 0;
3038 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003039}
3040
3041// getTrackName_l() must be called with ThreadBase::mLock held
3042int AudioFlinger::DirectOutputThread::getTrackName_l()
3043{
3044 return 0;
3045}
3046
3047// deleteTrackName_l() must be called with ThreadBase::mLock held
3048void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3049{
3050}
3051
3052// checkForNewParameters_l() must be called with ThreadBase::mLock held
3053bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3054{
3055 bool reconfig = false;
3056
3057 while (!mNewParameters.isEmpty()) {
3058 status_t status = NO_ERROR;
3059 String8 keyValuePair = mNewParameters[0];
3060 AudioParameter param = AudioParameter(keyValuePair);
3061 int value;
3062
3063 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3064 // do not accept frame count changes if tracks are open as the track buffer
3065 // size depends on frame count and correct behavior would not be garantied
3066 // if frame count is changed after track creation
3067 if (!mTracks.isEmpty()) {
3068 status = INVALID_OPERATION;
3069 } else {
3070 reconfig = true;
3071 }
3072 }
3073 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003074 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003075 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003076 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003077 mOutput->stream->common.standby(&mOutput->stream->common);
3078 mStandby = true;
3079 mBytesWritten = 0;
3080 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003081 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003082 }
3083 if (status == NO_ERROR && reconfig) {
3084 readOutputParameters();
3085 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3086 }
3087 }
3088
3089 mNewParameters.removeAt(0);
3090
3091 mParamStatus = status;
3092 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003093 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3094 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003095 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003096 }
3097 return reconfig;
3098}
3099
3100uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
3101{
3102 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003103 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003104 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003105 } else {
3106 time = 10000;
3107 }
3108 return time;
3109}
3110
3111uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
3112{
3113 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003114 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003115 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003116 } else {
3117 time = 10000;
3118 }
3119 return time;
3120}
3121
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003122uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
3123{
3124 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003125 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003126 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3127 } else {
3128 time = 10000;
3129 }
3130 return time;
3131}
3132
Glenn Kasten66fcab92012-02-24 14:59:21 -08003133void AudioFlinger::DirectOutputThread::cacheParameters_l()
3134{
3135 PlaybackThread::cacheParameters_l();
3136
3137 // use shorter standby delay as on normal output to release
3138 // hardware resources as soon as possible
3139 standbyDelay = microseconds(activeSleepTime*2);
3140}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003141
Mathias Agopian65ab4712010-07-14 17:59:35 -07003142// ----------------------------------------------------------------------------
3143
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003144AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003145 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003146 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3147 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003148{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003149 addOutputTrack(mainThread);
3150}
3151
3152AudioFlinger::DuplicatingThread::~DuplicatingThread()
3153{
3154 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3155 mOutputTracks[i]->destroy();
3156 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003157}
3158
Glenn Kasten000f0e32012-03-01 17:10:56 -08003159void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003160{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003161 // mix buffers...
3162 if (outputsReady(outputTracks)) {
3163 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3164 } else {
3165 memset(mMixBuffer, 0, mixBufferSize);
3166 }
3167 sleepTime = 0;
3168 writeFrames = mFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003169}
3170
3171void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3172{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003173 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003174 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003175 sleepTime = activeSleepTime;
3176 } else {
3177 sleepTime = idleSleepTime;
3178 }
3179 } else if (mBytesWritten != 0) {
3180 // flush remaining overflow buffers in output tracks
3181 for (size_t i = 0; i < outputTracks.size(); i++) {
3182 if (outputTracks[i]->isActive()) {
3183 sleepTime = 0;
3184 writeFrames = 0;
3185 memset(mMixBuffer, 0, mixBufferSize);
3186 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003187 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003188 }
3189 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003190}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003191
Glenn Kasten000f0e32012-03-01 17:10:56 -08003192void AudioFlinger::DuplicatingThread::threadLoop_write()
3193{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003194 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003195 for (size_t i = 0; i < outputTracks.size(); i++) {
3196 outputTracks[i]->write(mMixBuffer, writeFrames);
3197 }
3198 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003199}
Glenn Kasten688a6402012-02-29 07:57:06 -08003200
Glenn Kasten000f0e32012-03-01 17:10:56 -08003201void AudioFlinger::DuplicatingThread::threadLoop_standby()
3202{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003203 // DuplicatingThread implements standby by stopping all tracks
3204 for (size_t i = 0; i < outputTracks.size(); i++) {
3205 outputTracks[i]->stop();
3206 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003207}
3208
Glenn Kastenfa26a852012-03-06 11:28:04 -08003209void AudioFlinger::DuplicatingThread::saveOutputTracks()
3210{
3211 outputTracks = mOutputTracks;
3212}
3213
3214void AudioFlinger::DuplicatingThread::clearOutputTracks()
3215{
3216 outputTracks.clear();
3217}
3218
Mathias Agopian65ab4712010-07-14 17:59:35 -07003219void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3220{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003221 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003222 // FIXME explain this formula
Mathias Agopian65ab4712010-07-14 17:59:35 -07003223 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003224 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003225 this,
3226 mSampleRate,
3227 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003228 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003229 frameCount);
3230 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003231 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003232 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003233 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003234 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003235 }
3236}
3237
3238void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3239{
3240 Mutex::Autolock _l(mLock);
3241 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003242 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003243 mOutputTracks[i]->destroy();
3244 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003245 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003246 return;
3247 }
3248 }
Steve Block3856b092011-10-20 11:56:00 +01003249 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003250}
3251
Glenn Kasten438b0362012-03-06 11:24:48 -08003252// caller must hold mLock
3253void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003254{
3255 mWaitTimeMs = UINT_MAX;
3256 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3257 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003258 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003259 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3260 if (waitTimeMs < mWaitTimeMs) {
3261 mWaitTimeMs = waitTimeMs;
3262 }
3263 }
3264 }
3265}
3266
3267
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003268bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003269{
3270 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003271 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003272 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003273 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003274 return false;
3275 }
3276 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3277 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003278 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003279 return false;
3280 }
3281 }
3282 return true;
3283}
3284
3285uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3286{
3287 return (mWaitTimeMs * 1000) / 2;
3288}
3289
Glenn Kasten66fcab92012-02-24 14:59:21 -08003290void AudioFlinger::DuplicatingThread::cacheParameters_l()
3291{
3292 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3293 updateWaitTime_l();
3294
3295 MixerThread::cacheParameters_l();
3296}
3297
Mathias Agopian65ab4712010-07-14 17:59:35 -07003298// ----------------------------------------------------------------------------
3299
3300// TrackBase constructor must be called with AudioFlinger::mLock held
3301AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003302 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003303 const sp<Client>& client,
3304 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003305 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003306 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003307 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003308 const sp<IMemory>& sharedBuffer,
3309 int sessionId)
3310 : RefBase(),
3311 mThread(thread),
3312 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003313 mCblk(NULL),
3314 // mBuffer
3315 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003316 mFrameCount(0),
3317 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003318 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003319 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003320 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003321 // mChannelCount
3322 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003323{
Steve Block3856b092011-10-20 11:56:00 +01003324 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003325
Steve Blockb8a80522011-12-20 16:23:08 +00003326 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003327 size_t size = sizeof(audio_track_cblk_t);
3328 uint8_t channelCount = popcount(channelMask);
3329 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3330 if (sharedBuffer == 0) {
3331 size += bufferSize;
3332 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003333
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003334 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003335 mCblkMemory = client->heap()->allocate(size);
3336 if (mCblkMemory != 0) {
3337 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003338 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003339 new(mCblk) audio_track_cblk_t();
3340 // clear all buffers
3341 mCblk->frameCount = frameCount;
3342 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003343 mChannelCount = channelCount;
3344 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003345 if (sharedBuffer == 0) {
3346 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3347 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3348 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003349 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003350 mCblk->flags = CBLK_UNDERRUN_ON;
3351 } else {
3352 mBuffer = sharedBuffer->pointer();
3353 }
3354 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3355 }
3356 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003357 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003358 client->heap()->dump("AudioTrack");
3359 return;
3360 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003361 } else {
3362 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3363 // construct the shared structure in-place.
3364 new(mCblk) audio_track_cblk_t();
3365 // clear all buffers
3366 mCblk->frameCount = frameCount;
3367 mCblk->sampleRate = sampleRate;
3368 mChannelCount = channelCount;
3369 mChannelMask = channelMask;
3370 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3371 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3372 // Force underrun condition to avoid false underrun callback until first data is
3373 // written to buffer (other flags are cleared)
3374 mCblk->flags = CBLK_UNDERRUN_ON;
3375 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3376 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003377}
3378
3379AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3380{
Glenn Kastena0d68332012-01-27 16:47:15 -08003381 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003382 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003383 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003384 } else {
3385 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003386 }
3387 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003388 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003389 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003390 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003391 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003392 // If the client's reference count drops to zero, the associated destructor
3393 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3394 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003395 mClient.clear();
3396 }
3397}
3398
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003399// AudioBufferProvider interface
3400// getNextBuffer() = 0;
3401// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07003402void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3403{
Glenn Kastene0feee32011-12-13 11:53:26 -08003404 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003405 mFrameCount = buffer->frameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003406 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003407 buffer->frameCount = 0;
3408}
3409
3410bool AudioFlinger::ThreadBase::TrackBase::step() {
3411 bool result;
3412 audio_track_cblk_t* cblk = this->cblk();
3413
3414 result = cblk->stepServer(mFrameCount);
3415 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003416 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003417 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003418 }
3419 return result;
3420}
3421
3422void AudioFlinger::ThreadBase::TrackBase::reset() {
3423 audio_track_cblk_t* cblk = this->cblk();
3424
3425 cblk->user = 0;
3426 cblk->server = 0;
3427 cblk->userBase = 0;
3428 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003429 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01003430 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003431}
3432
Mathias Agopian65ab4712010-07-14 17:59:35 -07003433int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3434 return (int)mCblk->sampleRate;
3435}
3436
Mathias Agopian65ab4712010-07-14 17:59:35 -07003437void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3438 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003439 size_t frameSize = cblk->frameSize;
3440 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3441 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003442
3443 // Check validity of returned pointer in case the track control block would have been corrupted.
3444 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003445 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003446 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 -07003447 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003448 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003449 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003450 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003451 }
3452
3453 return bufferStart;
3454}
3455
3456// ----------------------------------------------------------------------------
3457
3458// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3459AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003460 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003461 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003462 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003463 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003464 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003465 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003466 int frameCount,
3467 const sp<IMemory>& sharedBuffer,
3468 int sessionId)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003469 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003470 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3471 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003472{
3473 if (mCblk != NULL) {
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003474 if (thread != NULL) {
3475 mName = thread->getTrackName_l();
3476 mMainBuffer = thread->mixBuffer();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003477 }
Glenn Kasten23d82a92012-02-03 11:10:00 -08003478 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003479 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003480 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003481 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003482 mStreamType = streamType;
3483 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3484 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003485 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003486 }
3487}
3488
3489AudioFlinger::PlaybackThread::Track::~Track()
3490{
Steve Block3856b092011-10-20 11:56:00 +01003491 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003492 sp<ThreadBase> thread = mThread.promote();
3493 if (thread != 0) {
3494 Mutex::Autolock _l(thread->mLock);
3495 mState = TERMINATED;
3496 }
3497}
3498
3499void AudioFlinger::PlaybackThread::Track::destroy()
3500{
3501 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3502 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08003503 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003504 // we must acquire a strong reference on this Track before locking mLock
3505 // here so that the destructor is called only when exiting this function.
3506 // On the other hand, as long as Track::destroy() is only called by
3507 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3508 // this Track with its member mTrack.
3509 sp<Track> keep(this);
3510 { // scope for mLock
3511 sp<ThreadBase> thread = mThread.promote();
3512 if (thread != 0) {
3513 if (!isOutputTrack()) {
3514 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08003515 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003516
3517 // to track the speaker usage
3518 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003519 }
3520 AudioSystem::releaseOutput(thread->id());
3521 }
3522 Mutex::Autolock _l(thread->mLock);
3523 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3524 playbackThread->destroyTrack_l(this);
3525 }
3526 }
3527}
3528
3529void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3530{
Glenn Kasten83d86532012-01-17 14:39:34 -08003531 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003532 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 -07003533 mName - AudioMixer::TRACK0,
Glenn Kasten44deb052012-02-05 18:09:08 -08003534 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003535 mStreamType,
3536 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003537 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003538 mSessionId,
3539 mFrameCount,
3540 mState,
3541 mMute,
3542 mFillingUpStatus,
3543 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003544 vlr & 0xFFFF,
3545 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003546 mCblk->server,
3547 mCblk->user,
3548 (int)mMainBuffer,
3549 (int)mAuxBuffer);
3550}
3551
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003552// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08003553status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003554 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003555{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003556 audio_track_cblk_t* cblk = this->cblk();
3557 uint32_t framesReady;
3558 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003559
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003560 // Check if last stepServer failed, try to step now
3561 if (mStepServerFailed) {
3562 if (!step()) goto getNextBuffer_exit;
3563 ALOGV("stepServer recovered");
3564 mStepServerFailed = false;
3565 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003566
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003567 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003568
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003569 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003570 uint32_t s = cblk->server;
3571 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3572
3573 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3574 if (framesReq > framesReady) {
3575 framesReq = framesReady;
3576 }
3577 if (s + framesReq > bufferEnd) {
3578 framesReq = bufferEnd - s;
3579 }
3580
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003581 buffer->raw = getBuffer(s, framesReq);
3582 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003583
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003584 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003585 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003586 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003587
3588getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003589 buffer->raw = NULL;
3590 buffer->frameCount = 0;
3591 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3592 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003593}
3594
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003595uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08003596 return mCblk->framesReady();
3597}
3598
Mathias Agopian65ab4712010-07-14 17:59:35 -07003599bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003600 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003601
John Grossman4ff14ba2012-02-08 16:37:41 -08003602 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003603 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3604 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003605 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003606 return true;
3607 }
3608 return false;
3609}
3610
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003611status_t AudioFlinger::PlaybackThread::Track::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003612{
3613 status_t status = NO_ERROR;
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003614 ALOGV("start(%d), calling pid %d session %d tid %d",
3615 mName, IPCThreadState::self()->getCallingPid(), mSessionId, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003616 sp<ThreadBase> thread = mThread.promote();
3617 if (thread != 0) {
3618 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003619 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003620 // here the track could be either new, or restarted
3621 // in both cases "unstop" the track
3622 if (mState == PAUSED) {
3623 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003624 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003625 } else {
3626 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003627 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003628 }
3629
3630 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3631 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003632 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003633 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003634
3635 // to track the speaker usage
3636 if (status == NO_ERROR) {
3637 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3638 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003639 }
3640 if (status == NO_ERROR) {
3641 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3642 playbackThread->addTrack_l(this);
3643 } else {
3644 mState = state;
3645 }
3646 } else {
3647 status = BAD_VALUE;
3648 }
3649 return status;
3650}
3651
3652void AudioFlinger::PlaybackThread::Track::stop()
3653{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003654 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003655 sp<ThreadBase> thread = mThread.promote();
3656 if (thread != 0) {
3657 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003658 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003659 if (mState > STOPPED) {
3660 mState = STOPPED;
3661 // If the track is not active (PAUSED and buffers full), flush buffers
3662 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3663 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3664 reset();
3665 }
Steve Block3856b092011-10-20 11:56:00 +01003666 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003667 }
3668 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3669 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003670 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003671 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003672
3673 // to track the speaker usage
3674 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003675 }
3676 }
3677}
3678
3679void AudioFlinger::PlaybackThread::Track::pause()
3680{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003681 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003682 sp<ThreadBase> thread = mThread.promote();
3683 if (thread != 0) {
3684 Mutex::Autolock _l(thread->mLock);
3685 if (mState == ACTIVE || mState == RESUMING) {
3686 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003687 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003688 if (!isOutputTrack()) {
3689 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003690 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003691 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003692
3693 // to track the speaker usage
3694 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003695 }
3696 }
3697 }
3698}
3699
3700void AudioFlinger::PlaybackThread::Track::flush()
3701{
Steve Block3856b092011-10-20 11:56:00 +01003702 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003703 sp<ThreadBase> thread = mThread.promote();
3704 if (thread != 0) {
3705 Mutex::Autolock _l(thread->mLock);
3706 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3707 return;
3708 }
3709 // No point remaining in PAUSED state after a flush => go to
3710 // STOPPED state
3711 mState = STOPPED;
3712
Eric Laurent38ccae22011-03-28 18:37:07 -07003713 // do not reset the track if it is still in the process of being stopped or paused.
3714 // this will be done by prepareTracks_l() when the track is stopped.
3715 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3716 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3717 reset();
3718 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003719 }
3720}
3721
3722void AudioFlinger::PlaybackThread::Track::reset()
3723{
3724 // Do not reset twice to avoid discarding data written just after a flush and before
3725 // the audioflinger thread detects the track is stopped.
3726 if (!mResetDone) {
3727 TrackBase::reset();
3728 // Force underrun condition to avoid false underrun callback until first data is
3729 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003730 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3731 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003732 mFillingUpStatus = FS_FILLING;
3733 mResetDone = true;
3734 }
3735}
3736
3737void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3738{
3739 mMute = muted;
3740}
3741
Mathias Agopian65ab4712010-07-14 17:59:35 -07003742status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3743{
3744 status_t status = DEAD_OBJECT;
3745 sp<ThreadBase> thread = mThread.promote();
3746 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003747 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3748 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003749 }
3750 return status;
3751}
3752
3753void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3754{
3755 mAuxEffectId = EffectId;
3756 mAuxBuffer = buffer;
3757}
3758
John Grossman4ff14ba2012-02-08 16:37:41 -08003759// timed audio tracks
3760
3761sp<AudioFlinger::PlaybackThread::TimedTrack>
3762AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003763 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003764 const sp<Client>& client,
3765 audio_stream_type_t streamType,
3766 uint32_t sampleRate,
3767 audio_format_t format,
3768 uint32_t channelMask,
3769 int frameCount,
3770 const sp<IMemory>& sharedBuffer,
3771 int sessionId) {
3772 if (!client->reserveTimedTrack())
3773 return NULL;
3774
3775 sp<TimedTrack> track = new TimedTrack(
3776 thread, client, streamType, sampleRate, format, channelMask, frameCount,
3777 sharedBuffer, sessionId);
3778
3779 if (track == NULL) {
3780 client->releaseTimedTrack();
3781 return NULL;
3782 }
3783
3784 return track;
3785}
3786
3787AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003788 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003789 const sp<Client>& client,
3790 audio_stream_type_t streamType,
3791 uint32_t sampleRate,
3792 audio_format_t format,
3793 uint32_t channelMask,
3794 int frameCount,
3795 const sp<IMemory>& sharedBuffer,
3796 int sessionId)
3797 : Track(thread, client, streamType, sampleRate, format, channelMask,
3798 frameCount, sharedBuffer, sessionId),
3799 mTimedSilenceBuffer(NULL),
3800 mTimedSilenceBufferSize(0),
3801 mTimedAudioOutputOnTime(false),
3802 mMediaTimeTransformValid(false)
3803{
3804 LocalClock lc;
3805 mLocalTimeFreq = lc.getLocalFreq();
3806
3807 mLocalTimeToSampleTransform.a_zero = 0;
3808 mLocalTimeToSampleTransform.b_zero = 0;
3809 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3810 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3811 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3812 &mLocalTimeToSampleTransform.a_to_b_denom);
3813}
3814
3815AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3816 mClient->releaseTimedTrack();
3817 delete [] mTimedSilenceBuffer;
3818}
3819
3820status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3821 size_t size, sp<IMemory>* buffer) {
3822
3823 Mutex::Autolock _l(mTimedBufferQueueLock);
3824
3825 trimTimedBufferQueue_l();
3826
3827 // lazily initialize the shared memory heap for timed buffers
3828 if (mTimedMemoryDealer == NULL) {
3829 const int kTimedBufferHeapSize = 512 << 10;
3830
3831 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3832 "AudioFlingerTimed");
3833 if (mTimedMemoryDealer == NULL)
3834 return NO_MEMORY;
3835 }
3836
3837 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3838 if (newBuffer == NULL) {
3839 newBuffer = mTimedMemoryDealer->allocate(size);
3840 if (newBuffer == NULL)
3841 return NO_MEMORY;
3842 }
3843
3844 *buffer = newBuffer;
3845 return NO_ERROR;
3846}
3847
3848// caller must hold mTimedBufferQueueLock
3849void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
3850 int64_t mediaTimeNow;
3851 {
3852 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3853 if (!mMediaTimeTransformValid)
3854 return;
3855
3856 int64_t targetTimeNow;
3857 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
3858 ? mCCHelper.getCommonTime(&targetTimeNow)
3859 : mCCHelper.getLocalTime(&targetTimeNow);
3860
3861 if (OK != res)
3862 return;
3863
3864 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
3865 &mediaTimeNow)) {
3866 return;
3867 }
3868 }
3869
3870 size_t trimIndex;
3871 for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
3872 if (mTimedBufferQueue[trimIndex].pts() > mediaTimeNow)
3873 break;
3874 }
3875
3876 if (trimIndex) {
3877 mTimedBufferQueue.removeItemsAt(0, trimIndex);
3878 }
3879}
3880
3881status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
3882 const sp<IMemory>& buffer, int64_t pts) {
3883
3884 {
3885 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3886 if (!mMediaTimeTransformValid)
3887 return INVALID_OPERATION;
3888 }
3889
3890 Mutex::Autolock _l(mTimedBufferQueueLock);
3891
3892 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
3893
3894 return NO_ERROR;
3895}
3896
3897status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
3898 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
3899
3900 ALOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
3901 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
3902 target);
3903
3904 if (!(target == TimedAudioTrack::LOCAL_TIME ||
3905 target == TimedAudioTrack::COMMON_TIME)) {
3906 return BAD_VALUE;
3907 }
3908
3909 Mutex::Autolock lock(mMediaTimeTransformLock);
3910 mMediaTimeTransform = xform;
3911 mMediaTimeTransformTarget = target;
3912 mMediaTimeTransformValid = true;
3913
3914 return NO_ERROR;
3915}
3916
3917#define min(a, b) ((a) < (b) ? (a) : (b))
3918
3919// implementation of getNextBuffer for tracks whose buffers have timestamps
3920status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
3921 AudioBufferProvider::Buffer* buffer, int64_t pts)
3922{
3923 if (pts == AudioBufferProvider::kInvalidPTS) {
3924 buffer->raw = 0;
3925 buffer->frameCount = 0;
3926 return INVALID_OPERATION;
3927 }
3928
John Grossman4ff14ba2012-02-08 16:37:41 -08003929 Mutex::Autolock _l(mTimedBufferQueueLock);
3930
3931 while (true) {
3932
3933 // if we have no timed buffers, then fail
3934 if (mTimedBufferQueue.isEmpty()) {
3935 buffer->raw = 0;
3936 buffer->frameCount = 0;
3937 return NOT_ENOUGH_DATA;
3938 }
3939
3940 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
3941
3942 // calculate the PTS of the head of the timed buffer queue expressed in
3943 // local time
3944 int64_t headLocalPTS;
3945 {
3946 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3947
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003948 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08003949
3950 if (mMediaTimeTransform.a_to_b_denom == 0) {
3951 // the transform represents a pause, so yield silence
3952 timedYieldSilence(buffer->frameCount, buffer);
3953 return NO_ERROR;
3954 }
3955
3956 int64_t transformedPTS;
3957 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
3958 &transformedPTS)) {
3959 // the transform failed. this shouldn't happen, but if it does
3960 // then just drop this buffer
3961 ALOGW("timedGetNextBuffer transform failed");
3962 buffer->raw = 0;
3963 buffer->frameCount = 0;
3964 mTimedBufferQueue.removeAt(0);
3965 return NO_ERROR;
3966 }
3967
3968 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
3969 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
3970 &headLocalPTS)) {
3971 buffer->raw = 0;
3972 buffer->frameCount = 0;
3973 return INVALID_OPERATION;
3974 }
3975 } else {
3976 headLocalPTS = transformedPTS;
3977 }
3978 }
3979
3980 // adjust the head buffer's PTS to reflect the portion of the head buffer
3981 // that has already been consumed
3982 int64_t effectivePTS = headLocalPTS +
3983 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
3984
3985 // Calculate the delta in samples between the head of the input buffer
3986 // queue and the start of the next output buffer that will be written.
3987 // If the transformation fails because of over or underflow, it means
3988 // that the sample's position in the output stream is so far out of
3989 // whack that it should just be dropped.
3990 int64_t sampleDelta;
3991 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
3992 ALOGV("*** head buffer is too far from PTS: dropped buffer");
3993 mTimedBufferQueue.removeAt(0);
3994 continue;
3995 }
3996 if (!mLocalTimeToSampleTransform.doForwardTransform(
3997 (effectivePTS - pts) << 32, &sampleDelta)) {
3998 ALOGV("*** too late during sample rate transform: dropped buffer");
3999 mTimedBufferQueue.removeAt(0);
4000 continue;
4001 }
4002
4003 ALOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
4004 __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
4005 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
4006 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
4007
4008 // if the delta between the ideal placement for the next input sample and
4009 // the current output position is within this threshold, then we will
4010 // concatenate the next input samples to the previous output
4011 const int64_t kSampleContinuityThreshold =
4012 (static_cast<int64_t>(sampleRate()) << 32) / 10;
4013
4014 // if this is the first buffer of audio that we're emitting from this track
4015 // then it should be almost exactly on time.
4016 const int64_t kSampleStartupThreshold = 1LL << 32;
4017
4018 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
4019 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
4020 // the next input is close enough to being on time, so concatenate it
4021 // with the last output
4022 timedYieldSamples(buffer);
4023
4024 ALOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4025 return NO_ERROR;
4026 } else if (sampleDelta > 0) {
4027 // the gap between the current output position and the proper start of
4028 // the next input sample is too big, so fill it with silence
4029 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4030
4031 timedYieldSilence(framesUntilNextInput, buffer);
4032 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4033 return NO_ERROR;
4034 } else {
4035 // the next input sample is late
4036 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4037 size_t onTimeSamplePosition =
4038 head.position() + lateFrames * mCblk->frameSize;
4039
4040 if (onTimeSamplePosition > head.buffer()->size()) {
4041 // all the remaining samples in the head are too late, so
4042 // drop it and move on
4043 ALOGV("*** too late: dropped buffer");
4044 mTimedBufferQueue.removeAt(0);
4045 continue;
4046 } else {
4047 // skip over the late samples
4048 head.setPosition(onTimeSamplePosition);
4049
4050 // yield the available samples
4051 timedYieldSamples(buffer);
4052
4053 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4054 return NO_ERROR;
4055 }
4056 }
4057 }
4058}
4059
4060// Yield samples from the timed buffer queue head up to the given output
4061// buffer's capacity.
4062//
4063// Caller must hold mTimedBufferQueueLock
4064void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples(
4065 AudioBufferProvider::Buffer* buffer) {
4066
4067 const TimedBuffer& head = mTimedBufferQueue[0];
4068
4069 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4070 head.position());
4071
4072 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4073 mCblk->frameSize);
4074 size_t framesRequested = buffer->frameCount;
4075 buffer->frameCount = min(framesLeftInHead, framesRequested);
4076
4077 mTimedAudioOutputOnTime = true;
4078}
4079
4080// Yield samples of silence up to the given output buffer's capacity
4081//
4082// Caller must hold mTimedBufferQueueLock
4083void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence(
4084 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4085
4086 // lazily allocate a buffer filled with silence
4087 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4088 delete [] mTimedSilenceBuffer;
4089 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4090 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4091 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4092 }
4093
4094 buffer->raw = mTimedSilenceBuffer;
4095 size_t framesRequested = buffer->frameCount;
4096 buffer->frameCount = min(numFrames, framesRequested);
4097
4098 mTimedAudioOutputOnTime = false;
4099}
4100
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004101// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004102void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4103 AudioBufferProvider::Buffer* buffer) {
4104
4105 Mutex::Autolock _l(mTimedBufferQueueLock);
4106
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004107 // If the buffer which was just released is part of the buffer at the head
4108 // of the queue, be sure to update the amt of the buffer which has been
4109 // consumed. If the buffer being returned is not part of the head of the
4110 // queue, its either because the buffer is part of the silence buffer, or
4111 // because the head of the timed queue was trimmed after the mixer called
4112 // getNextBuffer but before the mixer called releaseBuffer.
4113 if ((buffer->raw != mTimedSilenceBuffer) && mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004114 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004115
4116 void* start = head.buffer()->pointer();
Glenn Kastenf063b492012-02-17 16:24:10 -08004117 void* end = (char *) head.buffer()->pointer() + head.buffer()->size();
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004118
4119 if ((buffer->raw >= start) && (buffer->raw <= end)) {
4120 head.setPosition(head.position() +
4121 (buffer->frameCount * mCblk->frameSize));
4122 if (static_cast<size_t>(head.position()) >= head.buffer()->size()) {
4123 mTimedBufferQueue.removeAt(0);
4124 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004125 }
4126 }
4127
4128 buffer->raw = 0;
4129 buffer->frameCount = 0;
4130}
4131
4132uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4133 Mutex::Autolock _l(mTimedBufferQueueLock);
4134
4135 uint32_t frames = 0;
4136 for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4137 const TimedBuffer& tb = mTimedBufferQueue[i];
4138 frames += (tb.buffer()->size() - tb.position()) / mCblk->frameSize;
4139 }
4140
4141 return frames;
4142}
4143
4144AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4145 : mPTS(0), mPosition(0) {}
4146
4147AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4148 const sp<IMemory>& buffer, int64_t pts)
4149 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4150
Mathias Agopian65ab4712010-07-14 17:59:35 -07004151// ----------------------------------------------------------------------------
4152
4153// RecordTrack constructor must be called with AudioFlinger::mLock held
4154AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004155 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004156 const sp<Client>& client,
4157 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004158 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004159 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004160 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004161 int sessionId)
4162 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004163 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004164 mOverflow(false)
4165{
4166 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004167 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
4168 if (format == AUDIO_FORMAT_PCM_16_BIT) {
4169 mCblk->frameSize = mChannelCount * sizeof(int16_t);
4170 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
4171 mCblk->frameSize = mChannelCount * sizeof(int8_t);
4172 } else {
4173 mCblk->frameSize = sizeof(int8_t);
4174 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004175 }
4176}
4177
4178AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4179{
4180 sp<ThreadBase> thread = mThread.promote();
4181 if (thread != 0) {
4182 AudioSystem::releaseInput(thread->id());
4183 }
4184}
4185
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004186// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004187status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004188{
4189 audio_track_cblk_t* cblk = this->cblk();
4190 uint32_t framesAvail;
4191 uint32_t framesReq = buffer->frameCount;
4192
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004193 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004194 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004195 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004196 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004197 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004198 }
4199
4200 framesAvail = cblk->framesAvailable_l();
4201
Glenn Kastenf6b16782011-12-15 09:51:17 -08004202 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004203 uint32_t s = cblk->server;
4204 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4205
4206 if (framesReq > framesAvail) {
4207 framesReq = framesAvail;
4208 }
4209 if (s + framesReq > bufferEnd) {
4210 framesReq = bufferEnd - s;
4211 }
4212
4213 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004214 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004215
4216 buffer->frameCount = framesReq;
4217 return NO_ERROR;
4218 }
4219
4220getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004221 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004222 buffer->frameCount = 0;
4223 return NOT_ENOUGH_DATA;
4224}
4225
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004226status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004227{
4228 sp<ThreadBase> thread = mThread.promote();
4229 if (thread != 0) {
4230 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004231 return recordThread->start(this, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004232 } else {
4233 return BAD_VALUE;
4234 }
4235}
4236
4237void AudioFlinger::RecordThread::RecordTrack::stop()
4238{
4239 sp<ThreadBase> thread = mThread.promote();
4240 if (thread != 0) {
4241 RecordThread *recordThread = (RecordThread *)thread.get();
4242 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004243 TrackBase::reset();
4244 // Force overerrun condition to avoid false overrun callback until first data is
4245 // read from buffer
4246 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004247 }
4248}
4249
4250void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4251{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004252 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004253 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004254 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004255 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004256 mSessionId,
4257 mFrameCount,
4258 mState,
4259 mCblk->sampleRate,
4260 mCblk->server,
4261 mCblk->user);
4262}
4263
4264
4265// ----------------------------------------------------------------------------
4266
4267AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004268 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004269 DuplicatingThread *sourceThread,
4270 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004271 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004272 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004273 int frameCount)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004274 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004275 mActive(false), mSourceThread(sourceThread)
4276{
4277
Mathias Agopian65ab4712010-07-14 17:59:35 -07004278 if (mCblk != NULL) {
4279 mCblk->flags |= CBLK_DIRECTION_OUT;
4280 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004281 mOutBuffer.frameCount = 0;
4282 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01004283 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004284 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4285 mCblk, mBuffer, mCblk->buffers,
4286 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004287 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004288 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004289 }
4290}
4291
4292AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4293{
4294 clearBufferQueue();
4295}
4296
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004297status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004298{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004299 status_t status = Track::start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004300 if (status != NO_ERROR) {
4301 return status;
4302 }
4303
4304 mActive = true;
4305 mRetryCount = 127;
4306 return status;
4307}
4308
4309void AudioFlinger::PlaybackThread::OutputTrack::stop()
4310{
4311 Track::stop();
4312 clearBufferQueue();
4313 mOutBuffer.frameCount = 0;
4314 mActive = false;
4315}
4316
4317bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4318{
4319 Buffer *pInBuffer;
4320 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004321 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004322 bool outputBufferFull = false;
4323 inBuffer.frameCount = frames;
4324 inBuffer.i16 = data;
4325
4326 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4327
4328 if (!mActive && frames != 0) {
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004329 start(0);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004330 sp<ThreadBase> thread = mThread.promote();
4331 if (thread != 0) {
4332 MixerThread *mixerThread = (MixerThread *)thread.get();
4333 if (mCblk->frameCount > frames){
4334 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4335 uint32_t startFrames = (mCblk->frameCount - frames);
4336 pInBuffer = new Buffer;
4337 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4338 pInBuffer->frameCount = startFrames;
4339 pInBuffer->i16 = pInBuffer->mBuffer;
4340 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4341 mBufferQueue.add(pInBuffer);
4342 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004343 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004344 }
4345 }
4346 }
4347 }
4348
4349 while (waitTimeLeftMs) {
4350 // First write pending buffers, then new data
4351 if (mBufferQueue.size()) {
4352 pInBuffer = mBufferQueue.itemAt(0);
4353 } else {
4354 pInBuffer = &inBuffer;
4355 }
4356
4357 if (pInBuffer->frameCount == 0) {
4358 break;
4359 }
4360
4361 if (mOutBuffer.frameCount == 0) {
4362 mOutBuffer.frameCount = pInBuffer->frameCount;
4363 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08004364 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01004365 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004366 outputBufferFull = true;
4367 break;
4368 }
4369 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4370 if (waitTimeLeftMs >= waitTimeMs) {
4371 waitTimeLeftMs -= waitTimeMs;
4372 } else {
4373 waitTimeLeftMs = 0;
4374 }
4375 }
4376
4377 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4378 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4379 mCblk->stepUser(outFrames);
4380 pInBuffer->frameCount -= outFrames;
4381 pInBuffer->i16 += outFrames * channelCount;
4382 mOutBuffer.frameCount -= outFrames;
4383 mOutBuffer.i16 += outFrames * channelCount;
4384
4385 if (pInBuffer->frameCount == 0) {
4386 if (mBufferQueue.size()) {
4387 mBufferQueue.removeAt(0);
4388 delete [] pInBuffer->mBuffer;
4389 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01004390 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004391 } else {
4392 break;
4393 }
4394 }
4395 }
4396
4397 // If we could not write all frames, allocate a buffer and queue it for next time.
4398 if (inBuffer.frameCount) {
4399 sp<ThreadBase> thread = mThread.promote();
4400 if (thread != 0 && !thread->standby()) {
4401 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4402 pInBuffer = new Buffer;
4403 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4404 pInBuffer->frameCount = inBuffer.frameCount;
4405 pInBuffer->i16 = pInBuffer->mBuffer;
4406 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4407 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01004408 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004409 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004410 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004411 }
4412 }
4413 }
4414
4415 // Calling write() with a 0 length buffer, means that no more data will be written:
4416 // If no more buffers are pending, fill output track buffer to make sure it is started
4417 // by output mixer.
4418 if (frames == 0 && mBufferQueue.size() == 0) {
4419 if (mCblk->user < mCblk->frameCount) {
4420 frames = mCblk->frameCount - mCblk->user;
4421 pInBuffer = new Buffer;
4422 pInBuffer->mBuffer = new int16_t[frames * channelCount];
4423 pInBuffer->frameCount = frames;
4424 pInBuffer->i16 = pInBuffer->mBuffer;
4425 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4426 mBufferQueue.add(pInBuffer);
4427 } else if (mActive) {
4428 stop();
4429 }
4430 }
4431
4432 return outputBufferFull;
4433}
4434
4435status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4436{
4437 int active;
4438 status_t result;
4439 audio_track_cblk_t* cblk = mCblk;
4440 uint32_t framesReq = buffer->frameCount;
4441
Steve Block3856b092011-10-20 11:56:00 +01004442// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004443 buffer->frameCount = 0;
4444
4445 uint32_t framesAvail = cblk->framesAvailable();
4446
4447
4448 if (framesAvail == 0) {
4449 Mutex::Autolock _l(cblk->lock);
4450 goto start_loop_here;
4451 while (framesAvail == 0) {
4452 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004453 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004454 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004455 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004456 }
4457 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4458 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004459 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004460 }
4461 // read the server count again
4462 start_loop_here:
4463 framesAvail = cblk->framesAvailable_l();
4464 }
4465 }
4466
4467// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004468// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004469// }
4470
4471 if (framesReq > framesAvail) {
4472 framesReq = framesAvail;
4473 }
4474
4475 uint32_t u = cblk->user;
4476 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4477
4478 if (u + framesReq > bufferEnd) {
4479 framesReq = bufferEnd - u;
4480 }
4481
4482 buffer->frameCount = framesReq;
4483 buffer->raw = (void *)cblk->buffer(u);
4484 return NO_ERROR;
4485}
4486
4487
4488void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4489{
4490 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004491
4492 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004493 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004494 delete [] pBuffer->mBuffer;
4495 delete pBuffer;
4496 }
4497 mBufferQueue.clear();
4498}
4499
4500// ----------------------------------------------------------------------------
4501
4502AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4503 : RefBase(),
4504 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08004505 // 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 -07004506 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08004507 mPid(pid),
4508 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004509{
4510 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4511}
4512
4513// Client destructor must be called with AudioFlinger::mLock held
4514AudioFlinger::Client::~Client()
4515{
4516 mAudioFlinger->removeClient_l(mPid);
4517}
4518
Glenn Kasten435dbe62012-01-30 10:15:48 -08004519sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004520{
4521 return mMemoryDealer;
4522}
4523
John Grossman4ff14ba2012-02-08 16:37:41 -08004524// Reserve one of the limited slots for a timed audio track associated
4525// with this client
4526bool AudioFlinger::Client::reserveTimedTrack()
4527{
4528 const int kMaxTimedTracksPerClient = 4;
4529
4530 Mutex::Autolock _l(mTimedTrackLock);
4531
4532 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4533 ALOGW("can not create timed track - pid %d has exceeded the limit",
4534 mPid);
4535 return false;
4536 }
4537
4538 mTimedTrackCount++;
4539 return true;
4540}
4541
4542// Release a slot for a timed audio track
4543void AudioFlinger::Client::releaseTimedTrack()
4544{
4545 Mutex::Autolock _l(mTimedTrackLock);
4546 mTimedTrackCount--;
4547}
4548
Mathias Agopian65ab4712010-07-14 17:59:35 -07004549// ----------------------------------------------------------------------------
4550
4551AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4552 const sp<IAudioFlingerClient>& client,
4553 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004554 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004555{
4556}
4557
4558AudioFlinger::NotificationClient::~NotificationClient()
4559{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004560}
4561
4562void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4563{
4564 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08004565 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004566}
4567
4568// ----------------------------------------------------------------------------
4569
4570AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4571 : BnAudioTrack(),
4572 mTrack(track)
4573{
4574}
4575
4576AudioFlinger::TrackHandle::~TrackHandle() {
4577 // just stop the track on deletion, associated resources
4578 // will be freed from the main thread once all pending buffers have
4579 // been played. Unless it's not in the active track list, in which
4580 // case we free everything now...
4581 mTrack->destroy();
4582}
4583
Glenn Kasten90716c52012-01-26 13:40:12 -08004584sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4585 return mTrack->getCblk();
4586}
4587
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004588status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4589 return mTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004590}
4591
4592void AudioFlinger::TrackHandle::stop() {
4593 mTrack->stop();
4594}
4595
4596void AudioFlinger::TrackHandle::flush() {
4597 mTrack->flush();
4598}
4599
4600void AudioFlinger::TrackHandle::mute(bool e) {
4601 mTrack->mute(e);
4602}
4603
4604void AudioFlinger::TrackHandle::pause() {
4605 mTrack->pause();
4606}
4607
Mathias Agopian65ab4712010-07-14 17:59:35 -07004608status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4609{
4610 return mTrack->attachAuxEffect(EffectId);
4611}
4612
John Grossman4ff14ba2012-02-08 16:37:41 -08004613status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4614 sp<IMemory>* buffer) {
4615 if (!mTrack->isTimedTrack())
4616 return INVALID_OPERATION;
4617
4618 PlaybackThread::TimedTrack* tt =
4619 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4620 return tt->allocateTimedBuffer(size, buffer);
4621}
4622
4623status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4624 int64_t pts) {
4625 if (!mTrack->isTimedTrack())
4626 return INVALID_OPERATION;
4627
4628 PlaybackThread::TimedTrack* tt =
4629 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4630 return tt->queueTimedBuffer(buffer, pts);
4631}
4632
4633status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4634 const LinearTransform& xform, int target) {
4635
4636 if (!mTrack->isTimedTrack())
4637 return INVALID_OPERATION;
4638
4639 PlaybackThread::TimedTrack* tt =
4640 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4641 return tt->setMediaTimeTransform(
4642 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4643}
4644
Mathias Agopian65ab4712010-07-14 17:59:35 -07004645status_t AudioFlinger::TrackHandle::onTransact(
4646 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4647{
4648 return BnAudioTrack::onTransact(code, data, reply, flags);
4649}
4650
4651// ----------------------------------------------------------------------------
4652
4653sp<IAudioRecord> AudioFlinger::openRecord(
4654 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004655 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004656 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004657 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004658 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004659 int frameCount,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004660 // FIXME dead, remove from IAudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -07004661 uint32_t flags,
4662 int *sessionId,
4663 status_t *status)
4664{
4665 sp<RecordThread::RecordTrack> recordTrack;
4666 sp<RecordHandle> recordHandle;
4667 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004668 status_t lStatus;
4669 RecordThread *thread;
4670 size_t inFrameCount;
4671 int lSessionId;
4672
4673 // check calling permissions
4674 if (!recordingAllowed()) {
4675 lStatus = PERMISSION_DENIED;
4676 goto Exit;
4677 }
4678
4679 // add client to list
4680 { // scope for mLock
4681 Mutex::Autolock _l(mLock);
4682 thread = checkRecordThread_l(input);
4683 if (thread == NULL) {
4684 lStatus = BAD_VALUE;
4685 goto Exit;
4686 }
4687
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004688 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004689
4690 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004691 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004692 lSessionId = *sessionId;
4693 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004694 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004695 if (sessionId != NULL) {
4696 *sessionId = lSessionId;
4697 }
4698 }
4699 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004700 recordTrack = thread->createRecordTrack_l(client,
4701 sampleRate,
4702 format,
4703 channelMask,
4704 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004705 lSessionId,
4706 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004707 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004708 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004709 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4710 // destructor is called by the TrackBase destructor with mLock held
4711 client.clear();
4712 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004713 goto Exit;
4714 }
4715
4716 // return to handle to client
4717 recordHandle = new RecordHandle(recordTrack);
4718 lStatus = NO_ERROR;
4719
4720Exit:
4721 if (status) {
4722 *status = lStatus;
4723 }
4724 return recordHandle;
4725}
4726
4727// ----------------------------------------------------------------------------
4728
4729AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4730 : BnAudioRecord(),
4731 mRecordTrack(recordTrack)
4732{
4733}
4734
4735AudioFlinger::RecordHandle::~RecordHandle() {
4736 stop();
4737}
4738
Glenn Kasten90716c52012-01-26 13:40:12 -08004739sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4740 return mRecordTrack->getCblk();
4741}
4742
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004743status_t AudioFlinger::RecordHandle::start(pid_t tid) {
Steve Block3856b092011-10-20 11:56:00 +01004744 ALOGV("RecordHandle::start()");
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004745 return mRecordTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004746}
4747
4748void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004749 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004750 mRecordTrack->stop();
4751}
4752
Mathias Agopian65ab4712010-07-14 17:59:35 -07004753status_t AudioFlinger::RecordHandle::onTransact(
4754 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4755{
4756 return BnAudioRecord::onTransact(code, data, reply, flags);
4757}
4758
4759// ----------------------------------------------------------------------------
4760
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004761AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4762 AudioStreamIn *input,
4763 uint32_t sampleRate,
4764 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004765 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004766 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004767 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004768 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4769 // mRsmpInIndex and mInputBytes set by readInputParameters()
4770 mReqChannelCount(popcount(channels)),
4771 mReqSampleRate(sampleRate)
4772 // mBytesRead is only meaningful while active, and so is cleared in start()
4773 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004774{
Glenn Kasten480b4682012-02-28 12:30:08 -08004775 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07004776
Mathias Agopian65ab4712010-07-14 17:59:35 -07004777 readInputParameters();
4778}
4779
4780
4781AudioFlinger::RecordThread::~RecordThread()
4782{
4783 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004784 delete mResampler;
4785 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004786}
4787
4788void AudioFlinger::RecordThread::onFirstRef()
4789{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004790 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004791}
4792
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004793status_t AudioFlinger::RecordThread::readyToRun()
4794{
4795 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004796 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004797 return status;
4798}
4799
Mathias Agopian65ab4712010-07-14 17:59:35 -07004800bool AudioFlinger::RecordThread::threadLoop()
4801{
4802 AudioBufferProvider::Buffer buffer;
4803 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004804 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004805
Eric Laurent44d98482010-09-30 16:12:31 -07004806 nsecs_t lastWarning = 0;
4807
Eric Laurentfeb0db62011-07-22 09:04:31 -07004808 acquireWakeLock();
4809
Mathias Agopian65ab4712010-07-14 17:59:35 -07004810 // start recording
4811 while (!exitPending()) {
4812
4813 processConfigEvents();
4814
4815 { // scope for mLock
4816 Mutex::Autolock _l(mLock);
4817 checkForNewParameters_l();
4818 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4819 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004820 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004821 mStandby = true;
4822 }
4823
4824 if (exitPending()) break;
4825
Eric Laurentfeb0db62011-07-22 09:04:31 -07004826 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004827 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004828 // go to sleep
4829 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004830 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004831 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004832 continue;
4833 }
4834 if (mActiveTrack != 0) {
4835 if (mActiveTrack->mState == TrackBase::PAUSING) {
4836 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004837 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004838 mStandby = true;
4839 }
4840 mActiveTrack.clear();
4841 mStartStopCond.broadcast();
4842 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4843 if (mReqChannelCount != mActiveTrack->channelCount()) {
4844 mActiveTrack.clear();
4845 mStartStopCond.broadcast();
4846 } else if (mBytesRead != 0) {
4847 // record start succeeds only if first read from audio input
4848 // succeeds
4849 if (mBytesRead > 0) {
4850 mActiveTrack->mState = TrackBase::ACTIVE;
4851 } else {
4852 mActiveTrack.clear();
4853 }
4854 mStartStopCond.broadcast();
4855 }
4856 mStandby = false;
4857 }
4858 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004859 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004860 }
4861
4862 if (mActiveTrack != 0) {
4863 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4864 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004865 unlockEffectChains(effectChains);
4866 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004867 continue;
4868 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004869 for (size_t i = 0; i < effectChains.size(); i ++) {
4870 effectChains[i]->process_l();
4871 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004872
Mathias Agopian65ab4712010-07-14 17:59:35 -07004873 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004874 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004875 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004876 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004877 // no resampling
4878 while (framesOut) {
4879 size_t framesIn = mFrameCount - mRsmpInIndex;
4880 if (framesIn) {
4881 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4882 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4883 if (framesIn > framesOut)
4884 framesIn = framesOut;
4885 mRsmpInIndex += framesIn;
4886 framesOut -= framesIn;
4887 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004888 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004889 memcpy(dst, src, framesIn * mFrameSize);
4890 } else {
4891 int16_t *src16 = (int16_t *)src;
4892 int16_t *dst16 = (int16_t *)dst;
4893 if (mChannelCount == 1) {
4894 while (framesIn--) {
4895 *dst16++ = *src16;
4896 *dst16++ = *src16++;
4897 }
4898 } else {
4899 while (framesIn--) {
4900 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4901 src16 += 2;
4902 }
4903 }
4904 }
4905 }
4906 if (framesOut && mFrameCount == mRsmpInIndex) {
4907 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004908 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004909 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004910 framesOut = 0;
4911 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004912 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004913 mRsmpInIndex = 0;
4914 }
4915 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004916 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004917 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4918 // Force input into standby so that it tries to
4919 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004920 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004921 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004922 }
4923 mRsmpInIndex = mFrameCount;
4924 framesOut = 0;
4925 buffer.frameCount = 0;
4926 }
4927 }
4928 }
4929 } else {
4930 // resampling
4931
4932 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4933 // alter output frame count as if we were expecting stereo samples
4934 if (mChannelCount == 1 && mReqChannelCount == 1) {
4935 framesOut >>= 1;
4936 }
4937 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4938 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4939 // are 32 bit aligned which should be always true.
4940 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004941 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004942 // the resampler always outputs stereo samples: do post stereo to mono conversion
4943 int16_t *src = (int16_t *)mRsmpOutBuffer;
4944 int16_t *dst = buffer.i16;
4945 while (framesOut--) {
4946 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4947 src += 2;
4948 }
4949 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004950 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004951 }
4952
4953 }
4954 mActiveTrack->releaseBuffer(&buffer);
4955 mActiveTrack->overflow();
4956 }
4957 // client isn't retrieving buffers fast enough
4958 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004959 if (!mActiveTrack->setOverflow()) {
4960 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004961 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004962 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004963 lastWarning = now;
4964 }
4965 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004966 // Release the processor for a while before asking for a new buffer.
4967 // This will give the application more chance to read from the buffer and
4968 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004969 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004970 }
4971 }
Eric Laurentec437d82011-07-26 20:54:46 -07004972 // enable changes in effect chain
4973 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004974 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004975 }
4976
4977 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004978 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004979 }
4980 mActiveTrack.clear();
4981
4982 mStartStopCond.broadcast();
4983
Eric Laurentfeb0db62011-07-22 09:04:31 -07004984 releaseWakeLock();
4985
Steve Block3856b092011-10-20 11:56:00 +01004986 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004987 return false;
4988}
4989
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004990
4991sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4992 const sp<AudioFlinger::Client>& client,
4993 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004994 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004995 int channelMask,
4996 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004997 int sessionId,
4998 status_t *status)
4999{
5000 sp<RecordTrack> track;
5001 status_t lStatus;
5002
5003 lStatus = initCheck();
5004 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005005 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005006 goto Exit;
5007 }
5008
5009 { // scope for mLock
5010 Mutex::Autolock _l(mLock);
5011
5012 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005013 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005014
Glenn Kasten7378ca52012-01-20 13:44:40 -08005015 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005016 lStatus = NO_MEMORY;
5017 goto Exit;
5018 }
5019
5020 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005021 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5022 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005023 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005024 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5025 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005026 }
5027 lStatus = NO_ERROR;
5028
5029Exit:
5030 if (status) {
5031 *status = lStatus;
5032 }
5033 return track;
5034}
5035
Glenn Kasten6dbc1352012-02-02 10:56:47 -08005036status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005037{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08005038 ALOGV("RecordThread::start tid=%d", tid);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005039 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005040 status_t status = NO_ERROR;
5041 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005042 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005043 if (mActiveTrack != 0) {
5044 if (recordTrack != mActiveTrack.get()) {
5045 status = -EBUSY;
5046 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5047 mActiveTrack->mState = TrackBase::ACTIVE;
5048 }
5049 return status;
5050 }
5051
5052 recordTrack->mState = TrackBase::IDLE;
5053 mActiveTrack = recordTrack;
5054 mLock.unlock();
5055 status_t status = AudioSystem::startInput(mId);
5056 mLock.lock();
5057 if (status != NO_ERROR) {
5058 mActiveTrack.clear();
5059 return status;
5060 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005061 mRsmpInIndex = mFrameCount;
5062 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005063 if (mResampler != NULL) {
5064 mResampler->reset();
5065 }
5066 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005067 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005068 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005069 mWaitWorkCV.signal();
5070 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005071 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005072 mActiveTrack.clear();
5073 status = INVALID_OPERATION;
5074 goto startError;
5075 }
5076 mStartStopCond.wait(mLock);
5077 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005078 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005079 status = BAD_VALUE;
5080 goto startError;
5081 }
Steve Block3856b092011-10-20 11:56:00 +01005082 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005083 return status;
5084 }
5085startError:
5086 AudioSystem::stopInput(mId);
5087 return status;
5088}
5089
5090void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005091 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005092 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005093 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005094 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005095 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5096 mActiveTrack->mState = TrackBase::PAUSING;
5097 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005098 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005099 return;
5100 }
5101 mStartStopCond.wait(mLock);
5102 // if we have been restarted, recordTrack == mActiveTrack.get() here
5103 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5104 mLock.unlock();
5105 AudioSystem::stopInput(mId);
5106 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005107 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005108 }
5109 }
5110 }
5111}
5112
5113status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5114{
5115 const size_t SIZE = 256;
5116 char buffer[SIZE];
5117 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005118
5119 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5120 result.append(buffer);
5121
5122 if (mActiveTrack != 0) {
5123 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005124 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005125 mActiveTrack->dump(buffer, SIZE);
5126 result.append(buffer);
5127
5128 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5129 result.append(buffer);
5130 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5131 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005132 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005133 result.append(buffer);
5134 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5135 result.append(buffer);
5136 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5137 result.append(buffer);
5138
5139
5140 } else {
5141 result.append("No record client\n");
5142 }
5143 write(fd, result.string(), result.size());
5144
5145 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005146 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005147
5148 return NO_ERROR;
5149}
5150
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005151// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005152status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005153{
5154 size_t framesReq = buffer->frameCount;
5155 size_t framesReady = mFrameCount - mRsmpInIndex;
5156 int channelCount;
5157
5158 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005159 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005160 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005161 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005162 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5163 // Force input into standby so that it tries to
5164 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005165 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005166 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005167 }
Glenn Kastene0feee32011-12-13 11:53:26 -08005168 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005169 buffer->frameCount = 0;
5170 return NOT_ENOUGH_DATA;
5171 }
5172 mRsmpInIndex = 0;
5173 framesReady = mFrameCount;
5174 }
5175
5176 if (framesReq > framesReady) {
5177 framesReq = framesReady;
5178 }
5179
5180 if (mChannelCount == 1 && mReqChannelCount == 2) {
5181 channelCount = 1;
5182 } else {
5183 channelCount = 2;
5184 }
5185 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5186 buffer->frameCount = framesReq;
5187 return NO_ERROR;
5188}
5189
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005190// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07005191void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5192{
5193 mRsmpInIndex += buffer->frameCount;
5194 buffer->frameCount = 0;
5195}
5196
5197bool AudioFlinger::RecordThread::checkForNewParameters_l()
5198{
5199 bool reconfig = false;
5200
5201 while (!mNewParameters.isEmpty()) {
5202 status_t status = NO_ERROR;
5203 String8 keyValuePair = mNewParameters[0];
5204 AudioParameter param = AudioParameter(keyValuePair);
5205 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08005206 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005207 int reqSamplingRate = mReqSampleRate;
5208 int reqChannelCount = mReqChannelCount;
5209
5210 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5211 reqSamplingRate = value;
5212 reconfig = true;
5213 }
5214 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08005215 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005216 reconfig = true;
5217 }
5218 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005219 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005220 reconfig = true;
5221 }
5222 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5223 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08005224 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005225 // if frame count is changed after track creation
5226 if (mActiveTrack != 0) {
5227 status = INVALID_OPERATION;
5228 } else {
5229 reconfig = true;
5230 }
5231 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005232 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5233 // forward device change to effects that have requested to be
5234 // aware of attached audio device.
5235 for (size_t i = 0; i < mEffectChains.size(); i++) {
5236 mEffectChains[i]->setDevice_l(value);
5237 }
5238 // store input device and output device but do not forward output device to audio HAL.
5239 // Note that status is ignored by the caller for output device
5240 // (see AudioFlinger::setParameters()
5241 if (value & AUDIO_DEVICE_OUT_ALL) {
5242 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5243 status = BAD_VALUE;
5244 } else {
5245 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07005246 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5247 if (mTrack != NULL) {
5248 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005249 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005250 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5251 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5252 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005253 }
5254 mDevice |= (uint32_t)value;
5255 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005256 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005257 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005258 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005259 mInput->stream->common.standby(&mInput->stream->common);
5260 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5261 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005262 }
5263 if (reconfig) {
5264 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005265 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005266 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005267 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08005268 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
5269 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005270 status = NO_ERROR;
5271 }
5272 if (status == NO_ERROR) {
5273 readInputParameters();
5274 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5275 }
5276 }
5277 }
5278
5279 mNewParameters.removeAt(0);
5280
5281 mParamStatus = status;
5282 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07005283 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5284 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08005285 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005286 }
5287 return reconfig;
5288}
5289
5290String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5291{
Dima Zavinfce7a472011-04-19 22:30:36 -07005292 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005293 String8 out_s8 = String8();
5294
5295 Mutex::Autolock _l(mLock);
5296 if (initCheck() != NO_ERROR) {
5297 return out_s8;
5298 }
Dima Zavinfce7a472011-04-19 22:30:36 -07005299
Dima Zavin799a70e2011-04-18 16:57:27 -07005300 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07005301 out_s8 = String8(s);
5302 free(s);
5303 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005304}
5305
5306void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5307 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08005308 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005309
5310 switch (event) {
5311 case AudioSystem::INPUT_OPENED:
5312 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005313 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005314 desc.samplingRate = mSampleRate;
5315 desc.format = mFormat;
5316 desc.frameCount = mFrameCount;
5317 desc.latency = 0;
5318 param2 = &desc;
5319 break;
5320
5321 case AudioSystem::INPUT_CLOSED:
5322 default:
5323 break;
5324 }
5325 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5326}
5327
5328void AudioFlinger::RecordThread::readInputParameters()
5329{
Glenn Kastene9dd0172012-01-27 18:08:45 -08005330 delete mRsmpInBuffer;
5331 // mRsmpInBuffer is always assigned a new[] below
5332 delete mRsmpOutBuffer;
5333 mRsmpOutBuffer = NULL;
5334 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08005335 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005336
Dima Zavin799a70e2011-04-18 16:57:27 -07005337 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005338 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5339 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07005340 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08005341 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07005342 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005343 mFrameCount = mInputBytes / mFrameSize;
5344 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5345
Glenn Kasten53d76db2012-03-08 12:32:47 -08005346 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005347 {
5348 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005349 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5350 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005351 if (mChannelCount == 1 && mReqChannelCount == 2) {
5352 channelCount = 1;
5353 } else {
5354 channelCount = 2;
5355 }
5356 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5357 mResampler->setSampleRate(mSampleRate);
5358 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5359 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5360
5361 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5362 if (mChannelCount == 1 && mReqChannelCount == 1) {
5363 mFrameCount >>= 1;
5364 }
5365
5366 }
5367 mRsmpInIndex = mFrameCount;
5368}
5369
5370unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5371{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005372 Mutex::Autolock _l(mLock);
5373 if (initCheck() != NO_ERROR) {
5374 return 0;
5375 }
5376
Dima Zavin799a70e2011-04-18 16:57:27 -07005377 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005378}
5379
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005380uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5381{
5382 Mutex::Autolock _l(mLock);
5383 uint32_t result = 0;
5384 if (getEffectChain_l(sessionId) != 0) {
5385 result = EFFECT_SESSION;
5386 }
5387
5388 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5389 result |= TRACK_SESSION;
5390 }
5391
5392 return result;
5393}
5394
Eric Laurent59bd0da2011-08-01 09:52:20 -07005395AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5396{
5397 Mutex::Autolock _l(mLock);
5398 return mTrack;
5399}
5400
Glenn Kastenaed850d2012-01-26 09:46:34 -08005401AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005402{
5403 Mutex::Autolock _l(mLock);
5404 return mInput;
5405}
5406
5407AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5408{
5409 Mutex::Autolock _l(mLock);
5410 AudioStreamIn *input = mInput;
5411 mInput = NULL;
5412 return input;
5413}
5414
5415// this method must always be called either with ThreadBase mLock held or inside the thread loop
5416audio_stream_t* AudioFlinger::RecordThread::stream()
5417{
5418 if (mInput == NULL) {
5419 return NULL;
5420 }
5421 return &mInput->stream->common;
5422}
5423
5424
Mathias Agopian65ab4712010-07-14 17:59:35 -07005425// ----------------------------------------------------------------------------
5426
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005427audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005428 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005429 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005430 uint32_t *pChannels,
5431 uint32_t *pLatencyMs,
Glenn Kasten18868c52012-03-07 09:15:37 -08005432 audio_policy_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005433{
5434 status_t status;
5435 PlaybackThread *thread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005436 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005437 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005438 uint32_t channels = pChannels ? *pChannels : 0;
5439 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07005440 audio_stream_out_t *outStream;
5441 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005442
Steve Block3856b092011-10-20 11:56:00 +01005443 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07005444 pDevices ? *pDevices : 0,
5445 samplingRate,
5446 format,
5447 channels,
5448 flags);
5449
5450 if (pDevices == NULL || *pDevices == 0) {
5451 return 0;
5452 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005453
Mathias Agopian65ab4712010-07-14 17:59:35 -07005454 Mutex::Autolock _l(mLock);
5455
Dima Zavin799a70e2011-04-18 16:57:27 -07005456 outHwDev = findSuitableHwDev_l(*pDevices);
5457 if (outHwDev == NULL)
5458 return 0;
5459
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005460 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Glenn Kasten58f30212012-01-12 12:27:51 -08005461 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005462 &channels, &samplingRate, &outStream);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005463 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01005464 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005465 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005466 samplingRate,
5467 format,
5468 channels,
5469 status);
5470
Dima Zavin799a70e2011-04-18 16:57:27 -07005471 if (outStream != NULL) {
5472 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005473 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07005474
Dima Zavinfce7a472011-04-19 22:30:36 -07005475 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5476 (format != AUDIO_FORMAT_PCM_16_BIT) ||
5477 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005478 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005479 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005480 } else {
5481 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005482 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005483 }
5484 mPlaybackThreads.add(id, thread);
5485
Glenn Kastena0d68332012-01-27 16:47:15 -08005486 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5487 if (pFormat != NULL) *pFormat = format;
5488 if (pChannels != NULL) *pChannels = channels;
5489 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005490
5491 // notify client processes of the new output creation
5492 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5493 return id;
5494 }
5495
5496 return 0;
5497}
5498
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005499audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
5500 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005501{
5502 Mutex::Autolock _l(mLock);
5503 MixerThread *thread1 = checkMixerThread_l(output1);
5504 MixerThread *thread2 = checkMixerThread_l(output2);
5505
5506 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005507 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005508 return 0;
5509 }
5510
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005511 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005512 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5513 thread->addOutputTrack(thread2);
5514 mPlaybackThreads.add(id, thread);
5515 // notify client processes of the new output creation
5516 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5517 return id;
5518}
5519
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005520status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005521{
5522 // keep strong reference on the playback thread so that
5523 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005524 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005525 {
5526 Mutex::Autolock _l(mLock);
5527 thread = checkPlaybackThread_l(output);
5528 if (thread == NULL) {
5529 return BAD_VALUE;
5530 }
5531
Steve Block3856b092011-10-20 11:56:00 +01005532 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005533
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005534 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005535 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005536 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005537 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5538 dupThread->removeOutputTrack((MixerThread *)thread.get());
5539 }
5540 }
5541 }
Glenn Kastena1117922012-01-26 10:53:32 -08005542 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005543 mPlaybackThreads.removeItem(output);
5544 }
5545 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005546 // The thread entity (active unit of execution) is no longer running here,
5547 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005548
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005549 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005550 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005551 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005552 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005553 out->hwDev->close_output_stream(out->hwDev, out->stream);
5554 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005555 }
5556 return NO_ERROR;
5557}
5558
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005559status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005560{
5561 Mutex::Autolock _l(mLock);
5562 PlaybackThread *thread = checkPlaybackThread_l(output);
5563
5564 if (thread == NULL) {
5565 return BAD_VALUE;
5566 }
5567
Steve Block3856b092011-10-20 11:56:00 +01005568 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005569 thread->suspend();
5570
5571 return NO_ERROR;
5572}
5573
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005574status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005575{
5576 Mutex::Autolock _l(mLock);
5577 PlaybackThread *thread = checkPlaybackThread_l(output);
5578
5579 if (thread == NULL) {
5580 return BAD_VALUE;
5581 }
5582
Steve Block3856b092011-10-20 11:56:00 +01005583 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005584
5585 thread->restore();
5586
5587 return NO_ERROR;
5588}
5589
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005590audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005591 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005592 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005593 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005594 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005595{
5596 status_t status;
5597 RecordThread *thread = NULL;
5598 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005599 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005600 uint32_t channels = pChannels ? *pChannels : 0;
5601 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005602 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005603 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005604 audio_stream_in_t *inStream;
5605 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005606
5607 if (pDevices == NULL || *pDevices == 0) {
5608 return 0;
5609 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005610
Mathias Agopian65ab4712010-07-14 17:59:35 -07005611 Mutex::Autolock _l(mLock);
5612
Dima Zavin799a70e2011-04-18 16:57:27 -07005613 inHwDev = findSuitableHwDev_l(*pDevices);
5614 if (inHwDev == NULL)
5615 return 0;
5616
Glenn Kasten58f30212012-01-12 12:27:51 -08005617 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005618 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005619 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005620 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005621 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005622 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005623 samplingRate,
5624 format,
5625 channels,
5626 acoustics,
5627 status);
5628
5629 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5630 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5631 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005632 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005633 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005634 (samplingRate <= 2 * reqSamplingRate) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08005635 (popcount(channels) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01005636 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005637 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005638 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005639 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005640 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005641 }
5642
Dima Zavin799a70e2011-04-18 16:57:27 -07005643 if (inStream != NULL) {
5644 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5645
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005646 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005647 // Start record thread
5648 // RecorThread require both input and output device indication to forward to audio
5649 // pre processing modules
5650 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5651 thread = new RecordThread(this,
5652 input,
5653 reqSamplingRate,
5654 reqChannels,
5655 id,
5656 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005657 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005658 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005659 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5660 if (pFormat != NULL) *pFormat = format;
5661 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005662
Dima Zavin799a70e2011-04-18 16:57:27 -07005663 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005664
5665 // notify client processes of the new input creation
5666 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5667 return id;
5668 }
5669
5670 return 0;
5671}
5672
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005673status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005674{
5675 // keep strong reference on the record thread so that
5676 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005677 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005678 {
5679 Mutex::Autolock _l(mLock);
5680 thread = checkRecordThread_l(input);
5681 if (thread == NULL) {
5682 return BAD_VALUE;
5683 }
5684
Steve Block3856b092011-10-20 11:56:00 +01005685 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08005686 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005687 mRecordThreads.removeItem(input);
5688 }
5689 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005690 // The thread entity (active unit of execution) is no longer running here,
5691 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005692
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005693 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005694 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005695 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005696 in->hwDev->close_input_stream(in->hwDev, in->stream);
5697 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005698
5699 return NO_ERROR;
5700}
5701
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005702status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005703{
5704 Mutex::Autolock _l(mLock);
5705 MixerThread *dstThread = checkMixerThread_l(output);
5706 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005707 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005708 return BAD_VALUE;
5709 }
5710
Steve Block3856b092011-10-20 11:56:00 +01005711 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005712 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5713
Eric Laurent9f6530f2011-08-30 10:18:54 -07005714 dstThread->setStreamValid(stream, true);
5715
Mathias Agopian65ab4712010-07-14 17:59:35 -07005716 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5717 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08005718 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005719 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005720 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005721 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005722 }
Eric Laurentde070132010-07-13 04:45:46 -07005723 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005724
5725 return NO_ERROR;
5726}
5727
5728
5729int AudioFlinger::newAudioSessionId()
5730{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005731 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005732}
5733
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005734void AudioFlinger::acquireAudioSessionId(int audioSession)
5735{
5736 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005737 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005738 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005739 size_t num = mAudioSessionRefs.size();
5740 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005741 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005742 if (ref->mSessionid == audioSession && ref->mPid == caller) {
5743 ref->mCnt++;
5744 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005745 return;
5746 }
5747 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005748 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5749 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005750}
5751
5752void AudioFlinger::releaseAudioSessionId(int audioSession)
5753{
5754 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005755 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005756 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005757 size_t num = mAudioSessionRefs.size();
5758 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005759 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005760 if (ref->mSessionid == audioSession && ref->mPid == caller) {
5761 ref->mCnt--;
5762 ALOGV(" decremented refcount to %d", ref->mCnt);
5763 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005764 mAudioSessionRefs.removeAt(i);
5765 delete ref;
5766 purgeStaleEffects_l();
5767 }
5768 return;
5769 }
5770 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005771 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005772}
5773
5774void AudioFlinger::purgeStaleEffects_l() {
5775
Steve Block3856b092011-10-20 11:56:00 +01005776 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005777
5778 Vector< sp<EffectChain> > chains;
5779
5780 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5781 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5782 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5783 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005784 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5785 chains.push(ec);
5786 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005787 }
5788 }
5789 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5790 sp<RecordThread> t = mRecordThreads.valueAt(i);
5791 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5792 sp<EffectChain> ec = t->mEffectChains[j];
5793 chains.push(ec);
5794 }
5795 }
5796
5797 for (size_t i = 0; i < chains.size(); i++) {
5798 sp<EffectChain> ec = chains[i];
5799 int sessionid = ec->sessionId();
5800 sp<ThreadBase> t = ec->mThread.promote();
5801 if (t == 0) {
5802 continue;
5803 }
5804 size_t numsessionrefs = mAudioSessionRefs.size();
5805 bool found = false;
5806 for (size_t k = 0; k < numsessionrefs; k++) {
5807 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08005808 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005809 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005810 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005811 found = true;
5812 break;
5813 }
5814 }
5815 if (!found) {
5816 // remove all effects from the chain
5817 while (ec->mEffects.size()) {
5818 sp<EffectModule> effect = ec->mEffects[0];
5819 effect->unPin();
5820 Mutex::Autolock _l (t->mLock);
5821 t->removeEffect_l(effect);
5822 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5823 sp<EffectHandle> handle = effect->mHandles[j].promote();
5824 if (handle != 0) {
5825 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005826 if (handle->mHasControl && handle->mEnabled) {
5827 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5828 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005829 }
5830 }
5831 AudioSystem::unregisterEffect(effect->id());
5832 }
5833 }
5834 }
5835 return;
5836}
5837
Mathias Agopian65ab4712010-07-14 17:59:35 -07005838// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005839AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005840{
Glenn Kastena1117922012-01-26 10:53:32 -08005841 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005842}
5843
5844// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005845AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005846{
5847 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08005848 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005849}
5850
5851// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005852AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005853{
Glenn Kastena1117922012-01-26 10:53:32 -08005854 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005855}
5856
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005857uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005858{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005859 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005860}
5861
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08005862AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005863{
5864 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5865 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005866 AudioStreamOut *output = thread->getOutput();
5867 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005868 return thread;
5869 }
5870 }
5871 return NULL;
5872}
5873
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08005874uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005875{
5876 PlaybackThread *thread = primaryPlaybackThread_l();
5877
5878 if (thread == NULL) {
5879 return 0;
5880 }
5881
5882 return thread->device();
5883}
5884
5885
Mathias Agopian65ab4712010-07-14 17:59:35 -07005886// ----------------------------------------------------------------------------
5887// Effect management
5888// ----------------------------------------------------------------------------
5889
5890
Glenn Kastenf587ba52012-01-26 16:25:10 -08005891status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005892{
5893 Mutex::Autolock _l(mLock);
5894 return EffectQueryNumberEffects(numEffects);
5895}
5896
Glenn Kastenf587ba52012-01-26 16:25:10 -08005897status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005898{
5899 Mutex::Autolock _l(mLock);
5900 return EffectQueryEffect(index, descriptor);
5901}
5902
Glenn Kasten5e92a782012-01-30 07:40:52 -08005903status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08005904 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005905{
5906 Mutex::Autolock _l(mLock);
5907 return EffectGetDescriptor(pUuid, descriptor);
5908}
5909
5910
Mathias Agopian65ab4712010-07-14 17:59:35 -07005911sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5912 effect_descriptor_t *pDesc,
5913 const sp<IEffectClient>& effectClient,
5914 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005915 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005916 int sessionId,
5917 status_t *status,
5918 int *id,
5919 int *enabled)
5920{
5921 status_t lStatus = NO_ERROR;
5922 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005923 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005924
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005925 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005926 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005927
5928 if (pDesc == NULL) {
5929 lStatus = BAD_VALUE;
5930 goto Exit;
5931 }
5932
Eric Laurent84e9a102010-09-23 16:10:16 -07005933 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005934 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005935 lStatus = PERMISSION_DENIED;
5936 goto Exit;
5937 }
5938
Dima Zavinfce7a472011-04-19 22:30:36 -07005939 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005940 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08005941 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005942 lStatus = PERMISSION_DENIED;
5943 goto Exit;
5944 }
5945
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005946 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005947 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005948 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005949 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005950 lStatus = BAD_VALUE;
5951 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005952 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005953 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005954 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005955 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005956 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005957 }
5958 }
5959
Mathias Agopian65ab4712010-07-14 17:59:35 -07005960 {
5961 Mutex::Autolock _l(mLock);
5962
Mathias Agopian65ab4712010-07-14 17:59:35 -07005963
5964 if (!EffectIsNullUuid(&pDesc->uuid)) {
5965 // if uuid is specified, request effect descriptor
5966 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5967 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005968 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005969 goto Exit;
5970 }
5971 } else {
5972 // if uuid is not specified, look for an available implementation
5973 // of the required type in effect factory
5974 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005975 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005976 lStatus = BAD_VALUE;
5977 goto Exit;
5978 }
5979 uint32_t numEffects = 0;
5980 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005981 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005982 bool found = false;
5983
5984 lStatus = EffectQueryNumberEffects(&numEffects);
5985 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005986 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005987 goto Exit;
5988 }
5989 for (uint32_t i = 0; i < numEffects; i++) {
5990 lStatus = EffectQueryEffect(i, &desc);
5991 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005992 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005993 continue;
5994 }
5995 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5996 // If matching type found save effect descriptor. If the session is
5997 // 0 and the effect is not auxiliary, continue enumeration in case
5998 // an auxiliary version of this effect type is available
5999 found = true;
6000 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07006001 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006002 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6003 break;
6004 }
6005 }
6006 }
6007 if (!found) {
6008 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00006009 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006010 goto Exit;
6011 }
6012 // For same effect type, chose auxiliary version over insert version if
6013 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07006014 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006015 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
6016 memcpy(&desc, &d, sizeof(effect_descriptor_t));
6017 }
6018 }
6019
6020 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07006021 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006022 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6023 lStatus = INVALID_OPERATION;
6024 goto Exit;
6025 }
6026
Eric Laurent59255e42011-07-27 19:49:51 -07006027 // check recording permission for visualizer
6028 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
6029 !recordingAllowed()) {
6030 lStatus = PERMISSION_DENIED;
6031 goto Exit;
6032 }
6033
Mathias Agopian65ab4712010-07-14 17:59:35 -07006034 // return effect descriptor
6035 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
6036
6037 // If output is not specified try to find a matching audio session ID in one of the
6038 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07006039 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
6040 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006041 // Note: io is never 0 when creating an effect on an input
6042 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006043 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07006044 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6045 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006046 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07006047 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07006048 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006049 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006050 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006051 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6052 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6053 io = mRecordThreads.keyAt(i);
6054 break;
6055 }
6056 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006057 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006058 // If no output thread contains the requested session ID, default to
6059 // first output. The effect chain will be moved to the correct output
6060 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006061 if (io == 0 && mPlaybackThreads.size()) {
6062 io = mPlaybackThreads.keyAt(0);
6063 }
Steve Block3856b092011-10-20 11:56:00 +01006064 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006065 }
6066 ThreadBase *thread = checkRecordThread_l(io);
6067 if (thread == NULL) {
6068 thread = checkPlaybackThread_l(io);
6069 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00006070 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006071 lStatus = BAD_VALUE;
6072 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07006073 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006074 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006075
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006076 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006077
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006078 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07006079 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6080 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006081 if (handle != 0 && id != NULL) {
6082 *id = handle->id();
6083 }
6084 }
6085
6086Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006087 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006088 *status = lStatus;
6089 }
6090 return handle;
6091}
6092
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006093status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
6094 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07006095{
Steve Block3856b092011-10-20 11:56:00 +01006096 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07006097 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006098 Mutex::Autolock _l(mLock);
6099 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006100 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006101 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006102 }
Eric Laurentde070132010-07-13 04:45:46 -07006103 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6104 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006105 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006106 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006107 }
Eric Laurentde070132010-07-13 04:45:46 -07006108 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6109 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006110 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006111 return BAD_VALUE;
6112 }
6113
6114 Mutex::Autolock _dl(dstThread->mLock);
6115 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07006116 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07006117
Mathias Agopian65ab4712010-07-14 17:59:35 -07006118 return NO_ERROR;
6119}
6120
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006121// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07006122status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07006123 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07006124 AudioFlinger::PlaybackThread *dstThread,
6125 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07006126{
Steve Block3856b092011-10-20 11:56:00 +01006127 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006128 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07006129
Eric Laurent59255e42011-07-27 19:49:51 -07006130 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006131 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006132 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006133 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07006134 return INVALID_OPERATION;
6135 }
6136
Eric Laurent39e94f82010-07-28 01:32:47 -07006137 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07006138 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07006139 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07006140 // removed.
6141 srcThread->removeEffectChain_l(chain);
6142
6143 // transfer all effects one by one so that new effect chain is created on new thread with
6144 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006145 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07006146 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006147 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07006148 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6149 while (effect != 0) {
6150 srcThread->removeEffect_l(effect);
6151 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07006152 // removeEffect_l() has stopped the effect if it was active so it must be restarted
6153 if (effect->state() == EffectModule::ACTIVE ||
6154 effect->state() == EffectModule::STOPPING) {
6155 effect->start();
6156 }
Eric Laurent39e94f82010-07-28 01:32:47 -07006157 // if the move request is not received from audio policy manager, the effect must be
6158 // re-registered with the new strategy and output
6159 if (dstChain == 0) {
6160 dstChain = effect->chain().promote();
6161 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006162 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07006163 srcThread->addEffect_l(effect);
6164 return NO_INIT;
6165 }
6166 strategy = dstChain->strategy();
6167 }
6168 if (reRegister) {
6169 AudioSystem::unregisterEffect(effect->id());
6170 AudioSystem::registerEffect(&effect->desc(),
6171 dstOutput,
6172 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07006173 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07006174 effect->id());
6175 }
Eric Laurentde070132010-07-13 04:45:46 -07006176 effect = chain->getEffectFromId_l(0);
6177 }
6178
6179 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006180}
6181
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006182
Mathias Agopian65ab4712010-07-14 17:59:35 -07006183// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006184sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07006185 const sp<AudioFlinger::Client>& client,
6186 const sp<IEffectClient>& effectClient,
6187 int32_t priority,
6188 int sessionId,
6189 effect_descriptor_t *desc,
6190 int *enabled,
6191 status_t *status
6192 )
6193{
6194 sp<EffectModule> effect;
6195 sp<EffectHandle> handle;
6196 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006197 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07006198 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006199 bool effectCreated = false;
6200 bool effectRegistered = false;
6201
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006202 lStatus = initCheck();
6203 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006204 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006205 goto Exit;
6206 }
6207
6208 // Do not allow effects with session ID 0 on direct output or duplicating threads
6209 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07006210 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006211 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07006212 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006213 lStatus = BAD_VALUE;
6214 goto Exit;
6215 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006216 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08006217 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006218 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006219 desc->name, desc->flags, mType);
6220 lStatus = BAD_VALUE;
6221 goto Exit;
6222 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006223
Steve Block3856b092011-10-20 11:56:00 +01006224 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006225
6226 { // scope for mLock
6227 Mutex::Autolock _l(mLock);
6228
6229 // check for existing effect chain with the requested audio session
6230 chain = getEffectChain_l(sessionId);
6231 if (chain == 0) {
6232 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006233 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006234 chain = new EffectChain(this, sessionId);
6235 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07006236 chain->setStrategy(getStrategyForSession_l(sessionId));
6237 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006238 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07006239 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006240 }
6241
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08006242 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006243
6244 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006245 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006246 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07006247 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006248 if (lStatus != NO_ERROR) {
6249 goto Exit;
6250 }
6251 effectRegistered = true;
6252 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07006253 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006254 lStatus = effect->status();
6255 if (lStatus != NO_ERROR) {
6256 goto Exit;
6257 }
Eric Laurentcab11242010-07-15 12:50:15 -07006258 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006259 if (lStatus != NO_ERROR) {
6260 goto Exit;
6261 }
6262 effectCreated = true;
6263
6264 effect->setDevice(mDevice);
6265 effect->setMode(mAudioFlinger->getMode());
6266 }
6267 // create effect handle and connect it to effect module
6268 handle = new EffectHandle(effect, client, effectClient, priority);
6269 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08006270 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006271 *enabled = (int)effect->isEnabled();
6272 }
6273 }
6274
6275Exit:
6276 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07006277 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006278 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07006279 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006280 }
6281 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07006282 AudioSystem::unregisterEffect(effect->id());
6283 }
6284 if (chainCreated) {
6285 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006286 }
6287 handle.clear();
6288 }
6289
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006290 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006291 *status = lStatus;
6292 }
6293 return handle;
6294}
6295
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006296sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6297{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006298 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08006299 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006300}
6301
Eric Laurentde070132010-07-13 04:45:46 -07006302// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6303// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006304status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07006305{
6306 // check for existing effect chain with the requested audio session
6307 int sessionId = effect->sessionId();
6308 sp<EffectChain> chain = getEffectChain_l(sessionId);
6309 bool chainCreated = false;
6310
6311 if (chain == 0) {
6312 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006313 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006314 chain = new EffectChain(this, sessionId);
6315 addEffectChain_l(chain);
6316 chain->setStrategy(getStrategyForSession_l(sessionId));
6317 chainCreated = true;
6318 }
Steve Block3856b092011-10-20 11:56:00 +01006319 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006320
6321 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006322 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07006323 this, effect->desc().name, chain.get());
6324 return BAD_VALUE;
6325 }
6326
6327 status_t status = chain->addEffect_l(effect);
6328 if (status != NO_ERROR) {
6329 if (chainCreated) {
6330 removeEffectChain_l(chain);
6331 }
6332 return status;
6333 }
6334
6335 effect->setDevice(mDevice);
6336 effect->setMode(mAudioFlinger->getMode());
6337 return NO_ERROR;
6338}
6339
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006340void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07006341
Steve Block3856b092011-10-20 11:56:00 +01006342 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006343 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07006344 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6345 detachAuxEffect_l(effect->id());
6346 }
6347
6348 sp<EffectChain> chain = effect->chain().promote();
6349 if (chain != 0) {
6350 // remove effect chain if removing last effect
6351 if (chain->removeEffect_l(effect) == 0) {
6352 removeEffectChain_l(chain);
6353 }
6354 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00006355 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006356 }
6357}
6358
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006359void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006360 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006361{
6362 effectChains = mEffectChains;
6363 for (size_t i = 0; i < mEffectChains.size(); i++) {
6364 mEffectChains[i]->lock();
6365 }
6366}
6367
6368void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006369 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006370{
6371 for (size_t i = 0; i < effectChains.size(); i++) {
6372 effectChains[i]->unlock();
6373 }
6374}
6375
6376sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6377{
6378 Mutex::Autolock _l(mLock);
6379 return getEffectChain_l(sessionId);
6380}
6381
6382sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6383{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006384 size_t size = mEffectChains.size();
6385 for (size_t i = 0; i < size; i++) {
6386 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08006387 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006388 }
6389 }
Glenn Kasten090f0192012-01-30 13:00:02 -08006390 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006391}
6392
Glenn Kastenf78aee72012-01-04 11:00:47 -08006393void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006394{
6395 Mutex::Autolock _l(mLock);
6396 size_t size = mEffectChains.size();
6397 for (size_t i = 0; i < size; i++) {
6398 mEffectChains[i]->setMode_l(mode);
6399 }
6400}
6401
6402void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006403 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08006404 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07006405
Mathias Agopian65ab4712010-07-14 17:59:35 -07006406 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006407 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006408 // delete the effect module if removing last handle on it
6409 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006410 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006411 removeEffect_l(effect);
6412 AudioSystem::unregisterEffect(effect->id());
6413 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006414 }
6415}
6416
6417status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6418{
6419 int session = chain->sessionId();
6420 int16_t *buffer = mMixBuffer;
6421 bool ownsBuffer = false;
6422
Steve Block3856b092011-10-20 11:56:00 +01006423 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006424 if (session > 0) {
6425 // Only one effect chain can be present in direct output thread and it uses
6426 // the mix buffer as input
6427 if (mType != DIRECT) {
6428 size_t numSamples = mFrameCount * mChannelCount;
6429 buffer = new int16_t[numSamples];
6430 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01006431 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006432 ownsBuffer = true;
6433 }
6434
6435 // Attach all tracks with same session ID to this chain.
6436 for (size_t i = 0; i < mTracks.size(); ++i) {
6437 sp<Track> track = mTracks[i];
6438 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006439 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006440 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006441 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006442 }
6443 }
6444
6445 // indicate all active tracks in the chain
6446 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6447 sp<Track> track = mActiveTracks[i].promote();
6448 if (track == 0) continue;
6449 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006450 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07006451 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006452 }
6453 }
6454 }
6455
6456 chain->setInBuffer(buffer, ownsBuffer);
6457 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006458 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006459 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006460 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6461 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006462 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006463 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6464 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006465 // Effect chain for other sessions are inserted at beginning of effect
6466 // chains list to be processed before output mix effects. Relative order between other
6467 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006468 size_t size = mEffectChains.size();
6469 size_t i = 0;
6470 for (i = 0; i < size; i++) {
6471 if (mEffectChains[i]->sessionId() < session) break;
6472 }
6473 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006474 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006475
6476 return NO_ERROR;
6477}
6478
6479size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6480{
6481 int session = chain->sessionId();
6482
Steve Block3856b092011-10-20 11:56:00 +01006483 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006484
6485 for (size_t i = 0; i < mEffectChains.size(); i++) {
6486 if (chain == mEffectChains[i]) {
6487 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006488 // detach all active tracks from the chain
6489 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6490 sp<Track> track = mActiveTracks[i].promote();
6491 if (track == 0) continue;
6492 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006493 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006494 chain.get(), session);
6495 chain->decActiveTrackCnt();
6496 }
6497 }
6498
Mathias Agopian65ab4712010-07-14 17:59:35 -07006499 // detach all tracks with same session ID from this chain
6500 for (size_t i = 0; i < mTracks.size(); ++i) {
6501 sp<Track> track = mTracks[i];
6502 if (session == track->sessionId()) {
6503 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006504 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006505 }
6506 }
Eric Laurentde070132010-07-13 04:45:46 -07006507 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006508 }
6509 }
6510 return mEffectChains.size();
6511}
6512
Eric Laurentde070132010-07-13 04:45:46 -07006513status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6514 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006515{
6516 Mutex::Autolock _l(mLock);
6517 return attachAuxEffect_l(track, EffectId);
6518}
6519
Eric Laurentde070132010-07-13 04:45:46 -07006520status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6521 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006522{
6523 status_t status = NO_ERROR;
6524
6525 if (EffectId == 0) {
6526 track->setAuxBuffer(0, NULL);
6527 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006528 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6529 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006530 if (effect != 0) {
6531 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6532 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6533 } else {
6534 status = INVALID_OPERATION;
6535 }
6536 } else {
6537 status = BAD_VALUE;
6538 }
6539 }
6540 return status;
6541}
6542
6543void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6544{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006545 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006546 sp<Track> track = mTracks[i];
6547 if (track->auxEffectId() == effectId) {
6548 attachAuxEffect_l(track, 0);
6549 }
6550 }
6551}
6552
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006553status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6554{
6555 // only one chain per input thread
6556 if (mEffectChains.size() != 0) {
6557 return INVALID_OPERATION;
6558 }
Steve Block3856b092011-10-20 11:56:00 +01006559 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006560
6561 chain->setInBuffer(NULL);
6562 chain->setOutBuffer(NULL);
6563
Eric Laurent59255e42011-07-27 19:49:51 -07006564 checkSuspendOnAddEffectChain_l(chain);
6565
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006566 mEffectChains.add(chain);
6567
6568 return NO_ERROR;
6569}
6570
6571size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6572{
Steve Block3856b092011-10-20 11:56:00 +01006573 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006574 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006575 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6576 chain.get(), mEffectChains.size(), this);
6577 if (mEffectChains.size() == 1) {
6578 mEffectChains.removeAt(0);
6579 }
6580 return 0;
6581}
6582
Mathias Agopian65ab4712010-07-14 17:59:35 -07006583// ----------------------------------------------------------------------------
6584// EffectModule implementation
6585// ----------------------------------------------------------------------------
6586
6587#undef LOG_TAG
6588#define LOG_TAG "AudioFlinger::EffectModule"
6589
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006590AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006591 const wp<AudioFlinger::EffectChain>& chain,
6592 effect_descriptor_t *desc,
6593 int id,
6594 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006595 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006596 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006597{
Steve Block3856b092011-10-20 11:56:00 +01006598 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006599 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006600 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006601 return;
6602 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006603
6604 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6605
6606 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006607 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006608
6609 if (mStatus != NO_ERROR) {
6610 return;
6611 }
6612 lStatus = init();
6613 if (lStatus < 0) {
6614 mStatus = lStatus;
6615 goto Error;
6616 }
6617
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006618 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6619 mPinned = true;
6620 }
Steve Block3856b092011-10-20 11:56:00 +01006621 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006622 return;
6623Error:
6624 EffectRelease(mEffectInterface);
6625 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006626 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006627}
6628
6629AudioFlinger::EffectModule::~EffectModule()
6630{
Steve Block3856b092011-10-20 11:56:00 +01006631 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006632 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006633 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6634 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6635 sp<ThreadBase> thread = mThread.promote();
6636 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006637 audio_stream_t *stream = thread->stream();
6638 if (stream != NULL) {
6639 stream->remove_audio_effect(stream, mEffectInterface);
6640 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006641 }
6642 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006643 // release effect engine
6644 EffectRelease(mEffectInterface);
6645 }
6646}
6647
Glenn Kasten435dbe62012-01-30 10:15:48 -08006648status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006649{
6650 status_t status;
6651
6652 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006653 int priority = handle->priority();
6654 size_t size = mHandles.size();
6655 sp<EffectHandle> h;
6656 size_t i;
6657 for (i = 0; i < size; i++) {
6658 h = mHandles[i].promote();
6659 if (h == 0) continue;
6660 if (h->priority() <= priority) break;
6661 }
6662 // if inserted in first place, move effect control from previous owner to this handle
6663 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006664 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006665 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006666 enabled = h->enabled();
6667 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006668 }
Eric Laurent59255e42011-07-27 19:49:51 -07006669 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006670 status = NO_ERROR;
6671 } else {
6672 status = ALREADY_EXISTS;
6673 }
Steve Block3856b092011-10-20 11:56:00 +01006674 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006675 mHandles.insertAt(handle, i);
6676 return status;
6677}
6678
6679size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6680{
6681 Mutex::Autolock _l(mLock);
6682 size_t size = mHandles.size();
6683 size_t i;
6684 for (i = 0; i < size; i++) {
6685 if (mHandles[i] == handle) break;
6686 }
6687 if (i == size) {
6688 return size;
6689 }
Steve Block3856b092011-10-20 11:56:00 +01006690 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006691
6692 bool enabled = false;
6693 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006694 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006695 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006696 enabled = hdl->enabled();
6697 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006698 mHandles.removeAt(i);
6699 size = mHandles.size();
6700 // if removed from first place, move effect control from this handle to next in line
6701 if (i == 0 && size != 0) {
6702 sp<EffectHandle> h = mHandles[0].promote();
6703 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006704 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006705 }
6706 }
6707
Eric Laurentec437d82011-07-26 20:54:46 -07006708 // Prevent calls to process() and other functions on effect interface from now on.
6709 // The effect engine will be released by the destructor when the last strong reference on
6710 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006711 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006712 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006713 }
6714
Mathias Agopian65ab4712010-07-14 17:59:35 -07006715 return size;
6716}
6717
Eric Laurent59255e42011-07-27 19:49:51 -07006718sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6719{
6720 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08006721 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07006722}
6723
Glenn Kasten58123c32012-02-03 10:32:24 -08006724void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006725{
Glenn Kasten90bebef2012-01-27 15:24:38 -08006726 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006727 // keep a strong reference on this EffectModule to avoid calling the
6728 // destructor before we exit
6729 sp<EffectModule> keep(this);
6730 {
6731 sp<ThreadBase> thread = mThread.promote();
6732 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006733 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006734 }
6735 }
6736}
6737
6738void AudioFlinger::EffectModule::updateState() {
6739 Mutex::Autolock _l(mLock);
6740
6741 switch (mState) {
6742 case RESTART:
6743 reset_l();
6744 // FALL THROUGH
6745
6746 case STARTING:
6747 // clear auxiliary effect input buffer for next accumulation
6748 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6749 memset(mConfig.inputCfg.buffer.raw,
6750 0,
6751 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6752 }
6753 start_l();
6754 mState = ACTIVE;
6755 break;
6756 case STOPPING:
6757 stop_l();
6758 mDisableWaitCnt = mMaxDisableWaitCnt;
6759 mState = STOPPED;
6760 break;
6761 case STOPPED:
6762 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6763 // turn off sequence.
6764 if (--mDisableWaitCnt == 0) {
6765 reset_l();
6766 mState = IDLE;
6767 }
6768 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006769 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006770 break;
6771 }
6772}
6773
6774void AudioFlinger::EffectModule::process()
6775{
6776 Mutex::Autolock _l(mLock);
6777
Eric Laurentec437d82011-07-26 20:54:46 -07006778 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006779 mConfig.inputCfg.buffer.raw == NULL ||
6780 mConfig.outputCfg.buffer.raw == NULL) {
6781 return;
6782 }
6783
Eric Laurent8f45bd72010-08-31 13:50:07 -07006784 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006785 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6786 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006787 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006788 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006789 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006790 }
6791
6792 // do the actual processing in the effect engine
6793 int ret = (*mEffectInterface)->process(mEffectInterface,
6794 &mConfig.inputCfg.buffer,
6795 &mConfig.outputCfg.buffer);
6796
6797 // force transition to IDLE state when engine is ready
6798 if (mState == STOPPED && ret == -ENODATA) {
6799 mDisableWaitCnt = 1;
6800 }
6801
6802 // clear auxiliary effect input buffer for next accumulation
6803 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006804 memset(mConfig.inputCfg.buffer.raw, 0,
6805 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006806 }
6807 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006808 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6809 // If an insert effect is idle and input buffer is different from output buffer,
6810 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006811 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006812 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006813 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6814 int16_t *in = mConfig.inputCfg.buffer.s16;
6815 int16_t *out = mConfig.outputCfg.buffer.s16;
6816 for (size_t i = 0; i < frameCnt; i++) {
6817 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006818 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006819 }
6820 }
6821}
6822
6823void AudioFlinger::EffectModule::reset_l()
6824{
6825 if (mEffectInterface == NULL) {
6826 return;
6827 }
6828 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6829}
6830
6831status_t AudioFlinger::EffectModule::configure()
6832{
6833 uint32_t channels;
6834 if (mEffectInterface == NULL) {
6835 return NO_INIT;
6836 }
6837
6838 sp<ThreadBase> thread = mThread.promote();
6839 if (thread == 0) {
6840 return DEAD_OBJECT;
6841 }
6842
6843 // TODO: handle configuration of effects replacing track process
6844 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006845 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006846 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006847 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006848 }
6849
6850 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006851 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006852 } else {
6853 mConfig.inputCfg.channels = channels;
6854 }
6855 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006856 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6857 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006858 mConfig.inputCfg.samplingRate = thread->sampleRate();
6859 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6860 mConfig.inputCfg.bufferProvider.cookie = NULL;
6861 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6862 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6863 mConfig.outputCfg.bufferProvider.cookie = NULL;
6864 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6865 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6866 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6867 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006868 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006869 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006870 // - in other sessions:
6871 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6872 // other effect: overwrites output buffer: input buffer == output buffer
6873 // Auxiliary effect:
6874 // accumulates in output buffer: input buffer != output buffer
6875 // Therefore: accumulate <=> input buffer != output buffer
6876 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6877 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6878 } else {
6879 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6880 }
6881 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6882 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6883 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6884 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6885
Steve Block3856b092011-10-20 11:56:00 +01006886 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006887 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6888
Mathias Agopian65ab4712010-07-14 17:59:35 -07006889 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006890 uint32_t size = sizeof(int);
6891 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006892 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006893 sizeof(effect_config_t),
6894 &mConfig,
6895 &size,
6896 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006897 if (status == 0) {
6898 status = cmdStatus;
6899 }
6900
6901 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6902 (1000 * mConfig.outputCfg.buffer.frameCount);
6903
6904 return status;
6905}
6906
6907status_t AudioFlinger::EffectModule::init()
6908{
6909 Mutex::Autolock _l(mLock);
6910 if (mEffectInterface == NULL) {
6911 return NO_INIT;
6912 }
6913 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006914 uint32_t size = sizeof(status_t);
6915 status_t status = (*mEffectInterface)->command(mEffectInterface,
6916 EFFECT_CMD_INIT,
6917 0,
6918 NULL,
6919 &size,
6920 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006921 if (status == 0) {
6922 status = cmdStatus;
6923 }
6924 return status;
6925}
6926
Eric Laurentec35a142011-10-05 17:42:25 -07006927status_t AudioFlinger::EffectModule::start()
6928{
6929 Mutex::Autolock _l(mLock);
6930 return start_l();
6931}
6932
Mathias Agopian65ab4712010-07-14 17:59:35 -07006933status_t AudioFlinger::EffectModule::start_l()
6934{
6935 if (mEffectInterface == NULL) {
6936 return NO_INIT;
6937 }
6938 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006939 uint32_t size = sizeof(status_t);
6940 status_t status = (*mEffectInterface)->command(mEffectInterface,
6941 EFFECT_CMD_ENABLE,
6942 0,
6943 NULL,
6944 &size,
6945 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006946 if (status == 0) {
6947 status = cmdStatus;
6948 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006949 if (status == 0 &&
6950 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6951 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6952 sp<ThreadBase> thread = mThread.promote();
6953 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006954 audio_stream_t *stream = thread->stream();
6955 if (stream != NULL) {
6956 stream->add_audio_effect(stream, mEffectInterface);
6957 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006958 }
6959 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006960 return status;
6961}
6962
Eric Laurentec437d82011-07-26 20:54:46 -07006963status_t AudioFlinger::EffectModule::stop()
6964{
6965 Mutex::Autolock _l(mLock);
6966 return stop_l();
6967}
6968
Mathias Agopian65ab4712010-07-14 17:59:35 -07006969status_t AudioFlinger::EffectModule::stop_l()
6970{
6971 if (mEffectInterface == NULL) {
6972 return NO_INIT;
6973 }
6974 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006975 uint32_t size = sizeof(status_t);
6976 status_t status = (*mEffectInterface)->command(mEffectInterface,
6977 EFFECT_CMD_DISABLE,
6978 0,
6979 NULL,
6980 &size,
6981 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006982 if (status == 0) {
6983 status = cmdStatus;
6984 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006985 if (status == 0 &&
6986 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6987 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6988 sp<ThreadBase> thread = mThread.promote();
6989 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006990 audio_stream_t *stream = thread->stream();
6991 if (stream != NULL) {
6992 stream->remove_audio_effect(stream, mEffectInterface);
6993 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006994 }
6995 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006996 return status;
6997}
6998
Eric Laurent25f43952010-07-28 05:40:18 -07006999status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
7000 uint32_t cmdSize,
7001 void *pCmdData,
7002 uint32_t *replySize,
7003 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007004{
7005 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007006// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007007
Eric Laurentec437d82011-07-26 20:54:46 -07007008 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007009 return NO_INIT;
7010 }
Eric Laurent25f43952010-07-28 05:40:18 -07007011 status_t status = (*mEffectInterface)->command(mEffectInterface,
7012 cmdCode,
7013 cmdSize,
7014 pCmdData,
7015 replySize,
7016 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007017 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07007018 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007019 for (size_t i = 1; i < mHandles.size(); i++) {
7020 sp<EffectHandle> h = mHandles[i].promote();
7021 if (h != 0) {
7022 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
7023 }
7024 }
7025 }
7026 return status;
7027}
7028
7029status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
7030{
Eric Laurentdb7c0792011-08-10 10:37:50 -07007031
Mathias Agopian65ab4712010-07-14 17:59:35 -07007032 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007033 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007034
7035 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007036 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
7037 if (enabled && status != NO_ERROR) {
7038 return status;
7039 }
7040
Mathias Agopian65ab4712010-07-14 17:59:35 -07007041 switch (mState) {
7042 // going from disabled to enabled
7043 case IDLE:
7044 mState = STARTING;
7045 break;
7046 case STOPPED:
7047 mState = RESTART;
7048 break;
7049 case STOPPING:
7050 mState = ACTIVE;
7051 break;
7052
7053 // going from enabled to disabled
7054 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007055 mState = STOPPED;
7056 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007057 case STARTING:
7058 mState = IDLE;
7059 break;
7060 case ACTIVE:
7061 mState = STOPPING;
7062 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007063 case DESTROYED:
7064 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007065 }
7066 for (size_t i = 1; i < mHandles.size(); i++) {
7067 sp<EffectHandle> h = mHandles[i].promote();
7068 if (h != 0) {
7069 h->setEnabled(enabled);
7070 }
7071 }
7072 }
7073 return NO_ERROR;
7074}
7075
Glenn Kastenc59c0042012-02-02 14:06:11 -08007076bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007077{
7078 switch (mState) {
7079 case RESTART:
7080 case STARTING:
7081 case ACTIVE:
7082 return true;
7083 case IDLE:
7084 case STOPPING:
7085 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07007086 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07007087 default:
7088 return false;
7089 }
7090}
7091
Glenn Kastenc59c0042012-02-02 14:06:11 -08007092bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07007093{
7094 switch (mState) {
7095 case RESTART:
7096 case ACTIVE:
7097 case STOPPING:
7098 case STOPPED:
7099 return true;
7100 case IDLE:
7101 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07007102 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007103 default:
7104 return false;
7105 }
7106}
7107
Mathias Agopian65ab4712010-07-14 17:59:35 -07007108status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7109{
7110 Mutex::Autolock _l(mLock);
7111 status_t status = NO_ERROR;
7112
7113 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7114 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07007115 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07007116 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7117 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007118 status_t cmdStatus;
7119 uint32_t volume[2];
7120 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07007121 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007122 volume[0] = *left;
7123 volume[1] = *right;
7124 if (controller) {
7125 pVolume = volume;
7126 }
Eric Laurent25f43952010-07-28 05:40:18 -07007127 status = (*mEffectInterface)->command(mEffectInterface,
7128 EFFECT_CMD_SET_VOLUME,
7129 size,
7130 volume,
7131 &size,
7132 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007133 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7134 *left = volume[0];
7135 *right = volume[1];
7136 }
7137 }
7138 return status;
7139}
7140
7141status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7142{
7143 Mutex::Autolock _l(mLock);
7144 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007145 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7146 // audio pre processing modules on RecordThread can receive both output and
7147 // input device indication in the same call
7148 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7149 if (dev) {
7150 status_t cmdStatus;
7151 uint32_t size = sizeof(status_t);
7152
7153 status = (*mEffectInterface)->command(mEffectInterface,
7154 EFFECT_CMD_SET_DEVICE,
7155 sizeof(uint32_t),
7156 &dev,
7157 &size,
7158 &cmdStatus);
7159 if (status == NO_ERROR) {
7160 status = cmdStatus;
7161 }
7162 }
7163 dev = device & AUDIO_DEVICE_IN_ALL;
7164 if (dev) {
7165 status_t cmdStatus;
7166 uint32_t size = sizeof(status_t);
7167
7168 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7169 EFFECT_CMD_SET_INPUT_DEVICE,
7170 sizeof(uint32_t),
7171 &dev,
7172 &size,
7173 &cmdStatus);
7174 if (status2 == NO_ERROR) {
7175 status2 = cmdStatus;
7176 }
7177 if (status == NO_ERROR) {
7178 status = status2;
7179 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007180 }
7181 }
7182 return status;
7183}
7184
Glenn Kastenf78aee72012-01-04 11:00:47 -08007185status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007186{
7187 Mutex::Autolock _l(mLock);
7188 status_t status = NO_ERROR;
7189 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007190 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007191 uint32_t size = sizeof(status_t);
7192 status = (*mEffectInterface)->command(mEffectInterface,
7193 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08007194 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07007195 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07007196 &size,
7197 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007198 if (status == NO_ERROR) {
7199 status = cmdStatus;
7200 }
7201 }
7202 return status;
7203}
7204
Eric Laurent59255e42011-07-27 19:49:51 -07007205void AudioFlinger::EffectModule::setSuspended(bool suspended)
7206{
7207 Mutex::Autolock _l(mLock);
7208 mSuspended = suspended;
7209}
Glenn Kastena3a85482012-01-04 11:01:11 -08007210
7211bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07007212{
7213 Mutex::Autolock _l(mLock);
7214 return mSuspended;
7215}
7216
Mathias Agopian65ab4712010-07-14 17:59:35 -07007217status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7218{
7219 const size_t SIZE = 256;
7220 char buffer[SIZE];
7221 String8 result;
7222
7223 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7224 result.append(buffer);
7225
7226 bool locked = tryLock(mLock);
7227 // failed to lock - AudioFlinger is probably deadlocked
7228 if (!locked) {
7229 result.append("\t\tCould not lock Fx mutex:\n");
7230 }
7231
7232 result.append("\t\tSession Status State Engine:\n");
7233 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7234 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7235 result.append(buffer);
7236
7237 result.append("\t\tDescriptor:\n");
7238 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7239 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7240 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7241 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7242 result.append(buffer);
7243 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7244 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7245 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7246 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7247 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07007248 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007249 mDescriptor.apiVersion,
7250 mDescriptor.flags);
7251 result.append(buffer);
7252 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7253 mDescriptor.name);
7254 result.append(buffer);
7255 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7256 mDescriptor.implementor);
7257 result.append(buffer);
7258
7259 result.append("\t\t- Input configuration:\n");
7260 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7261 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7262 (uint32_t)mConfig.inputCfg.buffer.raw,
7263 mConfig.inputCfg.buffer.frameCount,
7264 mConfig.inputCfg.samplingRate,
7265 mConfig.inputCfg.channels,
7266 mConfig.inputCfg.format);
7267 result.append(buffer);
7268
7269 result.append("\t\t- Output configuration:\n");
7270 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7271 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7272 (uint32_t)mConfig.outputCfg.buffer.raw,
7273 mConfig.outputCfg.buffer.frameCount,
7274 mConfig.outputCfg.samplingRate,
7275 mConfig.outputCfg.channels,
7276 mConfig.outputCfg.format);
7277 result.append(buffer);
7278
7279 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7280 result.append(buffer);
7281 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7282 for (size_t i = 0; i < mHandles.size(); ++i) {
7283 sp<EffectHandle> handle = mHandles[i].promote();
7284 if (handle != 0) {
7285 handle->dump(buffer, SIZE);
7286 result.append(buffer);
7287 }
7288 }
7289
7290 result.append("\n");
7291
7292 write(fd, result.string(), result.length());
7293
7294 if (locked) {
7295 mLock.unlock();
7296 }
7297
7298 return NO_ERROR;
7299}
7300
7301// ----------------------------------------------------------------------------
7302// EffectHandle implementation
7303// ----------------------------------------------------------------------------
7304
7305#undef LOG_TAG
7306#define LOG_TAG "AudioFlinger::EffectHandle"
7307
7308AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7309 const sp<AudioFlinger::Client>& client,
7310 const sp<IEffectClient>& effectClient,
7311 int32_t priority)
7312 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007313 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007314 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007315{
Steve Block3856b092011-10-20 11:56:00 +01007316 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007317
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007318 if (client == 0) {
7319 return;
7320 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007321 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7322 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7323 if (mCblkMemory != 0) {
7324 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7325
Glenn Kastena0d68332012-01-27 16:47:15 -08007326 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007327 new(mCblk) effect_param_cblk_t();
7328 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007329 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007330 } else {
Steve Block29357bc2012-01-06 19:20:56 +00007331 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007332 return;
7333 }
7334}
7335
7336AudioFlinger::EffectHandle::~EffectHandle()
7337{
Steve Block3856b092011-10-20 11:56:00 +01007338 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007339 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01007340 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007341}
7342
7343status_t AudioFlinger::EffectHandle::enable()
7344{
Steve Block3856b092011-10-20 11:56:00 +01007345 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007346 if (!mHasControl) return INVALID_OPERATION;
7347 if (mEffect == 0) return DEAD_OBJECT;
7348
Eric Laurentdb7c0792011-08-10 10:37:50 -07007349 if (mEnabled) {
7350 return NO_ERROR;
7351 }
7352
Eric Laurent59255e42011-07-27 19:49:51 -07007353 mEnabled = true;
7354
7355 sp<ThreadBase> thread = mEffect->thread().promote();
7356 if (thread != 0) {
7357 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7358 }
7359
7360 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7361 if (mEffect->suspended()) {
7362 return NO_ERROR;
7363 }
7364
Eric Laurentdb7c0792011-08-10 10:37:50 -07007365 status_t status = mEffect->setEnabled(true);
7366 if (status != NO_ERROR) {
7367 if (thread != 0) {
7368 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7369 }
7370 mEnabled = false;
7371 }
7372 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007373}
7374
7375status_t AudioFlinger::EffectHandle::disable()
7376{
Steve Block3856b092011-10-20 11:56:00 +01007377 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007378 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07007379 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007380
Eric Laurentdb7c0792011-08-10 10:37:50 -07007381 if (!mEnabled) {
7382 return NO_ERROR;
7383 }
Eric Laurent59255e42011-07-27 19:49:51 -07007384 mEnabled = false;
7385
7386 if (mEffect->suspended()) {
7387 return NO_ERROR;
7388 }
7389
7390 status_t status = mEffect->setEnabled(false);
7391
7392 sp<ThreadBase> thread = mEffect->thread().promote();
7393 if (thread != 0) {
7394 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7395 }
7396
7397 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007398}
7399
7400void AudioFlinger::EffectHandle::disconnect()
7401{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007402 disconnect(true);
7403}
7404
Glenn Kasten58123c32012-02-03 10:32:24 -08007405void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007406{
Glenn Kasten58123c32012-02-03 10:32:24 -08007407 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007408 if (mEffect == 0) {
7409 return;
7410 }
Glenn Kasten58123c32012-02-03 10:32:24 -08007411 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07007412
Eric Laurenta85a74a2011-10-19 11:44:54 -07007413 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007414 sp<ThreadBase> thread = mEffect->thread().promote();
7415 if (thread != 0) {
7416 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7417 }
Eric Laurent59255e42011-07-27 19:49:51 -07007418 }
7419
Mathias Agopian65ab4712010-07-14 17:59:35 -07007420 // release sp on module => module destructor can be called now
7421 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007422 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08007423 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08007424 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007425 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7426 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08007427 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007428 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07007429 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7430 mClient.clear();
7431 }
7432}
7433
Eric Laurent25f43952010-07-28 05:40:18 -07007434status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7435 uint32_t cmdSize,
7436 void *pCmdData,
7437 uint32_t *replySize,
7438 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007439{
Steve Block3856b092011-10-20 11:56:00 +01007440// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07007441// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007442
7443 // only get parameter command is permitted for applications not controlling the effect
7444 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7445 return INVALID_OPERATION;
7446 }
7447 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007448 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007449
7450 // handle commands that are not forwarded transparently to effect engine
7451 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7452 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7453 // no risk to block the whole media server process or mixer threads is we are stuck here
7454 Mutex::Autolock _l(mCblk->lock);
7455 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7456 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7457 mCblk->serverIndex = 0;
7458 mCblk->clientIndex = 0;
7459 return BAD_VALUE;
7460 }
7461 status_t status = NO_ERROR;
7462 while (mCblk->serverIndex < mCblk->clientIndex) {
7463 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007464 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007465 int *p = (int *)(mBuffer + mCblk->serverIndex);
7466 int size = *p++;
7467 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007468 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007469 break;
7470 }
7471 effect_param_t *param = (effect_param_t *)p;
7472 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007473 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007474 mCblk->serverIndex += size;
7475 continue;
7476 }
Eric Laurent25f43952010-07-28 05:40:18 -07007477 uint32_t psize = sizeof(effect_param_t) +
7478 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7479 param->vsize;
7480 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7481 psize,
7482 p,
7483 &rsize,
7484 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007485 // stop at first error encountered
7486 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007487 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007488 *(int *)pReplyData = reply;
7489 break;
7490 } else if (reply != NO_ERROR) {
7491 *(int *)pReplyData = reply;
7492 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007493 }
7494 mCblk->serverIndex += size;
7495 }
7496 mCblk->serverIndex = 0;
7497 mCblk->clientIndex = 0;
7498 return status;
7499 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007500 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007501 return enable();
7502 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007503 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007504 return disable();
7505 }
7506
7507 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7508}
7509
Eric Laurent59255e42011-07-27 19:49:51 -07007510void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007511{
Steve Block3856b092011-10-20 11:56:00 +01007512 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007513
7514 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007515 mEnabled = enabled;
7516
Mathias Agopian65ab4712010-07-14 17:59:35 -07007517 if (signal && mEffectClient != 0) {
7518 mEffectClient->controlStatusChanged(hasControl);
7519 }
7520}
7521
Eric Laurent25f43952010-07-28 05:40:18 -07007522void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7523 uint32_t cmdSize,
7524 void *pCmdData,
7525 uint32_t replySize,
7526 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007527{
7528 if (mEffectClient != 0) {
7529 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7530 }
7531}
7532
7533
7534
7535void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7536{
7537 if (mEffectClient != 0) {
7538 mEffectClient->enableStatusChanged(enabled);
7539 }
7540}
7541
7542status_t AudioFlinger::EffectHandle::onTransact(
7543 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7544{
7545 return BnEffect::onTransact(code, data, reply, flags);
7546}
7547
7548
7549void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7550{
Glenn Kastena0d68332012-01-27 16:47:15 -08007551 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007552
7553 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08007554 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007555 mPriority,
7556 mHasControl,
7557 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007558 mCblk ? mCblk->clientIndex : 0,
7559 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007560 );
7561
7562 if (locked) {
7563 mCblk->lock.unlock();
7564 }
7565}
7566
7567#undef LOG_TAG
7568#define LOG_TAG "AudioFlinger::EffectChain"
7569
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007570AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007571 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007572 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007573 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7574 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007575{
Dima Zavinfce7a472011-04-19 22:30:36 -07007576 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007577 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007578 return;
7579 }
7580 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7581 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007582}
7583
7584AudioFlinger::EffectChain::~EffectChain()
7585{
7586 if (mOwnInBuffer) {
7587 delete mInBuffer;
7588 }
7589
7590}
7591
Eric Laurent59255e42011-07-27 19:49:51 -07007592// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007593sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007594{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007595 size_t size = mEffects.size();
7596
7597 for (size_t i = 0; i < size; i++) {
7598 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007599 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007600 }
7601 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007602 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007603}
7604
Eric Laurent59255e42011-07-27 19:49:51 -07007605// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007606sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007607{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007608 size_t size = mEffects.size();
7609
7610 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007611 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7612 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007613 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007614 }
7615 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007616 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007617}
7618
Eric Laurent59255e42011-07-27 19:49:51 -07007619// getEffectFromType_l() must be called with ThreadBase::mLock held
7620sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7621 const effect_uuid_t *type)
7622{
Eric Laurent59255e42011-07-27 19:49:51 -07007623 size_t size = mEffects.size();
7624
7625 for (size_t i = 0; i < size; i++) {
7626 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007627 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007628 }
7629 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007630 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007631}
7632
Mathias Agopian65ab4712010-07-14 17:59:35 -07007633// Must be called with EffectChain::mLock locked
7634void AudioFlinger::EffectChain::process_l()
7635{
Eric Laurentdac69112010-09-28 14:09:57 -07007636 sp<ThreadBase> thread = mThread.promote();
7637 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007638 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007639 return;
7640 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007641 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7642 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007643 // always process effects unless no more tracks are on the session and the effect tail
7644 // has been rendered
7645 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007646 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007647 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007648
Eric Laurent544fe9b2011-11-11 15:42:52 -08007649 if (!tracksOnSession && mTailBufferCount == 0) {
7650 doProcess = false;
7651 }
7652
7653 if (activeTrackCnt() == 0) {
7654 // if no track is active and the effect tail has not been rendered,
7655 // the input buffer must be cleared here as the mixer process will not do it
7656 if (tracksOnSession || mTailBufferCount > 0) {
7657 size_t numSamples = thread->frameCount() * thread->channelCount();
7658 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7659 if (mTailBufferCount > 0) {
7660 mTailBufferCount--;
7661 }
7662 }
7663 }
Eric Laurentdac69112010-09-28 14:09:57 -07007664 }
7665
Mathias Agopian65ab4712010-07-14 17:59:35 -07007666 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007667 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007668 for (size_t i = 0; i < size; i++) {
7669 mEffects[i]->process();
7670 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007671 }
7672 for (size_t i = 0; i < size; i++) {
7673 mEffects[i]->updateState();
7674 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007675}
7676
Eric Laurentcab11242010-07-15 12:50:15 -07007677// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007678status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007679{
7680 effect_descriptor_t desc = effect->desc();
7681 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7682
7683 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007684 effect->setChain(this);
7685 sp<ThreadBase> thread = mThread.promote();
7686 if (thread == 0) {
7687 return NO_INIT;
7688 }
7689 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007690
7691 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7692 // Auxiliary effects are inserted at the beginning of mEffects vector as
7693 // they are processed first and accumulated in chain input buffer
7694 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007695
Mathias Agopian65ab4712010-07-14 17:59:35 -07007696 // the input buffer for auxiliary effect contains mono samples in
7697 // 32 bit format. This is to avoid saturation in AudoMixer
7698 // accumulation stage. Saturation is done in EffectModule::process() before
7699 // calling the process in effect engine
7700 size_t numSamples = thread->frameCount();
7701 int32_t *buffer = new int32_t[numSamples];
7702 memset(buffer, 0, numSamples * sizeof(int32_t));
7703 effect->setInBuffer((int16_t *)buffer);
7704 // auxiliary effects output samples to chain input buffer for further processing
7705 // by insert effects
7706 effect->setOutBuffer(mInBuffer);
7707 } else {
7708 // Insert effects are inserted at the end of mEffects vector as they are processed
7709 // after track and auxiliary effects.
7710 // Insert effect order as a function of indicated preference:
7711 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7712 // another effect is present
7713 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7714 // last effect claiming first position
7715 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7716 // first effect claiming last position
7717 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7718 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7719 // already present
7720
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007721 size_t size = mEffects.size();
7722 size_t idx_insert = size;
7723 ssize_t idx_insert_first = -1;
7724 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007725
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007726 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007727 effect_descriptor_t d = mEffects[i]->desc();
7728 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7729 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7730 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7731 // check invalid effect chaining combinations
7732 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7733 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007734 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007735 return INVALID_OPERATION;
7736 }
7737 // remember position of first insert effect and by default
7738 // select this as insert position for new effect
7739 if (idx_insert == size) {
7740 idx_insert = i;
7741 }
7742 // remember position of last insert effect claiming
7743 // first position
7744 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7745 idx_insert_first = i;
7746 }
7747 // remember position of first insert effect claiming
7748 // last position
7749 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7750 idx_insert_last == -1) {
7751 idx_insert_last = i;
7752 }
7753 }
7754 }
7755
7756 // modify idx_insert from first position if needed
7757 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7758 if (idx_insert_last != -1) {
7759 idx_insert = idx_insert_last;
7760 } else {
7761 idx_insert = size;
7762 }
7763 } else {
7764 if (idx_insert_first != -1) {
7765 idx_insert = idx_insert_first + 1;
7766 }
7767 }
7768
7769 // always read samples from chain input buffer
7770 effect->setInBuffer(mInBuffer);
7771
7772 // if last effect in the chain, output samples to chain
7773 // output buffer, otherwise to chain input buffer
7774 if (idx_insert == size) {
7775 if (idx_insert != 0) {
7776 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7777 mEffects[idx_insert-1]->configure();
7778 }
7779 effect->setOutBuffer(mOutBuffer);
7780 } else {
7781 effect->setOutBuffer(mInBuffer);
7782 }
7783 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007784
Steve Block3856b092011-10-20 11:56:00 +01007785 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007786 }
7787 effect->configure();
7788 return NO_ERROR;
7789}
7790
Eric Laurentcab11242010-07-15 12:50:15 -07007791// removeEffect_l() must be called with PlaybackThread::mLock held
7792size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007793{
7794 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007795 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007796 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7797
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007798 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007799 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007800 // calling stop here will remove pre-processing effect from the audio HAL.
7801 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7802 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007803 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7804 mEffects[i]->state() == EffectModule::STOPPING) {
7805 mEffects[i]->stop();
7806 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007807 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7808 delete[] effect->inBuffer();
7809 } else {
7810 if (i == size - 1 && i != 0) {
7811 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7812 mEffects[i - 1]->configure();
7813 }
7814 }
7815 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007816 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007817 break;
7818 }
7819 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007820
7821 return mEffects.size();
7822}
7823
Eric Laurentcab11242010-07-15 12:50:15 -07007824// setDevice_l() must be called with PlaybackThread::mLock held
7825void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007826{
7827 size_t size = mEffects.size();
7828 for (size_t i = 0; i < size; i++) {
7829 mEffects[i]->setDevice(device);
7830 }
7831}
7832
Eric Laurentcab11242010-07-15 12:50:15 -07007833// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007834void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007835{
7836 size_t size = mEffects.size();
7837 for (size_t i = 0; i < size; i++) {
7838 mEffects[i]->setMode(mode);
7839 }
7840}
7841
Eric Laurentcab11242010-07-15 12:50:15 -07007842// setVolume_l() must be called with PlaybackThread::mLock held
7843bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007844{
7845 uint32_t newLeft = *left;
7846 uint32_t newRight = *right;
7847 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007848 int ctrlIdx = -1;
7849 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007850
Eric Laurentcab11242010-07-15 12:50:15 -07007851 // first update volume controller
7852 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007853 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007854 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7855 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007856 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007857 break;
7858 }
7859 }
7860
7861 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007862 if (hasControl) {
7863 *left = mNewLeftVolume;
7864 *right = mNewRightVolume;
7865 }
7866 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007867 }
7868
7869 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007870 mLeftVolume = newLeft;
7871 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007872
7873 // second get volume update from volume controller
7874 if (ctrlIdx >= 0) {
7875 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007876 mNewLeftVolume = newLeft;
7877 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007878 }
7879 // then indicate volume to all other effects in chain.
7880 // Pass altered volume to effects before volume controller
7881 // and requested volume to effects after controller
7882 uint32_t lVol = newLeft;
7883 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007884
Mathias Agopian65ab4712010-07-14 17:59:35 -07007885 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007886 if ((int)i == ctrlIdx) continue;
7887 // this also works for ctrlIdx == -1 when there is no volume controller
7888 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007889 lVol = *left;
7890 rVol = *right;
7891 }
7892 mEffects[i]->setVolume(&lVol, &rVol, false);
7893 }
7894 *left = newLeft;
7895 *right = newRight;
7896
7897 return hasControl;
7898}
7899
Mathias Agopian65ab4712010-07-14 17:59:35 -07007900status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7901{
7902 const size_t SIZE = 256;
7903 char buffer[SIZE];
7904 String8 result;
7905
7906 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7907 result.append(buffer);
7908
7909 bool locked = tryLock(mLock);
7910 // failed to lock - AudioFlinger is probably deadlocked
7911 if (!locked) {
7912 result.append("\tCould not lock mutex:\n");
7913 }
7914
Eric Laurentcab11242010-07-15 12:50:15 -07007915 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7916 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007917 mEffects.size(),
7918 (uint32_t)mInBuffer,
7919 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007920 mActiveTrackCnt);
7921 result.append(buffer);
7922 write(fd, result.string(), result.size());
7923
7924 for (size_t i = 0; i < mEffects.size(); ++i) {
7925 sp<EffectModule> effect = mEffects[i];
7926 if (effect != 0) {
7927 effect->dump(fd, args);
7928 }
7929 }
7930
7931 if (locked) {
7932 mLock.unlock();
7933 }
7934
7935 return NO_ERROR;
7936}
7937
Eric Laurent59255e42011-07-27 19:49:51 -07007938// must be called with ThreadBase::mLock held
7939void AudioFlinger::EffectChain::setEffectSuspended_l(
7940 const effect_uuid_t *type, bool suspend)
7941{
7942 sp<SuspendedEffectDesc> desc;
7943 // use effect type UUID timelow as key as there is no real risk of identical
7944 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007945 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007946 if (suspend) {
7947 if (index >= 0) {
7948 desc = mSuspendedEffects.valueAt(index);
7949 } else {
7950 desc = new SuspendedEffectDesc();
7951 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7952 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007953 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007954 }
7955 if (desc->mRefCount++ == 0) {
7956 sp<EffectModule> effect = getEffectIfEnabled(type);
7957 if (effect != 0) {
7958 desc->mEffect = effect;
7959 effect->setSuspended(true);
7960 effect->setEnabled(false);
7961 }
7962 }
7963 } else {
7964 if (index < 0) {
7965 return;
7966 }
7967 desc = mSuspendedEffects.valueAt(index);
7968 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007969 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007970 desc->mRefCount = 1;
7971 }
7972 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007973 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007974 if (desc->mEffect != 0) {
7975 sp<EffectModule> effect = desc->mEffect.promote();
7976 if (effect != 0) {
7977 effect->setSuspended(false);
7978 sp<EffectHandle> handle = effect->controlHandle();
7979 if (handle != 0) {
7980 effect->setEnabled(handle->enabled());
7981 }
7982 }
7983 desc->mEffect.clear();
7984 }
7985 mSuspendedEffects.removeItemsAt(index);
7986 }
7987 }
7988}
7989
7990// must be called with ThreadBase::mLock held
7991void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7992{
7993 sp<SuspendedEffectDesc> desc;
7994
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007995 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07007996 if (suspend) {
7997 if (index >= 0) {
7998 desc = mSuspendedEffects.valueAt(index);
7999 } else {
8000 desc = new SuspendedEffectDesc();
8001 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01008002 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07008003 }
8004 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08008005 Vector< sp<EffectModule> > effects;
8006 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07008007 for (size_t i = 0; i < effects.size(); i++) {
8008 setEffectSuspended_l(&effects[i]->desc().type, true);
8009 }
8010 }
8011 } else {
8012 if (index < 0) {
8013 return;
8014 }
8015 desc = mSuspendedEffects.valueAt(index);
8016 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008017 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008018 desc->mRefCount = 1;
8019 }
8020 if (--desc->mRefCount == 0) {
8021 Vector<const effect_uuid_t *> types;
8022 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
8023 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
8024 continue;
8025 }
8026 types.add(&mSuspendedEffects.valueAt(i)->mType);
8027 }
8028 for (size_t i = 0; i < types.size(); i++) {
8029 setEffectSuspended_l(types[i], false);
8030 }
Steve Block3856b092011-10-20 11:56:00 +01008031 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008032 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
8033 }
8034 }
8035}
8036
Eric Laurent6bffdb82011-09-23 08:40:41 -07008037
8038// The volume effect is used for automated tests only
8039#ifndef OPENSL_ES_H_
8040static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
8041 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
8042const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
8043#endif //OPENSL_ES_H_
8044
Eric Laurentdb7c0792011-08-10 10:37:50 -07008045bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
8046{
8047 // auxiliary effects and visualizer are never suspended on output mix
8048 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8049 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07008050 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8051 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008052 return false;
8053 }
8054 return true;
8055}
8056
Glenn Kastend0539712012-01-30 12:56:03 -08008057void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07008058{
Glenn Kastend0539712012-01-30 12:56:03 -08008059 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07008060 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08008061 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8062 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07008063 }
Eric Laurent59255e42011-07-27 19:49:51 -07008064 }
Eric Laurent59255e42011-07-27 19:49:51 -07008065}
8066
8067sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8068 const effect_uuid_t *type)
8069{
Glenn Kasten090f0192012-01-30 13:00:02 -08008070 sp<EffectModule> effect = getEffectFromType_l(type);
8071 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008072}
8073
8074void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8075 bool enabled)
8076{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008077 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008078 if (enabled) {
8079 if (index < 0) {
8080 // if the effect is not suspend check if all effects are suspended
8081 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8082 if (index < 0) {
8083 return;
8084 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07008085 if (!isEffectEligibleForSuspend(effect->desc())) {
8086 return;
8087 }
Eric Laurent59255e42011-07-27 19:49:51 -07008088 setEffectSuspended_l(&effect->desc().type, enabled);
8089 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07008090 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008091 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07008092 return;
8093 }
Eric Laurent59255e42011-07-27 19:49:51 -07008094 }
Steve Block3856b092011-10-20 11:56:00 +01008095 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008096 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008097 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8098 // if effect is requested to suspended but was not yet enabled, supend it now.
8099 if (desc->mEffect == 0) {
8100 desc->mEffect = effect;
8101 effect->setEnabled(false);
8102 effect->setSuspended(true);
8103 }
8104 } else {
8105 if (index < 0) {
8106 return;
8107 }
Steve Block3856b092011-10-20 11:56:00 +01008108 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008109 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008110 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8111 desc->mEffect.clear();
8112 effect->setSuspended(false);
8113 }
8114}
8115
Mathias Agopian65ab4712010-07-14 17:59:35 -07008116#undef LOG_TAG
8117#define LOG_TAG "AudioFlinger"
8118
8119// ----------------------------------------------------------------------------
8120
8121status_t AudioFlinger::onTransact(
8122 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8123{
8124 return BnAudioFlinger::onTransact(code, data, reply, flags);
8125}
8126
Mathias Agopian65ab4712010-07-14 17:59:35 -07008127}; // namespace android