blob: ecc6147686288603568c063e7121455881c53ed4 [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
Glenn Kastend3cee2f2012-03-13 17:55:35 -070040#undef ADD_BATTERY_DATA
41
42#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080043#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080044#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070045#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070046
47#include <private/media/AudioTrackShared.h>
48#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070049
Dima Zavin64760242011-05-11 14:15:23 -070050#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070051#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
53#include "AudioMixer.h"
54#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080055#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Mathias Agopian65ab4712010-07-14 17:59:35 -070057#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070058#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070059#include <audio_effects/effect_ns.h>
60#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061
Glenn Kasten3b21c502011-12-15 09:52:39 -080062#include <audio_utils/primitives.h>
63
Eric Laurentfeb0db62011-07-22 09:04:31 -070064#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080065
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070066// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080067#ifdef DEBUG_CPU_USAGE
68#include <cpustats/CentralTendencyStatistics.h>
69#include <cpustats/ThreadCpuUsage.h>
70#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070071
John Grossman4ff14ba2012-02-08 16:37:41 -080072#include <common_time/cc_helper.h>
73#include <common_time/local_clock.h>
74
Mathias Agopian65ab4712010-07-14 17:59:35 -070075// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070076
Eric Laurentde070132010-07-13 04:45:46 -070077
Mathias Agopian65ab4712010-07-14 17:59:35 -070078namespace android {
79
Glenn Kastenec1d6b52011-12-12 09:04:45 -080080static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
81static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070082
Mathias Agopian65ab4712010-07-14 17:59:35 -070083static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -080084static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070085
86// retry counts for buffer fill timeout
87// 50 * ~20msecs = 1 second
88static const int8_t kMaxTrackRetries = 50;
89static const int8_t kMaxTrackStartupRetries = 50;
90// allow less retry attempts on direct output thread.
91// direct outputs can be a scarce resource in audio hardware and should
92// be released as quickly as possible.
93static const int8_t kMaxTrackRetriesDirect = 2;
94
95static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -080096static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070097
Glenn Kasten7dede872011-12-13 11:04:14 -080098// don't warn about blocked writes or record buffer overflows more often than this
99static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700100
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700101// RecordThread loop sleep time upon application overrun or audio HAL read error
102static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103
Glenn Kasten7dede872011-12-13 11:04:14 -0800104// maximum time to wait for setParameters to complete
105static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700106
Eric Laurent7cafbb32011-11-22 18:50:29 -0800107// minimum sleep time for the mixer thread loop when tracks are active but in underrun
108static const uint32_t kMinThreadSleepTimeUs = 5000;
109// maximum divider applied to the active sleep time in the mixer thread loop
110static const uint32_t kMaxThreadSleepTimeShift = 2;
111
John Grossman4ff14ba2012-02-08 16:37:41 -0800112nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800113
Mathias Agopian65ab4712010-07-14 17:59:35 -0700114// ----------------------------------------------------------------------------
115
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700116#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800117// To collect the amplifier usage
118static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800119 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
120 if (service == NULL) {
121 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800122 return;
123 }
124
125 service->addBatteryData(params);
126}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700127#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800128
Dima Zavin799a70e2011-04-18 16:57:27 -0700129static int load_audio_interface(const char *if_name, const hw_module_t **mod,
130 audio_hw_device_t **dev)
131{
132 int rc;
133
134 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
135 if (rc)
136 goto out;
137
138 rc = audio_hw_device_open(*mod, dev);
Steve Block29357bc2012-01-06 19:20:56 +0000139 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin799a70e2011-04-18 16:57:27 -0700140 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
141 if (rc)
142 goto out;
143
144 return 0;
145
146out:
147 *mod = NULL;
148 *dev = NULL;
149 return rc;
150}
151
Mathias Agopian65ab4712010-07-14 17:59:35 -0700152// ----------------------------------------------------------------------------
153
154AudioFlinger::AudioFlinger()
155 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800156 mPrimaryHardwareDev(NULL),
157 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
158 mMasterVolume(1.0f),
159 mMasterVolumeSupportLvl(MVS_NONE),
160 mMasterMute(false),
161 mNextUniqueId(1),
162 mMode(AUDIO_MODE_INVALID),
163 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700164{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700165}
166
167void AudioFlinger::onFirstRef()
168{
Dima Zavin799a70e2011-04-18 16:57:27 -0700169 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700170
Eric Laurent93575202011-01-18 18:39:02 -0800171 Mutex::Autolock _l(mLock);
172
Dima Zavin799a70e2011-04-18 16:57:27 -0700173 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800174 char val_str[PROPERTY_VALUE_MAX] = { 0 };
175 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
176 uint32_t int_val;
177 if (1 == sscanf(val_str, "%u", &int_val)) {
178 mStandbyTimeInNsecs = milliseconds(int_val);
179 ALOGI("Using %u mSec as standby time.", int_val);
180 } else {
181 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
182 ALOGI("Using default %u mSec as standby time.",
183 (uint32_t)(mStandbyTimeInNsecs / 1000000));
184 }
185 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700186
Eric Laurenta4c5a552012-03-29 10:12:40 -0700187 mMode = AUDIO_MODE_NORMAL;
188 mMasterVolumeSW = 1.0;
189 mMasterVolume = 1.0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800190 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700191}
192
193AudioFlinger::~AudioFlinger()
194{
Dima Zavin799a70e2011-04-18 16:57:27 -0700195
Mathias Agopian65ab4712010-07-14 17:59:35 -0700196 while (!mRecordThreads.isEmpty()) {
197 // closeInput() will remove first entry from mRecordThreads
198 closeInput(mRecordThreads.keyAt(0));
199 }
200 while (!mPlaybackThreads.isEmpty()) {
201 // closeOutput() will remove first entry from mPlaybackThreads
202 closeOutput(mPlaybackThreads.keyAt(0));
203 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700204
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800205 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
206 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700207 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
208 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700209 }
210}
211
Eric Laurenta4c5a552012-03-29 10:12:40 -0700212static const char * const audio_interfaces[] = {
213 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
214 AUDIO_HARDWARE_MODULE_ID_A2DP,
215 AUDIO_HARDWARE_MODULE_ID_USB,
216};
217#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
218
219audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(audio_module_handle_t module, uint32_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700220{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700221 // if module is 0, the request comes from an old policy manager and we should load
222 // well known modules
223 if (module == 0) {
224 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
225 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
226 loadHwModule_l(audio_interfaces[i]);
227 }
228 } else {
229 // check a match for the requested module handle
230 AudioHwDevice *audioHwdevice = mAudioHwDevs.valueFor(module);
231 if (audioHwdevice != NULL) {
232 return audioHwdevice->hwDevice();
233 }
234 }
235 // then try to find a module supporting the requested device.
Dima Zavin799a70e2011-04-18 16:57:27 -0700236 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700237 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700238 if ((dev->get_supported_devices(dev) & devices) == devices)
239 return dev;
240 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700241
Dima Zavin799a70e2011-04-18 16:57:27 -0700242 return NULL;
243}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700244
245status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
246{
247 const size_t SIZE = 256;
248 char buffer[SIZE];
249 String8 result;
250
251 result.append("Clients:\n");
252 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800253 sp<Client> client = mClients.valueAt(i).promote();
254 if (client != 0) {
255 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
256 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700257 }
258 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700259
260 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800261 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700262 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
263 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800264 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700265 result.append(buffer);
266 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700267 write(fd, result.string(), result.size());
268 return NO_ERROR;
269}
270
271
272status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
273{
274 const size_t SIZE = 256;
275 char buffer[SIZE];
276 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800277 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700278
John Grossman4ff14ba2012-02-08 16:37:41 -0800279 snprintf(buffer, SIZE, "Hardware status: %d\n"
280 "Standby Time mSec: %u\n",
281 hardwareStatus,
282 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700283 result.append(buffer);
284 write(fd, result.string(), result.size());
285 return NO_ERROR;
286}
287
288status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
289{
290 const size_t SIZE = 256;
291 char buffer[SIZE];
292 String8 result;
293 snprintf(buffer, SIZE, "Permission Denial: "
294 "can't dump AudioFlinger from pid=%d, uid=%d\n",
295 IPCThreadState::self()->getCallingPid(),
296 IPCThreadState::self()->getCallingUid());
297 result.append(buffer);
298 write(fd, result.string(), result.size());
299 return NO_ERROR;
300}
301
302static bool tryLock(Mutex& mutex)
303{
304 bool locked = false;
305 for (int i = 0; i < kDumpLockRetries; ++i) {
306 if (mutex.tryLock() == NO_ERROR) {
307 locked = true;
308 break;
309 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800310 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700311 }
312 return locked;
313}
314
315status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
316{
Glenn Kasten44deb052012-02-05 18:09:08 -0800317 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700318 dumpPermissionDenial(fd, args);
319 } else {
320 // get state of hardware lock
321 bool hardwareLocked = tryLock(mHardwareLock);
322 if (!hardwareLocked) {
323 String8 result(kHardwareLockedString);
324 write(fd, result.string(), result.size());
325 } else {
326 mHardwareLock.unlock();
327 }
328
329 bool locked = tryLock(mLock);
330
331 // failed to lock - AudioFlinger is probably deadlocked
332 if (!locked) {
333 String8 result(kDeadlockedString);
334 write(fd, result.string(), result.size());
335 }
336
337 dumpClients(fd, args);
338 dumpInternals(fd, args);
339
340 // dump playback threads
341 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
342 mPlaybackThreads.valueAt(i)->dump(fd, args);
343 }
344
345 // dump record threads
346 for (size_t i = 0; i < mRecordThreads.size(); i++) {
347 mRecordThreads.valueAt(i)->dump(fd, args);
348 }
349
Dima Zavin799a70e2011-04-18 16:57:27 -0700350 // dump all hardware devs
351 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700352 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700353 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700354 }
355 if (locked) mLock.unlock();
356 }
357 return NO_ERROR;
358}
359
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800360sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
361{
362 // If pid is already in the mClients wp<> map, then use that entry
363 // (for which promote() is always != 0), otherwise create a new entry and Client.
364 sp<Client> client = mClients.valueFor(pid).promote();
365 if (client == 0) {
366 client = new Client(this, pid);
367 mClients.add(pid, client);
368 }
369
370 return client;
371}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700372
373// IAudioFlinger interface
374
375
376sp<IAudioTrack> AudioFlinger::createTrack(
377 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800378 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700379 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800380 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700381 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700382 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800383 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700384 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800385 audio_io_handle_t output,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700386 int *sessionId,
387 status_t *status)
388{
389 sp<PlaybackThread::Track> track;
390 sp<TrackHandle> trackHandle;
391 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700392 status_t lStatus;
393 int lSessionId;
394
Glenn Kasten263709e2012-01-06 08:40:01 -0800395 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
396 // but if someone uses binder directly they could bypass that and cause us to crash
397 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000398 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700399 lStatus = BAD_VALUE;
400 goto Exit;
401 }
402
403 {
404 Mutex::Autolock _l(mLock);
405 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700406 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700407 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000408 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700409 lStatus = BAD_VALUE;
410 goto Exit;
411 }
412
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800413 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700414
Steve Block3856b092011-10-20 11:56:00 +0100415 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700416 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700417 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700418 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
419 if (mPlaybackThreads.keyAt(i) != output) {
420 // prevent same audio session on different output threads
421 uint32_t sessions = t->hasAudioSession(*sessionId);
422 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000423 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700424 lStatus = BAD_VALUE;
425 goto Exit;
426 }
427 // check if an effect with same session ID is waiting for a track to be created
428 if (sessions & PlaybackThread::EFFECT_SESSION) {
429 effectThread = t.get();
430 }
Eric Laurentde070132010-07-13 04:45:46 -0700431 }
432 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700433 lSessionId = *sessionId;
434 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700435 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700436 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700437 if (sessionId != NULL) {
438 *sessionId = lSessionId;
439 }
440 }
Steve Block3856b092011-10-20 11:56:00 +0100441 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700442
Glenn Kastena075db42012-03-06 11:22:44 -0800443 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -0700445 channelMask, frameCount, sharedBuffer, lSessionId, flags, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700446
447 // move effect chain to this output thread if an effect on same session was waiting
448 // for a track to be created
449 if (lStatus == NO_ERROR && effectThread != NULL) {
450 Mutex::Autolock _dl(thread->mLock);
451 Mutex::Autolock _sl(effectThread->mLock);
452 moveEffectChain_l(lSessionId, effectThread, thread, true);
453 }
Eric Laurenta011e352012-03-29 15:51:43 -0700454
455 // Look for sync events awaiting for a session to be used.
456 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
457 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
458 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
459 track->setSyncEvent(mPendingSyncEvents[i]);
460 mPendingSyncEvents.removeAt(i);
461 i--;
462 }
463 }
464 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700465 }
466 if (lStatus == NO_ERROR) {
467 trackHandle = new TrackHandle(track);
468 } else {
469 // remove local strong reference to Client before deleting the Track so that the Client
470 // destructor is called by the TrackBase destructor with mLock held
471 client.clear();
472 track.clear();
473 }
474
475Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700476 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700477 *status = lStatus;
478 }
479 return trackHandle;
480}
481
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800482uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700483{
484 Mutex::Autolock _l(mLock);
485 PlaybackThread *thread = checkPlaybackThread_l(output);
486 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000487 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700488 return 0;
489 }
490 return thread->sampleRate();
491}
492
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800493int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700494{
495 Mutex::Autolock _l(mLock);
496 PlaybackThread *thread = checkPlaybackThread_l(output);
497 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000498 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700499 return 0;
500 }
501 return thread->channelCount();
502}
503
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800504audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700505{
506 Mutex::Autolock _l(mLock);
507 PlaybackThread *thread = checkPlaybackThread_l(output);
508 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000509 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800510 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700511 }
512 return thread->format();
513}
514
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800515size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700516{
517 Mutex::Autolock _l(mLock);
518 PlaybackThread *thread = checkPlaybackThread_l(output);
519 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000520 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700521 return 0;
522 }
523 return thread->frameCount();
524}
525
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800526uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700527{
528 Mutex::Autolock _l(mLock);
529 PlaybackThread *thread = checkPlaybackThread_l(output);
530 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000531 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700532 return 0;
533 }
534 return thread->latency();
535}
536
537status_t AudioFlinger::setMasterVolume(float value)
538{
Eric Laurenta1884f92011-08-23 08:25:03 -0700539 status_t ret = initCheck();
540 if (ret != NO_ERROR) {
541 return ret;
542 }
543
Mathias Agopian65ab4712010-07-14 17:59:35 -0700544 // check calling permissions
545 if (!settingsAllowed()) {
546 return PERMISSION_DENIED;
547 }
548
John Grossman4ff14ba2012-02-08 16:37:41 -0800549 float swmv = value;
550
Eric Laurenta4c5a552012-03-29 10:12:40 -0700551 Mutex::Autolock _l(mLock);
552
Mathias Agopian65ab4712010-07-14 17:59:35 -0700553 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800554 if (MVS_NONE != mMasterVolumeSupportLvl) {
555 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
556 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700557 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
John Grossman4ff14ba2012-02-08 16:37:41 -0800558
559 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
560 if (NULL != dev->set_master_volume) {
561 dev->set_master_volume(dev, value);
562 }
563 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800564 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800565
566 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700567 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700568
John Grossman4ff14ba2012-02-08 16:37:41 -0800569 mMasterVolume = value;
570 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800571 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700572 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700573
574 return NO_ERROR;
575}
576
Glenn Kastenf78aee72012-01-04 11:00:47 -0800577status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700578{
Eric Laurenta1884f92011-08-23 08:25:03 -0700579 status_t ret = initCheck();
580 if (ret != NO_ERROR) {
581 return ret;
582 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700583
584 // check calling permissions
585 if (!settingsAllowed()) {
586 return PERMISSION_DENIED;
587 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800588 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000589 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700590 return BAD_VALUE;
591 }
592
593 { // scope for the lock
594 AutoMutex lock(mHardwareLock);
595 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700596 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700597 mHardwareStatus = AUDIO_HW_IDLE;
598 }
599
600 if (NO_ERROR == ret) {
601 Mutex::Autolock _l(mLock);
602 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800603 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700604 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700605 }
606
607 return ret;
608}
609
610status_t AudioFlinger::setMicMute(bool state)
611{
Eric Laurenta1884f92011-08-23 08:25:03 -0700612 status_t ret = initCheck();
613 if (ret != NO_ERROR) {
614 return ret;
615 }
616
Mathias Agopian65ab4712010-07-14 17:59:35 -0700617 // check calling permissions
618 if (!settingsAllowed()) {
619 return PERMISSION_DENIED;
620 }
621
622 AutoMutex lock(mHardwareLock);
623 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700624 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700625 mHardwareStatus = AUDIO_HW_IDLE;
626 return ret;
627}
628
629bool AudioFlinger::getMicMute() const
630{
Eric Laurenta1884f92011-08-23 08:25:03 -0700631 status_t ret = initCheck();
632 if (ret != NO_ERROR) {
633 return false;
634 }
635
Dima Zavinfce7a472011-04-19 22:30:36 -0700636 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800637 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700638 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700639 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700640 mHardwareStatus = AUDIO_HW_IDLE;
641 return state;
642}
643
644status_t AudioFlinger::setMasterMute(bool muted)
645{
646 // check calling permissions
647 if (!settingsAllowed()) {
648 return PERMISSION_DENIED;
649 }
650
Eric Laurent93575202011-01-18 18:39:02 -0800651 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800652 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700653 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800654 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700655 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700656
657 return NO_ERROR;
658}
659
660float AudioFlinger::masterVolume() const
661{
Glenn Kasten98067102011-12-13 11:47:54 -0800662 Mutex::Autolock _l(mLock);
663 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700664}
665
John Grossman4ff14ba2012-02-08 16:37:41 -0800666float AudioFlinger::masterVolumeSW() const
667{
668 Mutex::Autolock _l(mLock);
669 return masterVolumeSW_l();
670}
671
Mathias Agopian65ab4712010-07-14 17:59:35 -0700672bool AudioFlinger::masterMute() const
673{
Glenn Kasten98067102011-12-13 11:47:54 -0800674 Mutex::Autolock _l(mLock);
675 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700676}
677
John Grossman4ff14ba2012-02-08 16:37:41 -0800678float AudioFlinger::masterVolume_l() const
679{
680 if (MVS_FULL == mMasterVolumeSupportLvl) {
681 float ret_val;
682 AutoMutex lock(mHardwareLock);
683
684 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800685 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
686 (NULL != mPrimaryHardwareDev->get_master_volume),
687 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800688
689 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
690 mHardwareStatus = AUDIO_HW_IDLE;
691 return ret_val;
692 }
693
694 return mMasterVolume;
695}
696
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800697status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
698 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700699{
700 // check calling permissions
701 if (!settingsAllowed()) {
702 return PERMISSION_DENIED;
703 }
704
Glenn Kasten263709e2012-01-06 08:40:01 -0800705 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000706 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700707 return BAD_VALUE;
708 }
709
710 AutoMutex lock(mLock);
711 PlaybackThread *thread = NULL;
712 if (output) {
713 thread = checkPlaybackThread_l(output);
714 if (thread == NULL) {
715 return BAD_VALUE;
716 }
717 }
718
719 mStreamTypes[stream].volume = value;
720
721 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800722 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700723 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700724 }
725 } else {
726 thread->setStreamVolume(stream, value);
727 }
728
729 return NO_ERROR;
730}
731
Glenn Kastenfff6d712012-01-12 16:38:12 -0800732status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700733{
734 // check calling permissions
735 if (!settingsAllowed()) {
736 return PERMISSION_DENIED;
737 }
738
Glenn Kasten263709e2012-01-06 08:40:01 -0800739 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700740 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000741 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700742 return BAD_VALUE;
743 }
744
Eric Laurent93575202011-01-18 18:39:02 -0800745 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700746 mStreamTypes[stream].mute = muted;
747 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700748 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700749
750 return NO_ERROR;
751}
752
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800753float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700754{
Glenn Kasten263709e2012-01-06 08:40:01 -0800755 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700756 return 0.0f;
757 }
758
759 AutoMutex lock(mLock);
760 float volume;
761 if (output) {
762 PlaybackThread *thread = checkPlaybackThread_l(output);
763 if (thread == NULL) {
764 return 0.0f;
765 }
766 volume = thread->streamVolume(stream);
767 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800768 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700769 }
770
771 return volume;
772}
773
Glenn Kastenfff6d712012-01-12 16:38:12 -0800774bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700775{
Glenn Kasten263709e2012-01-06 08:40:01 -0800776 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700777 return true;
778 }
779
Glenn Kasten6637baa2012-01-09 09:40:36 -0800780 AutoMutex lock(mLock);
781 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700782}
783
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800784status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700785{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800786 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700787 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
788 // check calling permissions
789 if (!settingsAllowed()) {
790 return PERMISSION_DENIED;
791 }
792
Mathias Agopian65ab4712010-07-14 17:59:35 -0700793 // ioHandle == 0 means the parameters are global to the audio hardware interface
794 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700795 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700796 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800797 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700798 AutoMutex lock(mHardwareLock);
799 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
800 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
801 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
802 status_t result = dev->set_parameters(dev, keyValuePairs.string());
803 final_result = result ?: final_result;
804 }
805 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800806 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700807 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
808 AudioParameter param = AudioParameter(keyValuePairs);
809 String8 value;
810 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700811 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
812 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700813 for (size_t i = 0; i < mRecordThreads.size(); i++) {
814 sp<RecordThread> thread = mRecordThreads.valueAt(i);
815 RecordThread::RecordTrack *track = thread->track();
816 if (track != NULL) {
817 audio_devices_t device = (audio_devices_t)(
818 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700819 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700820 thread->setEffectSuspended(FX_IID_AEC,
821 suspend,
822 track->sessionId());
823 thread->setEffectSuspended(FX_IID_NS,
824 suspend,
825 track->sessionId());
826 }
827 }
Eric Laurentbee53372011-08-29 12:42:48 -0700828 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700829 }
830 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700831 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700832 }
833
834 // hold a strong ref on thread in case closeOutput() or closeInput() is called
835 // and the thread is exited once the lock is released
836 sp<ThreadBase> thread;
837 {
838 Mutex::Autolock _l(mLock);
839 thread = checkPlaybackThread_l(ioHandle);
840 if (thread == NULL) {
841 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800842 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700843 // indicate output device change to all input threads for pre processing
844 AudioParameter param = AudioParameter(keyValuePairs);
845 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700846 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
847 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700848 for (size_t i = 0; i < mRecordThreads.size(); i++) {
849 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
850 }
851 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700852 }
853 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800854 if (thread != 0) {
855 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700856 }
857 return BAD_VALUE;
858}
859
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800860String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700861{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800862// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700863// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
864
Eric Laurenta4c5a552012-03-29 10:12:40 -0700865 Mutex::Autolock _l(mLock);
866
Mathias Agopian65ab4712010-07-14 17:59:35 -0700867 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700868 String8 out_s8;
869
Dima Zavin799a70e2011-04-18 16:57:27 -0700870 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800871 char *s;
872 {
873 AutoMutex lock(mHardwareLock);
874 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700875 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800876 s = dev->get_parameters(dev, keys.string());
877 mHardwareStatus = AUDIO_HW_IDLE;
878 }
John Grossmanef7740b2012-02-09 11:28:36 -0800879 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700880 free(s);
881 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700882 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700883 }
884
Mathias Agopian65ab4712010-07-14 17:59:35 -0700885 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
886 if (playbackThread != NULL) {
887 return playbackThread->getParameters(keys);
888 }
889 RecordThread *recordThread = checkRecordThread_l(ioHandle);
890 if (recordThread != NULL) {
891 return recordThread->getParameters(keys);
892 }
893 return String8("");
894}
895
Glenn Kastenf587ba52012-01-26 16:25:10 -0800896size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700897{
Eric Laurenta1884f92011-08-23 08:25:03 -0700898 status_t ret = initCheck();
899 if (ret != NO_ERROR) {
900 return 0;
901 }
902
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800903 AutoMutex lock(mHardwareLock);
904 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
905 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
906 mHardwareStatus = AUDIO_HW_IDLE;
907 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700908}
909
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800910unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700911{
912 if (ioHandle == 0) {
913 return 0;
914 }
915
916 Mutex::Autolock _l(mLock);
917
918 RecordThread *recordThread = checkRecordThread_l(ioHandle);
919 if (recordThread != NULL) {
920 return recordThread->getInputFramesLost();
921 }
922 return 0;
923}
924
925status_t AudioFlinger::setVoiceVolume(float value)
926{
Eric Laurenta1884f92011-08-23 08:25:03 -0700927 status_t ret = initCheck();
928 if (ret != NO_ERROR) {
929 return ret;
930 }
931
Mathias Agopian65ab4712010-07-14 17:59:35 -0700932 // check calling permissions
933 if (!settingsAllowed()) {
934 return PERMISSION_DENIED;
935 }
936
937 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800938 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700939 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700940 mHardwareStatus = AUDIO_HW_IDLE;
941
942 return ret;
943}
944
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800945status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
946 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700947{
948 status_t status;
949
950 Mutex::Autolock _l(mLock);
951
952 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
953 if (playbackThread != NULL) {
954 return playbackThread->getRenderPosition(halFrames, dspFrames);
955 }
956
957 return BAD_VALUE;
958}
959
960void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
961{
962
963 Mutex::Autolock _l(mLock);
964
Glenn Kastenbb001922012-02-03 11:10:26 -0800965 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700966 if (mNotificationClients.indexOfKey(pid) < 0) {
967 sp<NotificationClient> notificationClient = new NotificationClient(this,
968 client,
969 pid);
Steve Block3856b092011-10-20 11:56:00 +0100970 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700971
972 mNotificationClients.add(pid, notificationClient);
973
974 sp<IBinder> binder = client->asBinder();
975 binder->linkToDeath(notificationClient);
976
977 // the config change is always sent from playback or record threads to avoid deadlock
978 // with AudioSystem::gLock
979 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
980 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
981 }
982
983 for (size_t i = 0; i < mRecordThreads.size(); i++) {
984 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
985 }
986 }
987}
988
989void AudioFlinger::removeNotificationClient(pid_t pid)
990{
991 Mutex::Autolock _l(mLock);
992
Glenn Kastena3b09252012-01-20 09:19:01 -0800993 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700994
Steve Block3856b092011-10-20 11:56:00 +0100995 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800996 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700997 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800998 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700999 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001000 ALOGV(" pid %d @ %d", ref->mPid, i);
1001 if (ref->mPid == pid) {
1002 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001003 mAudioSessionRefs.removeAt(i);
1004 delete ref;
1005 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001006 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001007 } else {
1008 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001009 }
1010 }
1011 if (removed) {
1012 purgeStaleEffects_l();
1013 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001014}
1015
1016// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001017void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001018{
1019 size_t size = mNotificationClients.size();
1020 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001021 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1022 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001023 }
1024}
1025
1026// removeClient_l() must be called with AudioFlinger::mLock held
1027void AudioFlinger::removeClient_l(pid_t pid)
1028{
Steve Block3856b092011-10-20 11:56:00 +01001029 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001030 mClients.removeItem(pid);
1031}
1032
1033
1034// ----------------------------------------------------------------------------
1035
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001036AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1037 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001038 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001039 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001040 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
1041 // mChannelMask
1042 mChannelCount(0),
1043 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1044 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001045 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001046 mDevice(device),
1047 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001048{
1049}
1050
1051AudioFlinger::ThreadBase::~ThreadBase()
1052{
1053 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001054 // do not lock the mutex in destructor
1055 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001056 if (mPowerManager != 0) {
1057 sp<IBinder> binder = mPowerManager->asBinder();
1058 binder->unlinkToDeath(mDeathRecipient);
1059 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001060}
1061
1062void AudioFlinger::ThreadBase::exit()
1063{
Steve Block3856b092011-10-20 11:56:00 +01001064 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001065 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001066 // This lock prevents the following race in thread (uniprocessor for illustration):
1067 // if (!exitPending()) {
1068 // // context switch from here to exit()
1069 // // exit() calls requestExit(), what exitPending() observes
1070 // // exit() calls signal(), which is dropped since no waiters
1071 // // context switch back from exit() to here
1072 // mWaitWorkCV.wait(...);
1073 // // now thread is hung
1074 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001075 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001076 requestExit();
1077 mWaitWorkCV.signal();
1078 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001079 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1080 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001081 requestExitAndWait();
1082}
1083
Mathias Agopian65ab4712010-07-14 17:59:35 -07001084status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1085{
1086 status_t status;
1087
Steve Block3856b092011-10-20 11:56:00 +01001088 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001089 Mutex::Autolock _l(mLock);
1090
1091 mNewParameters.add(keyValuePairs);
1092 mWaitWorkCV.signal();
1093 // wait condition with timeout in case the thread loop has exited
1094 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001095 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001096 status = mParamStatus;
1097 mWaitWorkCV.signal();
1098 } else {
1099 status = TIMED_OUT;
1100 }
1101 return status;
1102}
1103
1104void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1105{
1106 Mutex::Autolock _l(mLock);
1107 sendConfigEvent_l(event, param);
1108}
1109
1110// sendConfigEvent_l() must be called with ThreadBase::mLock held
1111void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1112{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001113 ConfigEvent configEvent;
1114 configEvent.mEvent = event;
1115 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001116 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001117 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001118 mWaitWorkCV.signal();
1119}
1120
1121void AudioFlinger::ThreadBase::processConfigEvents()
1122{
1123 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001124 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001125 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001126 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001127 mConfigEvents.removeAt(0);
1128 // release mLock before locking AudioFlinger mLock: lock order is always
1129 // AudioFlinger then ThreadBase to avoid cross deadlock
1130 mLock.unlock();
1131 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001132 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001133 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001134 mLock.lock();
1135 }
1136 mLock.unlock();
1137}
1138
1139status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1140{
1141 const size_t SIZE = 256;
1142 char buffer[SIZE];
1143 String8 result;
1144
1145 bool locked = tryLock(mLock);
1146 if (!locked) {
1147 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1148 write(fd, buffer, strlen(buffer));
1149 }
1150
Eric Laurent612bbb52012-03-14 15:03:26 -07001151 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1152 result.append(buffer);
1153 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1154 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001155 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1156 result.append(buffer);
1157 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1158 result.append(buffer);
1159 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1160 result.append(buffer);
1161 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1162 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001163 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1164 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001165 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1166 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001167 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001168 result.append(buffer);
1169
1170 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1171 result.append(buffer);
1172 result.append(" Index Command");
1173 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1174 snprintf(buffer, SIZE, "\n %02d ", i);
1175 result.append(buffer);
1176 result.append(mNewParameters[i]);
1177 }
1178
1179 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1180 result.append(buffer);
1181 snprintf(buffer, SIZE, " Index event param\n");
1182 result.append(buffer);
1183 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001184 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001185 result.append(buffer);
1186 }
1187 result.append("\n");
1188
1189 write(fd, result.string(), result.size());
1190
1191 if (locked) {
1192 mLock.unlock();
1193 }
1194 return NO_ERROR;
1195}
1196
Eric Laurent1d2bff02011-07-24 17:49:51 -07001197status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1198{
1199 const size_t SIZE = 256;
1200 char buffer[SIZE];
1201 String8 result;
1202
1203 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1204 write(fd, buffer, strlen(buffer));
1205
1206 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1207 sp<EffectChain> chain = mEffectChains[i];
1208 if (chain != 0) {
1209 chain->dump(fd, args);
1210 }
1211 }
1212 return NO_ERROR;
1213}
1214
Eric Laurentfeb0db62011-07-22 09:04:31 -07001215void AudioFlinger::ThreadBase::acquireWakeLock()
1216{
1217 Mutex::Autolock _l(mLock);
1218 acquireWakeLock_l();
1219}
1220
1221void AudioFlinger::ThreadBase::acquireWakeLock_l()
1222{
1223 if (mPowerManager == 0) {
1224 // use checkService() to avoid blocking if power service is not up yet
1225 sp<IBinder> binder =
1226 defaultServiceManager()->checkService(String16("power"));
1227 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001228 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001229 } else {
1230 mPowerManager = interface_cast<IPowerManager>(binder);
1231 binder->linkToDeath(mDeathRecipient);
1232 }
1233 }
1234 if (mPowerManager != 0) {
1235 sp<IBinder> binder = new BBinder();
1236 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1237 binder,
1238 String16(mName));
1239 if (status == NO_ERROR) {
1240 mWakeLockToken = binder;
1241 }
Steve Block3856b092011-10-20 11:56:00 +01001242 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001243 }
1244}
1245
1246void AudioFlinger::ThreadBase::releaseWakeLock()
1247{
1248 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001249 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001250}
1251
1252void AudioFlinger::ThreadBase::releaseWakeLock_l()
1253{
1254 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001255 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001256 if (mPowerManager != 0) {
1257 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1258 }
1259 mWakeLockToken.clear();
1260 }
1261}
1262
1263void AudioFlinger::ThreadBase::clearPowerManager()
1264{
1265 Mutex::Autolock _l(mLock);
1266 releaseWakeLock_l();
1267 mPowerManager.clear();
1268}
1269
1270void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1271{
1272 sp<ThreadBase> thread = mThread.promote();
1273 if (thread != 0) {
1274 thread->clearPowerManager();
1275 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001276 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001277}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001278
Eric Laurent59255e42011-07-27 19:49:51 -07001279void AudioFlinger::ThreadBase::setEffectSuspended(
1280 const effect_uuid_t *type, bool suspend, int sessionId)
1281{
1282 Mutex::Autolock _l(mLock);
1283 setEffectSuspended_l(type, suspend, sessionId);
1284}
1285
1286void AudioFlinger::ThreadBase::setEffectSuspended_l(
1287 const effect_uuid_t *type, bool suspend, int sessionId)
1288{
Glenn Kasten090f0192012-01-30 13:00:02 -08001289 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001290 if (chain != 0) {
1291 if (type != NULL) {
1292 chain->setEffectSuspended_l(type, suspend);
1293 } else {
1294 chain->setEffectSuspendedAll_l(suspend);
1295 }
1296 }
1297
1298 updateSuspendedSessions_l(type, suspend, sessionId);
1299}
1300
1301void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1302{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001303 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001304 if (index < 0) {
1305 return;
1306 }
1307
1308 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1309 mSuspendedSessions.editValueAt(index);
1310
1311 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001312 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001313 for (int j = 0; j < desc->mRefCount; j++) {
1314 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1315 chain->setEffectSuspendedAll_l(true);
1316 } else {
Steve Block3856b092011-10-20 11:56:00 +01001317 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001318 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001319 chain->setEffectSuspended_l(&desc->mType, true);
1320 }
1321 }
1322 }
1323}
1324
Eric Laurent59255e42011-07-27 19:49:51 -07001325void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1326 bool suspend,
1327 int sessionId)
1328{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001329 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001330
1331 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1332
1333 if (suspend) {
1334 if (index >= 0) {
1335 sessionEffects = mSuspendedSessions.editValueAt(index);
1336 } else {
1337 mSuspendedSessions.add(sessionId, sessionEffects);
1338 }
1339 } else {
1340 if (index < 0) {
1341 return;
1342 }
1343 sessionEffects = mSuspendedSessions.editValueAt(index);
1344 }
1345
1346
1347 int key = EffectChain::kKeyForSuspendAll;
1348 if (type != NULL) {
1349 key = type->timeLow;
1350 }
1351 index = sessionEffects.indexOfKey(key);
1352
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001353 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001354 if (suspend) {
1355 if (index >= 0) {
1356 desc = sessionEffects.valueAt(index);
1357 } else {
1358 desc = new SuspendedSessionDesc();
1359 if (type != NULL) {
1360 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1361 }
1362 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001363 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001364 }
1365 desc->mRefCount++;
1366 } else {
1367 if (index < 0) {
1368 return;
1369 }
1370 desc = sessionEffects.valueAt(index);
1371 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001372 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001373 sessionEffects.removeItemsAt(index);
1374 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001375 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001376 sessionId);
1377 mSuspendedSessions.removeItem(sessionId);
1378 }
1379 }
1380 }
1381 if (!sessionEffects.isEmpty()) {
1382 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1383 }
1384}
1385
1386void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1387 bool enabled,
1388 int sessionId)
1389{
1390 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001391 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1392}
Eric Laurent59255e42011-07-27 19:49:51 -07001393
Eric Laurenta85a74a2011-10-19 11:44:54 -07001394void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1395 bool enabled,
1396 int sessionId)
1397{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001398 if (mType != RECORD) {
1399 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1400 // another session. This gives the priority to well behaved effect control panels
1401 // and applications not using global effects.
1402 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1403 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1404 }
1405 }
Eric Laurent59255e42011-07-27 19:49:51 -07001406
1407 sp<EffectChain> chain = getEffectChain_l(sessionId);
1408 if (chain != 0) {
1409 chain->checkSuspendOnEffectEnabled(effect, enabled);
1410 }
1411}
1412
Mathias Agopian65ab4712010-07-14 17:59:35 -07001413// ----------------------------------------------------------------------------
1414
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001415AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1416 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001417 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001418 uint32_t device,
1419 type_t type)
1420 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001421 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1422 // Assumes constructor is called by AudioFlinger with it's mLock held,
1423 // but it would be safer to explicitly pass initial masterMute as parameter
1424 mMasterMute(audioFlinger->masterMute_l()),
1425 // mStreamTypes[] initialized in constructor body
1426 mOutput(output),
1427 // Assumes constructor is called by AudioFlinger with it's mLock held,
1428 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001429 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001430 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001431 mMixerStatus(MIXER_IDLE),
Glenn Kasten66fcab92012-02-24 14:59:21 -08001432 mPrevMixerStatus(MIXER_IDLE),
1433 standbyDelay(AudioFlinger::mStandbyTimeInNsecs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001434{
Glenn Kasten480b4682012-02-28 12:30:08 -08001435 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001436
Mathias Agopian65ab4712010-07-14 17:59:35 -07001437 readOutputParameters();
1438
Glenn Kasten263709e2012-01-06 08:40:01 -08001439 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001440 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1441 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1442 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001443 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1444 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001445 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001446 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1447 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001448}
1449
1450AudioFlinger::PlaybackThread::~PlaybackThread()
1451{
1452 delete [] mMixBuffer;
1453}
1454
1455status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1456{
1457 dumpInternals(fd, args);
1458 dumpTracks(fd, args);
1459 dumpEffectChains(fd, args);
1460 return NO_ERROR;
1461}
1462
1463status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1464{
1465 const size_t SIZE = 256;
1466 char buffer[SIZE];
1467 String8 result;
1468
1469 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1470 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001471 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 -07001472 for (size_t i = 0; i < mTracks.size(); ++i) {
1473 sp<Track> track = mTracks[i];
1474 if (track != 0) {
1475 track->dump(buffer, SIZE);
1476 result.append(buffer);
1477 }
1478 }
1479
1480 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1481 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001482 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 -07001483 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001484 sp<Track> track = mActiveTracks[i].promote();
1485 if (track != 0) {
1486 track->dump(buffer, SIZE);
1487 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001488 }
1489 }
1490 write(fd, result.string(), result.size());
1491 return NO_ERROR;
1492}
1493
Mathias Agopian65ab4712010-07-14 17:59:35 -07001494status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1495{
1496 const size_t SIZE = 256;
1497 char buffer[SIZE];
1498 String8 result;
1499
1500 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1501 result.append(buffer);
1502 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1503 result.append(buffer);
1504 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1505 result.append(buffer);
1506 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1507 result.append(buffer);
1508 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1509 result.append(buffer);
1510 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1511 result.append(buffer);
1512 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1513 result.append(buffer);
1514 write(fd, result.string(), result.size());
1515
1516 dumpBase(fd, args);
1517
1518 return NO_ERROR;
1519}
1520
1521// Thread virtuals
1522status_t AudioFlinger::PlaybackThread::readyToRun()
1523{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001524 status_t status = initCheck();
1525 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001526 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001527 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001528 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001529 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001530 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001531}
1532
1533void AudioFlinger::PlaybackThread::onFirstRef()
1534{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001535 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001536}
1537
1538// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001539sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001540 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001541 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001542 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001543 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001544 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001545 int frameCount,
1546 const sp<IMemory>& sharedBuffer,
1547 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001548 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001549 status_t *status)
1550{
1551 sp<Track> track;
1552 status_t lStatus;
1553
Glenn Kasten73d22752012-03-19 13:38:30 -07001554 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1555
1556 // client expresses a preference for FAST, but we get the final say
1557 if ((flags & IAudioFlinger::TRACK_FAST) &&
1558 !(
1559 // not timed
1560 (!isTimed) &&
1561 // either of these use cases:
1562 (
1563 // use case 1: shared buffer with any frame count
1564 (
1565 (sharedBuffer != 0)
1566 ) ||
1567 // use case 2: callback handler and small power-of-2 frame count
1568 (
1569 // unfortunately we can't verify that there's a callback until start()
1570 // FIXME supported frame counts should not be hard-coded
1571 (
1572 (frameCount == 128) ||
1573 (frameCount == 256) ||
1574 (frameCount == 512)
1575 )
1576 )
1577 ) &&
1578 // PCM data
1579 audio_is_linear_pcm(format) &&
1580 // mono or stereo
1581 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1582 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1583 // hardware sample rate
1584 (sampleRate == mSampleRate)
1585 // FIXME test that MixerThread for this fast track has a capable output HAL
1586 // FIXME add a permission test also?
1587 ) ) {
1588 ALOGW("AUDIO_POLICY_OUTPUT_FLAG_FAST denied");
1589 flags &= ~IAudioFlinger::TRACK_FAST;
1590 }
1591
Mathias Agopian65ab4712010-07-14 17:59:35 -07001592 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001593 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1594 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001595 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001596 "for output %p with format %d",
1597 sampleRate, format, channelMask, mOutput, mFormat);
1598 lStatus = BAD_VALUE;
1599 goto Exit;
1600 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001601 }
1602 } else {
1603 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1604 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001605 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001606 lStatus = BAD_VALUE;
1607 goto Exit;
1608 }
1609 }
1610
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001611 lStatus = initCheck();
1612 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001613 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001614 goto Exit;
1615 }
1616
1617 { // scope for mLock
1618 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001619
1620 // all tracks in same audio session must share the same routing strategy otherwise
1621 // conflicts will happen when tracks are moved from one output to another by audio policy
1622 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001623 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001624 for (size_t i = 0; i < mTracks.size(); ++i) {
1625 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001626 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001627 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001628 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001629 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001630 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001631 lStatus = BAD_VALUE;
1632 goto Exit;
1633 }
1634 }
1635 }
1636
John Grossman4ff14ba2012-02-08 16:37:41 -08001637 if (!isTimed) {
1638 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001639 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001640 } else {
1641 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1642 channelMask, frameCount, sharedBuffer, sessionId);
1643 }
1644 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001645 lStatus = NO_MEMORY;
1646 goto Exit;
1647 }
1648 mTracks.add(track);
1649
1650 sp<EffectChain> chain = getEffectChain_l(sessionId);
1651 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001652 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001653 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001654 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001655 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001656 }
1657 }
1658 lStatus = NO_ERROR;
1659
1660Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001661 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001662 *status = lStatus;
1663 }
1664 return track;
1665}
1666
1667uint32_t AudioFlinger::PlaybackThread::latency() const
1668{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001669 Mutex::Autolock _l(mLock);
1670 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001671 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001672 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001673 return 0;
1674 }
1675}
1676
Glenn Kasten6637baa2012-01-09 09:40:36 -08001677void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001678{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001679 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001680 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001681}
1682
Glenn Kasten6637baa2012-01-09 09:40:36 -08001683void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001684{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001685 Mutex::Autolock _l(mLock);
1686 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001687}
1688
Glenn Kasten6637baa2012-01-09 09:40:36 -08001689void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, 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 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001693}
1694
Glenn Kasten6637baa2012-01-09 09:40:36 -08001695void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001696{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001697 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001698 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001699}
1700
Glenn Kastenfff6d712012-01-12 16:38:12 -08001701float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
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 return mStreamTypes[stream].volume;
1705}
1706
Mathias Agopian65ab4712010-07-14 17:59:35 -07001707// addTrack_l() must be called with ThreadBase::mLock held
1708status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1709{
1710 status_t status = ALREADY_EXISTS;
1711
1712 // set retry count for buffer fill
1713 track->mRetryCount = kMaxTrackStartupRetries;
1714 if (mActiveTracks.indexOf(track) < 0) {
1715 // the track is newly added, make sure it fills up all its
1716 // buffers before playing. This is to ensure the client will
1717 // effectively get the latency it requested.
1718 track->mFillingUpStatus = Track::FS_FILLING;
1719 track->mResetDone = false;
1720 mActiveTracks.add(track);
1721 if (track->mainBuffer() != mMixBuffer) {
1722 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1723 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001724 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001725 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001726 }
1727 }
1728
1729 status = NO_ERROR;
1730 }
1731
Steve Block3856b092011-10-20 11:56:00 +01001732 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001733 mWaitWorkCV.broadcast();
1734
1735 return status;
1736}
1737
1738// destroyTrack_l() must be called with ThreadBase::mLock held
1739void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1740{
1741 track->mState = TrackBase::TERMINATED;
1742 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001743 removeTrack_l(track);
1744 }
1745}
1746
1747void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1748{
1749 mTracks.remove(track);
1750 deleteTrackName_l(track->name());
1751 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1752 if (chain != 0) {
1753 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001754 }
1755}
1756
1757String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1758{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001759 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001760 char *s;
1761
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001762 Mutex::Autolock _l(mLock);
1763 if (initCheck() != NO_ERROR) {
1764 return out_s8;
1765 }
1766
Dima Zavin799a70e2011-04-18 16:57:27 -07001767 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001768 out_s8 = String8(s);
1769 free(s);
1770 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001771}
1772
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001773// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001774void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1775 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001776 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001777
Steve Block3856b092011-10-20 11:56:00 +01001778 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001779
1780 switch (event) {
1781 case AudioSystem::OUTPUT_OPENED:
1782 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001783 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001784 desc.samplingRate = mSampleRate;
1785 desc.format = mFormat;
1786 desc.frameCount = mFrameCount;
1787 desc.latency = latency();
1788 param2 = &desc;
1789 break;
1790
1791 case AudioSystem::STREAM_CONFIG_CHANGED:
1792 param2 = &param;
1793 case AudioSystem::OUTPUT_CLOSED:
1794 default:
1795 break;
1796 }
1797 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1798}
1799
1800void AudioFlinger::PlaybackThread::readOutputParameters()
1801{
Dima Zavin799a70e2011-04-18 16:57:27 -07001802 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001803 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1804 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001805 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001806 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001807 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001808
1809 // FIXME - Current mixer implementation only supports stereo output: Always
1810 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001811 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001812 mMixBuffer = new int16_t[mFrameCount * 2];
1813 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1814
Eric Laurentde070132010-07-13 04:45:46 -07001815 // force reconfiguration of effect chains and engines to take new buffer size and audio
1816 // parameters into account
1817 // Note that mLock is not held when readOutputParameters() is called from the constructor
1818 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1819 // matter.
1820 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1821 Vector< sp<EffectChain> > effectChains = mEffectChains;
1822 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001823 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001824 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001825}
1826
1827status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1828{
Glenn Kastena0d68332012-01-27 16:47:15 -08001829 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001830 return BAD_VALUE;
1831 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001832 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001833 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001834 return INVALID_OPERATION;
1835 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001836 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001837
Dima Zavin799a70e2011-04-18 16:57:27 -07001838 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001839}
1840
Eric Laurent39e94f82010-07-28 01:32:47 -07001841uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001842{
1843 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001844 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001845 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001846 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001847 }
1848
1849 for (size_t i = 0; i < mTracks.size(); ++i) {
1850 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001851 if (sessionId == track->sessionId() &&
1852 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001853 result |= TRACK_SESSION;
1854 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001855 }
1856 }
1857
Eric Laurent39e94f82010-07-28 01:32:47 -07001858 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001859}
1860
Eric Laurentde070132010-07-13 04:45:46 -07001861uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1862{
Dima Zavinfce7a472011-04-19 22:30:36 -07001863 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001864 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001865 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1866 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001867 }
1868 for (size_t i = 0; i < mTracks.size(); i++) {
1869 sp<Track> track = mTracks[i];
1870 if (sessionId == track->sessionId() &&
1871 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001872 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07001873 }
1874 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001875 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001876}
1877
Mathias Agopian65ab4712010-07-14 17:59:35 -07001878
Glenn Kastenaed850d2012-01-26 09:46:34 -08001879AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001880{
1881 Mutex::Autolock _l(mLock);
1882 return mOutput;
1883}
1884
1885AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1886{
1887 Mutex::Autolock _l(mLock);
1888 AudioStreamOut *output = mOutput;
1889 mOutput = NULL;
1890 return output;
1891}
1892
1893// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08001894audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001895{
1896 if (mOutput == NULL) {
1897 return NULL;
1898 }
1899 return &mOutput->stream->common;
1900}
1901
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08001902uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08001903{
1904 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1905 // decoding and transfer time. So sleeping for half of the latency would likely cause
1906 // underruns
1907 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1908 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1909 } else {
1910 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1911 }
1912}
1913
Eric Laurenta011e352012-03-29 15:51:43 -07001914status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1915{
1916 if (!isValidSyncEvent(event)) {
1917 return BAD_VALUE;
1918 }
1919
1920 Mutex::Autolock _l(mLock);
1921
1922 for (size_t i = 0; i < mTracks.size(); ++i) {
1923 sp<Track> track = mTracks[i];
1924 if (event->triggerSession() == track->sessionId()) {
1925 track->setSyncEvent(event);
1926 return NO_ERROR;
1927 }
1928 }
1929
1930 return NAME_NOT_FOUND;
1931}
1932
1933bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
1934{
1935 switch (event->type()) {
1936 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
1937 return true;
1938 default:
1939 break;
1940 }
1941 return false;
1942}
1943
Mathias Agopian65ab4712010-07-14 17:59:35 -07001944// ----------------------------------------------------------------------------
1945
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001946AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001947 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten000f0e32012-03-01 17:10:56 -08001948 : PlaybackThread(audioFlinger, output, id, device, type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001949{
Glenn Kasten000f0e32012-03-01 17:10:56 -08001950 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001951 // FIXME - Current mixer implementation only supports stereo output
1952 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001953 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001954 }
1955}
1956
1957AudioFlinger::MixerThread::~MixerThread()
1958{
1959 delete mAudioMixer;
1960}
1961
Glenn Kasten83efdd02012-02-24 07:21:32 -08001962class CpuStats {
1963public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08001964 CpuStats();
1965 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08001966#ifdef DEBUG_CPU_USAGE
1967private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08001968 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
1969 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
1970
1971 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
1972
1973 int mCpuNum; // thread's current CPU number
1974 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08001975#endif
1976};
1977
Glenn Kasten190a46f2012-03-06 11:27:10 -08001978CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08001979#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08001980 : mCpuNum(-1), mCpukHz(-1)
1981#endif
1982{
1983}
1984
1985void CpuStats::sample(const String8 &title) {
1986#ifdef DEBUG_CPU_USAGE
1987 // get current thread's delta CPU time in wall clock ns
1988 double wcNs;
1989 bool valid = mCpuUsage.sampleAndEnable(wcNs);
1990
1991 // record sample for wall clock statistics
1992 if (valid) {
1993 mWcStats.sample(wcNs);
1994 }
1995
1996 // get the current CPU number
1997 int cpuNum = sched_getcpu();
1998
1999 // get the current CPU frequency in kHz
2000 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2001
2002 // check if either CPU number or frequency changed
2003 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2004 mCpuNum = cpuNum;
2005 mCpukHz = cpukHz;
2006 // ignore sample for purposes of cycles
2007 valid = false;
2008 }
2009
2010 // if no change in CPU number or frequency, then record sample for cycle statistics
2011 if (valid && mCpukHz > 0) {
2012 double cycles = wcNs * cpukHz * 0.000001;
2013 mHzStats.sample(cycles);
2014 }
2015
2016 unsigned n = mWcStats.n();
2017 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002018 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002019 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002020 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2021 double perLoop = elapsed / (double) n;
2022 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002023 double perLoop1k = perLoop * 0.001;
2024 double mean = mWcStats.mean();
2025 double stddev = mWcStats.stddev();
2026 double minimum = mWcStats.minimum();
2027 double maximum = mWcStats.maximum();
2028 double meanCycles = mHzStats.mean();
2029 double stddevCycles = mHzStats.stddev();
2030 double minCycles = mHzStats.minimum();
2031 double maxCycles = mHzStats.maximum();
2032 mCpuUsage.resetElapsed();
2033 mWcStats.reset();
2034 mHzStats.reset();
2035 ALOGD("CPU usage for %s over past %.1f secs\n"
2036 " (%u mixer loops at %.1f mean ms per loop):\n"
2037 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2038 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2039 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2040 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002041 elapsed * .000000001, n, perLoop * .000001,
2042 mean * .001,
2043 stddev * .001,
2044 minimum * .001,
2045 maximum * .001,
2046 mean / perLoop100,
2047 stddev / perLoop100,
2048 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002049 maximum / perLoop100,
2050 meanCycles / perLoop1k,
2051 stddevCycles / perLoop1k,
2052 minCycles / perLoop1k,
2053 maxCycles / perLoop1k);
2054
Glenn Kasten83efdd02012-02-24 07:21:32 -08002055 }
2056 }
2057#endif
2058};
2059
Glenn Kasten37d825e2012-02-24 07:21:48 -08002060void AudioFlinger::PlaybackThread::checkSilentMode_l()
2061{
2062 if (!mMasterMute) {
2063 char value[PROPERTY_VALUE_MAX];
2064 if (property_get("ro.audio.silent", value, "0") > 0) {
2065 char *endptr;
2066 unsigned long ul = strtoul(value, &endptr, 0);
2067 if (*endptr == '\0' && ul != 0) {
2068 ALOGD("Silence is golden");
2069 // The setprop command will not allow a property to be changed after
2070 // the first time it is set, so we don't have to worry about un-muting.
2071 setMasterMute_l(true);
2072 }
2073 }
2074 }
2075}
2076
Glenn Kasten000f0e32012-03-01 17:10:56 -08002077bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002078{
2079 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002080
Glenn Kasten000f0e32012-03-01 17:10:56 -08002081 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002082
2083 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002084 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002085if (mType == MIXER) {
2086 longStandbyExit = false;
2087}
Glenn Kasten688a6402012-02-29 07:57:06 -08002088
Glenn Kasten000f0e32012-03-01 17:10:56 -08002089 // DUPLICATING
2090 // FIXME could this be made local to while loop?
2091 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002092
Glenn Kasten66fcab92012-02-24 14:59:21 -08002093 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002094 sleepTime = idleSleepTime;
2095
2096if (mType == MIXER) {
2097 sleepTimeShift = 0;
2098}
2099
Glenn Kasten83efdd02012-02-24 07:21:32 -08002100 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002101 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002102
Eric Laurentfeb0db62011-07-22 09:04:31 -07002103 acquireWakeLock();
2104
Mathias Agopian65ab4712010-07-14 17:59:35 -07002105 while (!exitPending())
2106 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002107 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002108
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002109 Vector< sp<EffectChain> > effectChains;
2110
Mathias Agopian65ab4712010-07-14 17:59:35 -07002111 processConfigEvents();
2112
Mathias Agopian65ab4712010-07-14 17:59:35 -07002113 { // scope for mLock
2114
2115 Mutex::Autolock _l(mLock);
2116
2117 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002118 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002119 }
2120
Glenn Kastenfa26a852012-03-06 11:28:04 -08002121 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002122
Mathias Agopian65ab4712010-07-14 17:59:35 -07002123 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002124 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002125 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002126 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002127
2128 threadLoop_standby();
2129
Mathias Agopian65ab4712010-07-14 17:59:35 -07002130 mStandby = true;
2131 mBytesWritten = 0;
2132 }
2133
Glenn Kasten3e074702012-02-28 18:40:35 -08002134 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002135 // we're about to wait, flush the binder command buffer
2136 IPCThreadState::self()->flushCommands();
2137
Glenn Kastenfa26a852012-03-06 11:28:04 -08002138 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002139
Mathias Agopian65ab4712010-07-14 17:59:35 -07002140 if (exitPending()) break;
2141
Eric Laurentfeb0db62011-07-22 09:04:31 -07002142 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002143 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002144 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002145 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002146 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002147 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002148
Eric Laurent27741442012-01-17 19:20:12 -08002149 mPrevMixerStatus = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002150
Glenn Kasten37d825e2012-02-24 07:21:48 -08002151 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002152
Glenn Kasten000f0e32012-03-01 17:10:56 -08002153 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002154 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002155 if (mType == MIXER) {
2156 sleepTimeShift = 0;
2157 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002158
Mathias Agopian65ab4712010-07-14 17:59:35 -07002159 continue;
2160 }
2161 }
2162
Glenn Kastenfec279f2012-03-08 07:47:15 -08002163 mixer_state newMixerStatus = prepareTracks_l(&tracksToRemove);
2164 // Shift in the new status; this could be a queue if it's
2165 // useful to filter the mixer status over several cycles.
2166 mPrevMixerStatus = mMixerStatus;
2167 mMixerStatus = newMixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002168
2169 // prevent any changes in effect chain list and in each effect chain
2170 // during mixing and effect process as the audio buffers could be deleted
2171 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002172 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002173 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002174
Glenn Kastenfec279f2012-03-08 07:47:15 -08002175 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002176 threadLoop_mix();
2177 } else {
2178 threadLoop_sleepTime();
2179 }
2180
2181 if (mSuspended > 0) {
2182 sleepTime = suspendSleepTimeUs();
2183 }
2184
2185 // only process effects if we're going to write
2186 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002187 for (size_t i = 0; i < effectChains.size(); i ++) {
2188 effectChains[i]->process_l();
2189 }
2190 }
2191
2192 // enable changes in effect chain
2193 unlockEffectChains(effectChains);
2194
2195 // sleepTime == 0 means we must write to audio hardware
2196 if (sleepTime == 0) {
2197
2198 threadLoop_write();
2199
2200if (mType == MIXER) {
2201 // write blocked detection
2202 nsecs_t now = systemTime();
2203 nsecs_t delta = now - mLastWriteTime;
2204 if (!mStandby && delta > maxPeriod) {
2205 mNumDelayedWrites++;
2206 if ((now - lastWarning) > kWarningThrottleNs) {
2207 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2208 ns2ms(delta), mNumDelayedWrites, this);
2209 lastWarning = now;
2210 }
2211 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2212 // a different threshold. Or completely removed for what it is worth anyway...
2213 if (mStandby) {
2214 longStandbyExit = true;
2215 }
2216 }
2217}
2218
2219 mStandby = false;
2220 } else {
2221 usleep(sleepTime);
2222 }
2223
2224 // finally let go of removed track(s), without the lock held
2225 // since we can't guarantee the destructors won't acquire that
2226 // same lock.
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002227 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002228
Glenn Kastenfa26a852012-03-06 11:28:04 -08002229 // FIXME I don't understand the need for this here;
2230 // it was in the original code but maybe the
2231 // assignment in saveOutputTracks() makes this unnecessary?
2232 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002233
2234 // Effect chains will be actually deleted here if they were removed from
2235 // mEffectChains list during mixing or effects processing
2236 effectChains.clear();
2237
2238 // FIXME Note that the above .clear() is no longer necessary since effectChains
2239 // is now local to this block, but will keep it for now (at least until merge done).
2240 }
2241
2242if (mType == MIXER || mType == DIRECT) {
2243 // put output stream into standby mode
2244 if (!mStandby) {
2245 mOutput->stream->common.standby(&mOutput->stream->common);
2246 }
2247}
2248if (mType == DUPLICATING) {
2249 // for DuplicatingThread, standby mode is handled by the outputTracks
2250}
2251
2252 releaseWakeLock();
2253
2254 ALOGV("Thread %p type %d exiting", this, mType);
2255 return false;
2256}
2257
2258// shared by MIXER and DIRECT, overridden by DUPLICATING
2259void AudioFlinger::PlaybackThread::threadLoop_write()
2260{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002261 // FIXME rewrite to reduce number of system calls
2262 mLastWriteTime = systemTime();
2263 mInWrite = true;
2264 mBytesWritten += mixBufferSize;
2265 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2266 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2267 mNumWrites++;
2268 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002269}
2270
2271// shared by MIXER and DIRECT, overridden by DUPLICATING
2272void AudioFlinger::PlaybackThread::threadLoop_standby()
2273{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002274 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2275 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002276}
2277
2278void AudioFlinger::MixerThread::threadLoop_mix()
2279{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002280 // obtain the presentation timestamp of the next output buffer
2281 int64_t pts;
2282 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002283
Glenn Kasten952eeb22012-03-06 11:30:57 -08002284 if (NULL != mOutput->stream->get_next_write_timestamp) {
2285 status = mOutput->stream->get_next_write_timestamp(
2286 mOutput->stream, &pts);
2287 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002288
Glenn Kasten952eeb22012-03-06 11:30:57 -08002289 if (status != NO_ERROR) {
2290 pts = AudioBufferProvider::kInvalidPTS;
2291 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002292
Glenn Kasten952eeb22012-03-06 11:30:57 -08002293 // mix buffers...
2294 mAudioMixer->process(pts);
2295 // increase sleep time progressively when application underrun condition clears.
2296 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2297 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2298 // such that we would underrun the audio HAL.
2299 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2300 sleepTimeShift--;
2301 }
2302 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002303 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002304 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002305}
2306
2307void AudioFlinger::MixerThread::threadLoop_sleepTime()
2308{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002309 // If no tracks are ready, sleep once for the duration of an output
2310 // buffer size, then write 0s to the output
2311 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002312 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002313 sleepTime = activeSleepTime >> sleepTimeShift;
2314 if (sleepTime < kMinThreadSleepTimeUs) {
2315 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002316 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002317 // reduce sleep time in case of consecutive application underruns to avoid
2318 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2319 // duration we would end up writing less data than needed by the audio HAL if
2320 // the condition persists.
2321 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2322 sleepTimeShift++;
2323 }
2324 } else {
2325 sleepTime = idleSleepTime;
2326 }
2327 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002328 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002329 memset (mMixBuffer, 0, mixBufferSize);
2330 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002331 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002332 }
2333 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002334}
2335
2336// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002337AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002338 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002339{
2340
Glenn Kasten29c23c32012-01-26 13:37:52 -08002341 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002342 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002343 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002344 size_t mixedTracks = 0;
2345 size_t tracksWithEffect = 0;
2346
2347 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002348 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002349
Eric Laurent571d49c2010-08-11 05:20:11 -07002350 if (masterMute) {
2351 masterVolume = 0;
2352 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002353 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002354 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002355 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002356 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002357 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002358 masterVolume = (float)((v + (1 << 23)) >> 24);
2359 chain.clear();
2360 }
2361
2362 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002363 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002364 if (t == 0) continue;
2365
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002366 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002367 Track* const track = t.get();
2368 audio_track_cblk_t* cblk = track->cblk();
2369
2370 // The first time a track is added we wait
2371 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002372 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002373 // make sure that we have enough frames to mix one full buffer.
2374 // enforce this condition only once to enable draining the buffer in case the client
2375 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002376 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002377 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002378 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002379 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002380 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002381 if (t->sampleRate() == (int)mSampleRate) {
2382 minFrames = mFrameCount;
2383 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002384 // +1 for rounding and +1 for additional sample needed for interpolation
2385 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2386 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07002387 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08002388 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2389 // the minimum track buffer size is normally twice the number of frames necessary
2390 // to fill one buffer and the resampler should not leave more than one buffer worth
2391 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002392 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002393 }
2394 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002395 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002396 !track->isPaused() && !track->isTerminated())
2397 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002398 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002399
2400 mixedTracks++;
2401
2402 // track->mainBuffer() != mMixBuffer means there is an effect chain
2403 // connected to the track
2404 chain.clear();
2405 if (track->mainBuffer() != mMixBuffer) {
2406 chain = getEffectChain_l(track->sessionId());
2407 // Delegate volume control to effect in track effect chain if needed
2408 if (chain != 0) {
2409 tracksWithEffect++;
2410 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002411 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002412 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002413 }
2414 }
2415
2416
2417 int param = AudioMixer::VOLUME;
2418 if (track->mFillingUpStatus == Track::FS_FILLED) {
2419 // no ramp for the first volume setting
2420 track->mFillingUpStatus = Track::FS_ACTIVE;
2421 if (track->mState == TrackBase::RESUMING) {
2422 track->mState = TrackBase::ACTIVE;
2423 param = AudioMixer::RAMP_VOLUME;
2424 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002425 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002426 } else if (cblk->server != 0) {
2427 // If the track is stopped before the first frame was mixed,
2428 // do not apply ramp
2429 param = AudioMixer::RAMP_VOLUME;
2430 }
2431
2432 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002433 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002434 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002435 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002436 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002437 if (track->isPausing()) {
2438 track->setPaused();
2439 }
2440 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002441
Mathias Agopian65ab4712010-07-14 17:59:35 -07002442 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002443 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002444 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002445 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002446 vl = vlr & 0xFFFF;
2447 vr = vlr >> 16;
2448 // track volumes come from shared memory, so can't be trusted and must be clamped
2449 if (vl > MAX_GAIN_INT) {
2450 ALOGV("Track left volume out of range: %04X", vl);
2451 vl = MAX_GAIN_INT;
2452 }
2453 if (vr > MAX_GAIN_INT) {
2454 ALOGV("Track right volume out of range: %04X", vr);
2455 vr = MAX_GAIN_INT;
2456 }
2457 // now apply the master volume and stream type volume
2458 vl = (uint32_t)(v * vl) << 12;
2459 vr = (uint32_t)(v * vr) << 12;
2460 // assuming master volume and stream type volume each go up to 1.0,
2461 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002462
Glenn Kasten05632a52012-01-03 14:22:33 -08002463 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2464 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002465 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002466 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002467 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002468 }
2469 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002470 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002471 // Delegate volume control to effect in track effect chain if needed
2472 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2473 // Do not ramp volume if volume is controlled by effect
2474 param = AudioMixer::VOLUME;
2475 track->mHasVolumeController = true;
2476 } else {
2477 // force no volume ramp when volume controller was just disabled or removed
2478 // from effect chain to avoid volume spike
2479 if (track->mHasVolumeController) {
2480 param = AudioMixer::VOLUME;
2481 }
2482 track->mHasVolumeController = false;
2483 }
2484
2485 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002486 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002487 vl = (vl + (1 << 11)) >> 12;
2488 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2489 vr = (vr + (1 << 11)) >> 12;
2490 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002491
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002492 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 -07002493
Mathias Agopian65ab4712010-07-14 17:59:35 -07002494 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002495 mAudioMixer->setBufferProvider(name, track);
2496 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002497
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002498 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2499 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2500 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002501 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002502 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002503 AudioMixer::TRACK,
2504 AudioMixer::FORMAT, (void *)track->format());
2505 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002506 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002507 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002508 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002509 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002510 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002511 AudioMixer::RESAMPLE,
2512 AudioMixer::SAMPLE_RATE,
2513 (void *)(cblk->sampleRate));
2514 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002515 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002516 AudioMixer::TRACK,
2517 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2518 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002519 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002520 AudioMixer::TRACK,
2521 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2522
2523 // reset retry count
2524 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002525
Eric Laurent27741442012-01-17 19:20:12 -08002526 // If one track is ready, set the mixer ready if:
2527 // - the mixer was not ready during previous round OR
2528 // - no other track is not ready
2529 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2530 mixerStatus != MIXER_TRACKS_ENABLED) {
2531 mixerStatus = MIXER_TRACKS_READY;
2532 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002533 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002534 //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 -07002535 if (track->isStopped()) {
2536 track->reset();
2537 }
2538 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2539 // We have consumed all the buffers of this track.
2540 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07002541 // TODO: use actual buffer filling status instead of latency when available from
2542 // audio HAL
2543 size_t audioHALFrames =
2544 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2545 size_t framesWritten =
2546 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2547 if (track->presentationComplete(framesWritten, audioHALFrames)) {
2548 tracksToRemove->add(track);
2549 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002550 } else {
2551 // No buffers for this track. Give it a few chances to
2552 // fill a buffer, then remove it from active list.
2553 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002554 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002555 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002556 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002557 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002558 // If one track is not ready, mark the mixer also not ready if:
2559 // - the mixer was ready during previous round OR
2560 // - no other track is ready
2561 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2562 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002563 mixerStatus = MIXER_TRACKS_ENABLED;
2564 }
2565 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002566 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002567 }
2568 }
2569
2570 // remove all the tracks that need to be...
2571 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002572 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002573 for (size_t i=0 ; i<count ; i++) {
2574 const sp<Track>& track = tracksToRemove->itemAt(i);
2575 mActiveTracks.remove(track);
2576 if (track->mainBuffer() != mMixBuffer) {
2577 chain = getEffectChain_l(track->sessionId());
2578 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002579 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002580 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002581 }
2582 }
2583 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002584 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002585 }
2586 }
2587 }
2588
2589 // mix buffer must be cleared if all tracks are connected to an
2590 // effect chain as in this case the mixer will not write to
2591 // mix buffer and track effects will accumulate into it
2592 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2593 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2594 }
2595
2596 return mixerStatus;
2597}
2598
Glenn Kasten66fcab92012-02-24 14:59:21 -08002599/*
2600The derived values that are cached:
2601 - mixBufferSize from frame count * frame size
2602 - activeSleepTime from activeSleepTimeUs()
2603 - idleSleepTime from idleSleepTimeUs()
2604 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2605 - maxPeriod from frame count and sample rate (MIXER only)
2606
2607The parameters that affect these derived values are:
2608 - frame count
2609 - frame size
2610 - sample rate
2611 - device type: A2DP or not
2612 - device latency
2613 - format: PCM or not
2614 - active sleep time
2615 - idle sleep time
2616*/
2617
2618void AudioFlinger::PlaybackThread::cacheParameters_l()
2619{
2620 mixBufferSize = mFrameCount * mFrameSize;
2621 activeSleepTime = activeSleepTimeUs();
2622 idleSleepTime = idleSleepTimeUs();
2623}
2624
Glenn Kastenfff6d712012-01-12 16:38:12 -08002625void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002626{
Steve Block3856b092011-10-20 11:56:00 +01002627 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002628 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002629 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002630
Mathias Agopian65ab4712010-07-14 17:59:35 -07002631 size_t size = mTracks.size();
2632 for (size_t i = 0; i < size; i++) {
2633 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08002634 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002635 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002636 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002637 }
2638 }
2639}
2640
Mathias Agopian65ab4712010-07-14 17:59:35 -07002641// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07002642int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002643{
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07002644 int name = mAudioMixer->getTrackName();
2645 if (name >= 0) {
2646 mAudioMixer->setParameter(name,
2647 AudioMixer::TRACK,
2648 AudioMixer::CHANNEL_MASK, (void *)channelMask);
2649 }
2650 return name;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002651}
2652
2653// deleteTrackName_l() must be called with ThreadBase::mLock held
2654void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2655{
Steve Block3856b092011-10-20 11:56:00 +01002656 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002657 mAudioMixer->deleteTrackName(name);
2658}
2659
2660// checkForNewParameters_l() must be called with ThreadBase::mLock held
2661bool AudioFlinger::MixerThread::checkForNewParameters_l()
2662{
2663 bool reconfig = false;
2664
2665 while (!mNewParameters.isEmpty()) {
2666 status_t status = NO_ERROR;
2667 String8 keyValuePair = mNewParameters[0];
2668 AudioParameter param = AudioParameter(keyValuePair);
2669 int value;
2670
2671 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2672 reconfig = true;
2673 }
2674 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002675 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002676 status = BAD_VALUE;
2677 } else {
2678 reconfig = true;
2679 }
2680 }
2681 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002682 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002683 status = BAD_VALUE;
2684 } else {
2685 reconfig = true;
2686 }
2687 }
2688 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2689 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002690 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002691 // if frame count is changed after track creation
2692 if (!mTracks.isEmpty()) {
2693 status = INVALID_OPERATION;
2694 } else {
2695 reconfig = true;
2696 }
2697 }
2698 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07002699#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08002700 // when changing the audio output device, call addBatteryData to notify
2701 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002702 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002703 uint32_t params = 0;
2704 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002705 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002706 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2707 }
2708
2709 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002710 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002711 // check if any other device (except speaker) is on
2712 if (value & deviceWithoutSpeaker ) {
2713 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2714 }
2715
2716 if (params != 0) {
2717 addBatteryData(params);
2718 }
2719 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07002720#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08002721
Mathias Agopian65ab4712010-07-14 17:59:35 -07002722 // forward device change to effects that have requested to be
2723 // aware of attached audio device.
2724 mDevice = (uint32_t)value;
2725 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002726 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002727 }
2728 }
2729
2730 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002731 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002732 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002733 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002734 mOutput->stream->common.standby(&mOutput->stream->common);
2735 mStandby = true;
2736 mBytesWritten = 0;
2737 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002738 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002739 }
2740 if (status == NO_ERROR && reconfig) {
2741 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002742 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2743 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002744 readOutputParameters();
2745 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2746 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07002747 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002748 if (name < 0) break;
2749 mTracks[i]->mName = name;
2750 // limit track sample rate to 2 x new output sample rate
2751 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2752 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2753 }
2754 }
2755 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2756 }
2757 }
2758
2759 mNewParameters.removeAt(0);
2760
2761 mParamStatus = status;
2762 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002763 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2764 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002765 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002766 }
2767 return reconfig;
2768}
2769
2770status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2771{
2772 const size_t SIZE = 256;
2773 char buffer[SIZE];
2774 String8 result;
2775
2776 PlaybackThread::dumpInternals(fd, args);
2777
2778 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2779 result.append(buffer);
2780 write(fd, result.string(), result.size());
2781 return NO_ERROR;
2782}
2783
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002784uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002785{
Eric Laurent60e18242010-07-29 06:50:24 -07002786 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002787}
2788
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002789uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002790{
2791 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2792}
2793
Glenn Kasten66fcab92012-02-24 14:59:21 -08002794void AudioFlinger::MixerThread::cacheParameters_l()
2795{
2796 PlaybackThread::cacheParameters_l();
2797
2798 // FIXME: Relaxed timing because of a certain device that can't meet latency
2799 // Should be reduced to 2x after the vendor fixes the driver issue
2800 // increase threshold again due to low power audio mode. The way this warning
2801 // threshold is calculated and its usefulness should be reconsidered anyway.
2802 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
2803}
2804
Mathias Agopian65ab4712010-07-14 17:59:35 -07002805// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002806AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2807 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002808 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002809 // mLeftVolFloat, mRightVolFloat
2810 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002811{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002812}
2813
2814AudioFlinger::DirectOutputThread::~DirectOutputThread()
2815{
2816}
2817
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002818AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
2819 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08002820)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002821{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002822 sp<Track> trackToRemove;
2823
Glenn Kastenfec279f2012-03-08 07:47:15 -08002824 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002825
Glenn Kasten952eeb22012-03-06 11:30:57 -08002826 // find out which tracks need to be processed
2827 if (mActiveTracks.size() != 0) {
2828 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08002829 // The track died recently
2830 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002831
Glenn Kasten952eeb22012-03-06 11:30:57 -08002832 Track* const track = t.get();
2833 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834
Glenn Kasten952eeb22012-03-06 11:30:57 -08002835 // The first time a track is added we wait
2836 // for all its buffers to be filled before processing it
2837 if (cblk->framesReady() && track->isReady() &&
2838 !track->isPaused() && !track->isTerminated())
2839 {
2840 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002841
Glenn Kasten952eeb22012-03-06 11:30:57 -08002842 if (track->mFillingUpStatus == Track::FS_FILLED) {
2843 track->mFillingUpStatus = Track::FS_ACTIVE;
2844 mLeftVolFloat = mRightVolFloat = 0;
2845 mLeftVolShort = mRightVolShort = 0;
2846 if (track->mState == TrackBase::RESUMING) {
2847 track->mState = TrackBase::ACTIVE;
2848 rampVolume = true;
2849 }
2850 } else if (cblk->server != 0) {
2851 // If the track is stopped before the first frame was mixed,
2852 // do not apply ramp
2853 rampVolume = true;
2854 }
2855 // compute volume for this track
2856 float left, right;
2857 if (track->isMuted() || mMasterMute || track->isPausing() ||
2858 mStreamTypes[track->streamType()].mute) {
2859 left = right = 0;
2860 if (track->isPausing()) {
2861 track->setPaused();
2862 }
2863 } else {
2864 float typeVolume = mStreamTypes[track->streamType()].volume;
2865 float v = mMasterVolume * typeVolume;
2866 uint32_t vlr = cblk->getVolumeLR();
2867 float v_clamped = v * (vlr & 0xFFFF);
2868 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2869 left = v_clamped/MAX_GAIN;
2870 v_clamped = v * (vlr >> 16);
2871 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2872 right = v_clamped/MAX_GAIN;
2873 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002874
Glenn Kasten952eeb22012-03-06 11:30:57 -08002875 if (left != mLeftVolFloat || right != mRightVolFloat) {
2876 mLeftVolFloat = left;
2877 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002878
Glenn Kasten952eeb22012-03-06 11:30:57 -08002879 // If audio HAL implements volume control,
2880 // force software volume to nominal value
2881 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
2882 left = 1.0f;
2883 right = 1.0f;
2884 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002885
Glenn Kasten952eeb22012-03-06 11:30:57 -08002886 // Convert volumes from float to 8.24
2887 uint32_t vl = (uint32_t)(left * (1 << 24));
2888 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002889
Glenn Kasten952eeb22012-03-06 11:30:57 -08002890 // Delegate volume control to effect in track effect chain if needed
2891 // only one effect chain can be present on DirectOutputThread, so if
2892 // there is one, the track is connected to it
2893 if (!mEffectChains.isEmpty()) {
2894 // Do not ramp volume if volume is controlled by effect
2895 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002896 rampVolume = false;
2897 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002898 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002899
Glenn Kasten952eeb22012-03-06 11:30:57 -08002900 // Convert volumes from 8.24 to 4.12 format
2901 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2902 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2903 leftVol = (uint16_t)v_clamped;
2904 v_clamped = (vr + (1 << 11)) >> 12;
2905 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2906 rightVol = (uint16_t)v_clamped;
2907 } else {
2908 leftVol = mLeftVolShort;
2909 rightVol = mRightVolShort;
2910 rampVolume = false;
2911 }
2912
2913 // reset retry count
2914 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002915 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002916 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002917 } else {
2918 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2919 if (track->isStopped()) {
2920 track->reset();
2921 }
2922 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2923 // We have consumed all the buffers of this track.
2924 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07002925 // TODO: implement behavior for compressed audio
2926 size_t audioHALFrames =
2927 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2928 size_t framesWritten =
2929 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2930 if (track->presentationComplete(framesWritten, audioHALFrames)) {
2931 trackToRemove = track;
2932 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002933 } else {
2934 // No buffers for this track. Give it a few chances to
2935 // fill a buffer, then remove it from active list.
2936 if (--(track->mRetryCount) <= 0) {
2937 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2938 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002939 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002940 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002941 }
2942 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002943 }
2944 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002945
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002946 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08002947 // remove all the tracks that need to be...
2948 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002949 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002950 mActiveTracks.remove(trackToRemove);
2951 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002952 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08002953 trackToRemove->sessionId());
2954 mEffectChains[0]->decActiveTrackCnt();
2955 }
2956 if (trackToRemove->isTerminated()) {
2957 removeTrack_l(trackToRemove);
2958 }
2959 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002960
Glenn Kastenfec279f2012-03-08 07:47:15 -08002961 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002962}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002963
Glenn Kasten000f0e32012-03-01 17:10:56 -08002964void AudioFlinger::DirectOutputThread::threadLoop_mix()
2965{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002966 AudioBufferProvider::Buffer buffer;
2967 size_t frameCount = mFrameCount;
2968 int8_t *curBuf = (int8_t *)mMixBuffer;
2969 // output audio to hardware
2970 while (frameCount) {
2971 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002972 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002973 if (CC_UNLIKELY(buffer.raw == NULL)) {
2974 memset(curBuf, 0, frameCount * mFrameSize);
2975 break;
2976 }
2977 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2978 frameCount -= buffer.frameCount;
2979 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002980 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002981 }
2982 sleepTime = 0;
2983 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002984 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08002985
2986 // apply volume
2987
2988 // Do not apply volume on compressed audio
2989 if (!audio_is_linear_pcm(mFormat)) {
2990 return;
2991 }
2992
2993 // convert to signed 16 bit before volume calculation
2994 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
2995 size_t count = mFrameCount * mChannelCount;
2996 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2997 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002998 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08002999 *dst-- = (int16_t)(*src--^0x80) << 8;
3000 }
3001 }
3002
3003 frameCount = mFrameCount;
3004 int16_t *out = mMixBuffer;
3005 if (rampVolume) {
3006 if (mChannelCount == 1) {
3007 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3008 int32_t vlInc = d / (int32_t)frameCount;
3009 int32_t vl = ((int32_t)mLeftVolShort << 16);
3010 do {
3011 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3012 out++;
3013 vl += vlInc;
3014 } while (--frameCount);
3015
3016 } else {
3017 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3018 int32_t vlInc = d / (int32_t)frameCount;
3019 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
3020 int32_t vrInc = d / (int32_t)frameCount;
3021 int32_t vl = ((int32_t)mLeftVolShort << 16);
3022 int32_t vr = ((int32_t)mRightVolShort << 16);
3023 do {
3024 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3025 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3026 out += 2;
3027 vl += vlInc;
3028 vr += vrInc;
3029 } while (--frameCount);
3030 }
3031 } else {
3032 if (mChannelCount == 1) {
3033 do {
3034 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3035 out++;
3036 } while (--frameCount);
3037 } else {
3038 do {
3039 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3040 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3041 out += 2;
3042 } while (--frameCount);
3043 }
3044 }
3045
3046 // convert back to unsigned 8 bit after volume calculation
3047 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3048 size_t count = mFrameCount * mChannelCount;
3049 int16_t *src = mMixBuffer;
3050 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003051 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003052 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3053 }
3054 }
3055
3056 mLeftVolShort = leftVol;
3057 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003058}
3059
3060void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3061{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003062 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003063 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003064 sleepTime = activeSleepTime;
3065 } else {
3066 sleepTime = idleSleepTime;
3067 }
3068 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3069 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
3070 sleepTime = 0;
3071 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003072}
3073
3074// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003075int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003076{
3077 return 0;
3078}
3079
3080// deleteTrackName_l() must be called with ThreadBase::mLock held
3081void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3082{
3083}
3084
3085// checkForNewParameters_l() must be called with ThreadBase::mLock held
3086bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3087{
3088 bool reconfig = false;
3089
3090 while (!mNewParameters.isEmpty()) {
3091 status_t status = NO_ERROR;
3092 String8 keyValuePair = mNewParameters[0];
3093 AudioParameter param = AudioParameter(keyValuePair);
3094 int value;
3095
3096 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3097 // do not accept frame count changes if tracks are open as the track buffer
3098 // size depends on frame count and correct behavior would not be garantied
3099 // if frame count is changed after track creation
3100 if (!mTracks.isEmpty()) {
3101 status = INVALID_OPERATION;
3102 } else {
3103 reconfig = true;
3104 }
3105 }
3106 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003107 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003108 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003109 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003110 mOutput->stream->common.standby(&mOutput->stream->common);
3111 mStandby = true;
3112 mBytesWritten = 0;
3113 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003114 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003115 }
3116 if (status == NO_ERROR && reconfig) {
3117 readOutputParameters();
3118 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3119 }
3120 }
3121
3122 mNewParameters.removeAt(0);
3123
3124 mParamStatus = status;
3125 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003126 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3127 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003128 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003129 }
3130 return reconfig;
3131}
3132
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003133uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003134{
3135 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003136 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003137 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003138 } else {
3139 time = 10000;
3140 }
3141 return time;
3142}
3143
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003144uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003145{
3146 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003147 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003148 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003149 } else {
3150 time = 10000;
3151 }
3152 return time;
3153}
3154
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003155uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003156{
3157 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003158 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003159 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3160 } else {
3161 time = 10000;
3162 }
3163 return time;
3164}
3165
Glenn Kasten66fcab92012-02-24 14:59:21 -08003166void AudioFlinger::DirectOutputThread::cacheParameters_l()
3167{
3168 PlaybackThread::cacheParameters_l();
3169
3170 // use shorter standby delay as on normal output to release
3171 // hardware resources as soon as possible
3172 standbyDelay = microseconds(activeSleepTime*2);
3173}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003174
Mathias Agopian65ab4712010-07-14 17:59:35 -07003175// ----------------------------------------------------------------------------
3176
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003177AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003178 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003179 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3180 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003181{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003182 addOutputTrack(mainThread);
3183}
3184
3185AudioFlinger::DuplicatingThread::~DuplicatingThread()
3186{
3187 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3188 mOutputTracks[i]->destroy();
3189 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003190}
3191
Glenn Kasten000f0e32012-03-01 17:10:56 -08003192void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003193{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003194 // mix buffers...
3195 if (outputsReady(outputTracks)) {
3196 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3197 } else {
3198 memset(mMixBuffer, 0, mixBufferSize);
3199 }
3200 sleepTime = 0;
3201 writeFrames = mFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003202}
3203
3204void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3205{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003206 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003207 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003208 sleepTime = activeSleepTime;
3209 } else {
3210 sleepTime = idleSleepTime;
3211 }
3212 } else if (mBytesWritten != 0) {
3213 // flush remaining overflow buffers in output tracks
3214 for (size_t i = 0; i < outputTracks.size(); i++) {
3215 if (outputTracks[i]->isActive()) {
3216 sleepTime = 0;
3217 writeFrames = 0;
3218 memset(mMixBuffer, 0, mixBufferSize);
3219 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003221 }
3222 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003223}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003224
Glenn Kasten000f0e32012-03-01 17:10:56 -08003225void AudioFlinger::DuplicatingThread::threadLoop_write()
3226{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003227 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003228 for (size_t i = 0; i < outputTracks.size(); i++) {
3229 outputTracks[i]->write(mMixBuffer, writeFrames);
3230 }
3231 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003232}
Glenn Kasten688a6402012-02-29 07:57:06 -08003233
Glenn Kasten000f0e32012-03-01 17:10:56 -08003234void AudioFlinger::DuplicatingThread::threadLoop_standby()
3235{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003236 // DuplicatingThread implements standby by stopping all tracks
3237 for (size_t i = 0; i < outputTracks.size(); i++) {
3238 outputTracks[i]->stop();
3239 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003240}
3241
Glenn Kastenfa26a852012-03-06 11:28:04 -08003242void AudioFlinger::DuplicatingThread::saveOutputTracks()
3243{
3244 outputTracks = mOutputTracks;
3245}
3246
3247void AudioFlinger::DuplicatingThread::clearOutputTracks()
3248{
3249 outputTracks.clear();
3250}
3251
Mathias Agopian65ab4712010-07-14 17:59:35 -07003252void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3253{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003254 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003255 // FIXME explain this formula
Mathias Agopian65ab4712010-07-14 17:59:35 -07003256 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003257 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003258 this,
3259 mSampleRate,
3260 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003261 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003262 frameCount);
3263 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003264 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003265 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003266 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003267 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003268 }
3269}
3270
3271void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3272{
3273 Mutex::Autolock _l(mLock);
3274 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003275 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003276 mOutputTracks[i]->destroy();
3277 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003278 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003279 return;
3280 }
3281 }
Steve Block3856b092011-10-20 11:56:00 +01003282 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003283}
3284
Glenn Kasten438b0362012-03-06 11:24:48 -08003285// caller must hold mLock
3286void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003287{
3288 mWaitTimeMs = UINT_MAX;
3289 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3290 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003291 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003292 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3293 if (waitTimeMs < mWaitTimeMs) {
3294 mWaitTimeMs = waitTimeMs;
3295 }
3296 }
3297 }
3298}
3299
3300
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003301bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003302{
3303 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003304 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003305 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003306 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003307 return false;
3308 }
3309 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3310 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003311 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003312 return false;
3313 }
3314 }
3315 return true;
3316}
3317
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003318uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003319{
3320 return (mWaitTimeMs * 1000) / 2;
3321}
3322
Glenn Kasten66fcab92012-02-24 14:59:21 -08003323void AudioFlinger::DuplicatingThread::cacheParameters_l()
3324{
3325 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3326 updateWaitTime_l();
3327
3328 MixerThread::cacheParameters_l();
3329}
3330
Mathias Agopian65ab4712010-07-14 17:59:35 -07003331// ----------------------------------------------------------------------------
3332
3333// TrackBase constructor must be called with AudioFlinger::mLock held
3334AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003335 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003336 const sp<Client>& client,
3337 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003338 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003339 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003340 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003341 const sp<IMemory>& sharedBuffer,
3342 int sessionId)
3343 : RefBase(),
3344 mThread(thread),
3345 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003346 mCblk(NULL),
3347 // mBuffer
3348 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003349 mFrameCount(0),
3350 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003351 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003352 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003353 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003354 // mChannelCount
3355 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003356{
Steve Block3856b092011-10-20 11:56:00 +01003357 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003358
Steve Blockb8a80522011-12-20 16:23:08 +00003359 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003360 size_t size = sizeof(audio_track_cblk_t);
3361 uint8_t channelCount = popcount(channelMask);
3362 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3363 if (sharedBuffer == 0) {
3364 size += bufferSize;
3365 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003366
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003367 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003368 mCblkMemory = client->heap()->allocate(size);
3369 if (mCblkMemory != 0) {
3370 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003371 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003372 new(mCblk) audio_track_cblk_t();
3373 // clear all buffers
3374 mCblk->frameCount = frameCount;
3375 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003376// uncomment the following lines to quickly test 32-bit wraparound
3377// mCblk->user = 0xffff0000;
3378// mCblk->server = 0xffff0000;
3379// mCblk->userBase = 0xffff0000;
3380// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003381 mChannelCount = channelCount;
3382 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003383 if (sharedBuffer == 0) {
3384 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3385 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3386 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003387 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003388 mCblk->flags = CBLK_UNDERRUN_ON;
3389 } else {
3390 mBuffer = sharedBuffer->pointer();
3391 }
3392 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3393 }
3394 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003395 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003396 client->heap()->dump("AudioTrack");
3397 return;
3398 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003399 } else {
3400 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07003401 // construct the shared structure in-place.
3402 new(mCblk) audio_track_cblk_t();
3403 // clear all buffers
3404 mCblk->frameCount = frameCount;
3405 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003406// uncomment the following lines to quickly test 32-bit wraparound
3407// mCblk->user = 0xffff0000;
3408// mCblk->server = 0xffff0000;
3409// mCblk->userBase = 0xffff0000;
3410// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003411 mChannelCount = channelCount;
3412 mChannelMask = channelMask;
3413 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3414 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3415 // Force underrun condition to avoid false underrun callback until first data is
3416 // written to buffer (other flags are cleared)
3417 mCblk->flags = CBLK_UNDERRUN_ON;
3418 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003419 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003420}
3421
3422AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3423{
Glenn Kastena0d68332012-01-27 16:47:15 -08003424 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003425 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003426 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003427 } else {
3428 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003429 }
3430 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003431 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003432 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003433 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003434 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003435 // If the client's reference count drops to zero, the associated destructor
3436 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3437 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003438 mClient.clear();
3439 }
3440}
3441
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003442// AudioBufferProvider interface
3443// getNextBuffer() = 0;
3444// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07003445void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3446{
Glenn Kastene0feee32011-12-13 11:53:26 -08003447 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003448 mFrameCount = buffer->frameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003449 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003450 buffer->frameCount = 0;
3451}
3452
3453bool AudioFlinger::ThreadBase::TrackBase::step() {
3454 bool result;
3455 audio_track_cblk_t* cblk = this->cblk();
3456
3457 result = cblk->stepServer(mFrameCount);
3458 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003459 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003460 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003461 }
3462 return result;
3463}
3464
3465void AudioFlinger::ThreadBase::TrackBase::reset() {
3466 audio_track_cblk_t* cblk = this->cblk();
3467
3468 cblk->user = 0;
3469 cblk->server = 0;
3470 cblk->userBase = 0;
3471 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003472 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01003473 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003474}
3475
Mathias Agopian65ab4712010-07-14 17:59:35 -07003476int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3477 return (int)mCblk->sampleRate;
3478}
3479
Mathias Agopian65ab4712010-07-14 17:59:35 -07003480void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3481 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003482 size_t frameSize = cblk->frameSize;
3483 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3484 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003485
3486 // Check validity of returned pointer in case the track control block would have been corrupted.
3487 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003488 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003489 ALOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Marco Nelissena1472d92012-03-30 14:36:54 -07003490 server %u, serverBase %u, user %u, userBase %u",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003491 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003492 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003493 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003494 }
3495
3496 return bufferStart;
3497}
3498
Eric Laurenta011e352012-03-29 15:51:43 -07003499status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
3500{
3501 mSyncEvents.add(event);
3502 return NO_ERROR;
3503}
3504
Mathias Agopian65ab4712010-07-14 17:59:35 -07003505// ----------------------------------------------------------------------------
3506
3507// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3508AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003509 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003510 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003511 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003512 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003513 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003514 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003515 int frameCount,
3516 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07003517 int sessionId,
3518 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003519 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07003520 mMute(false),
3521 // mFillingUpStatus ?
3522 // mRetryCount initialized later when needed
3523 mSharedBuffer(sharedBuffer),
3524 mStreamType(streamType),
3525 mName(-1), // see note below
3526 mMainBuffer(thread->mixBuffer()),
3527 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07003528 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07003529 mPresentationCompleteFrames(0),
3530 mFlags(flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003531{
3532 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003533 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3534 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003535 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kastenf9959012012-03-19 11:14:37 -07003536 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003537 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
Glenn Kastenf9959012012-03-19 11:14:37 -07003538 if (mName < 0) {
3539 ALOGE("no more track names available");
3540 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003541 }
Glenn Kastenf9959012012-03-19 11:14:37 -07003542 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003543}
3544
3545AudioFlinger::PlaybackThread::Track::~Track()
3546{
Steve Block3856b092011-10-20 11:56:00 +01003547 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003548 sp<ThreadBase> thread = mThread.promote();
3549 if (thread != 0) {
3550 Mutex::Autolock _l(thread->mLock);
3551 mState = TERMINATED;
3552 }
3553}
3554
3555void AudioFlinger::PlaybackThread::Track::destroy()
3556{
3557 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3558 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08003559 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003560 // we must acquire a strong reference on this Track before locking mLock
3561 // here so that the destructor is called only when exiting this function.
3562 // On the other hand, as long as Track::destroy() is only called by
3563 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3564 // this Track with its member mTrack.
3565 sp<Track> keep(this);
3566 { // scope for mLock
3567 sp<ThreadBase> thread = mThread.promote();
3568 if (thread != 0) {
3569 if (!isOutputTrack()) {
3570 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08003571 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003572
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003573#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003574 // to track the speaker usage
3575 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003576#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003577 }
3578 AudioSystem::releaseOutput(thread->id());
3579 }
3580 Mutex::Autolock _l(thread->mLock);
3581 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3582 playbackThread->destroyTrack_l(this);
3583 }
3584 }
3585}
3586
3587void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3588{
Glenn Kasten83d86532012-01-17 14:39:34 -08003589 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003590 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 -07003591 mName - AudioMixer::TRACK0,
Glenn Kasten44deb052012-02-05 18:09:08 -08003592 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003593 mStreamType,
3594 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003595 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003596 mSessionId,
3597 mFrameCount,
3598 mState,
3599 mMute,
3600 mFillingUpStatus,
3601 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003602 vlr & 0xFFFF,
3603 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003604 mCblk->server,
3605 mCblk->user,
3606 (int)mMainBuffer,
3607 (int)mAuxBuffer);
3608}
3609
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003610// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08003611status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003612 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003613{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003614 audio_track_cblk_t* cblk = this->cblk();
3615 uint32_t framesReady;
3616 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003617
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003618 // Check if last stepServer failed, try to step now
3619 if (mStepServerFailed) {
3620 if (!step()) goto getNextBuffer_exit;
3621 ALOGV("stepServer recovered");
3622 mStepServerFailed = false;
3623 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003624
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003625 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003626
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003627 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003628 uint32_t s = cblk->server;
3629 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3630
3631 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3632 if (framesReq > framesReady) {
3633 framesReq = framesReady;
3634 }
Marco Nelissena1472d92012-03-30 14:36:54 -07003635 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003636 framesReq = bufferEnd - s;
3637 }
3638
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003639 buffer->raw = getBuffer(s, framesReq);
3640 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003641
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003642 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003643 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003644 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003645
3646getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003647 buffer->raw = NULL;
3648 buffer->frameCount = 0;
3649 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3650 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003651}
3652
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003653uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08003654 return mCblk->framesReady();
3655}
3656
Mathias Agopian65ab4712010-07-14 17:59:35 -07003657bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003658 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003659
John Grossman4ff14ba2012-02-08 16:37:41 -08003660 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003661 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3662 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003663 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003664 return true;
3665 }
3666 return false;
3667}
3668
Eric Laurenta011e352012-03-29 15:51:43 -07003669status_t AudioFlinger::PlaybackThread::Track::start(pid_t tid,
3670 AudioSystem::sync_event_t event,
3671 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003672{
3673 status_t status = NO_ERROR;
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003674 ALOGV("start(%d), calling pid %d session %d tid %d",
3675 mName, IPCThreadState::self()->getCallingPid(), mSessionId, tid);
Glenn Kasten73d22752012-03-19 13:38:30 -07003676 // check for use case 2 with missing callback
3677 if (isFastTrack() && (mSharedBuffer == 0) && (tid == 0)) {
3678 ALOGW("AUDIO_POLICY_OUTPUT_FLAG_FAST denied");
3679 mFlags &= ~IAudioFlinger::TRACK_FAST;
3680 // FIXME the track must be invalidated and moved to another thread or
3681 // attached directly to the normal mixer now
3682 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003683 sp<ThreadBase> thread = mThread.promote();
3684 if (thread != 0) {
3685 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003686 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003687 // here the track could be either new, or restarted
3688 // in both cases "unstop" the track
3689 if (mState == PAUSED) {
3690 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003691 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003692 } else {
3693 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003694 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003695 }
3696
3697 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3698 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003699 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003700 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003701
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003702#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003703 // to track the speaker usage
3704 if (status == NO_ERROR) {
3705 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3706 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003707#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003708 }
3709 if (status == NO_ERROR) {
3710 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3711 playbackThread->addTrack_l(this);
3712 } else {
3713 mState = state;
3714 }
3715 } else {
3716 status = BAD_VALUE;
3717 }
3718 return status;
3719}
3720
3721void AudioFlinger::PlaybackThread::Track::stop()
3722{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003723 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003724 sp<ThreadBase> thread = mThread.promote();
3725 if (thread != 0) {
3726 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003727 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003728 if (mState > STOPPED) {
3729 mState = STOPPED;
3730 // If the track is not active (PAUSED and buffers full), flush buffers
3731 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3732 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3733 reset();
3734 }
Steve Block3856b092011-10-20 11:56:00 +01003735 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003736 }
3737 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3738 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003739 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003740 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003741
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003742#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003743 // to track the speaker usage
3744 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003745#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003746 }
3747 }
3748}
3749
3750void AudioFlinger::PlaybackThread::Track::pause()
3751{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003752 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003753 sp<ThreadBase> thread = mThread.promote();
3754 if (thread != 0) {
3755 Mutex::Autolock _l(thread->mLock);
3756 if (mState == ACTIVE || mState == RESUMING) {
3757 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003758 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003759 if (!isOutputTrack()) {
3760 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003761 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003762 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003763
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003764#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003765 // to track the speaker usage
3766 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003767#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003768 }
3769 }
3770 }
3771}
3772
3773void AudioFlinger::PlaybackThread::Track::flush()
3774{
Steve Block3856b092011-10-20 11:56:00 +01003775 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003776 sp<ThreadBase> thread = mThread.promote();
3777 if (thread != 0) {
3778 Mutex::Autolock _l(thread->mLock);
3779 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3780 return;
3781 }
3782 // No point remaining in PAUSED state after a flush => go to
3783 // STOPPED state
3784 mState = STOPPED;
3785
Eric Laurent38ccae22011-03-28 18:37:07 -07003786 // do not reset the track if it is still in the process of being stopped or paused.
3787 // this will be done by prepareTracks_l() when the track is stopped.
3788 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3789 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3790 reset();
3791 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003792 }
3793}
3794
3795void AudioFlinger::PlaybackThread::Track::reset()
3796{
3797 // Do not reset twice to avoid discarding data written just after a flush and before
3798 // the audioflinger thread detects the track is stopped.
3799 if (!mResetDone) {
3800 TrackBase::reset();
3801 // Force underrun condition to avoid false underrun callback until first data is
3802 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003803 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3804 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003805 mFillingUpStatus = FS_FILLING;
3806 mResetDone = true;
Eric Laurenta011e352012-03-29 15:51:43 -07003807 mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003808 }
3809}
3810
3811void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3812{
3813 mMute = muted;
3814}
3815
Mathias Agopian65ab4712010-07-14 17:59:35 -07003816status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3817{
3818 status_t status = DEAD_OBJECT;
3819 sp<ThreadBase> thread = mThread.promote();
3820 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003821 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3822 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003823 }
3824 return status;
3825}
3826
3827void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3828{
3829 mAuxEffectId = EffectId;
3830 mAuxBuffer = buffer;
3831}
3832
Eric Laurenta011e352012-03-29 15:51:43 -07003833bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
3834 size_t audioHalFrames)
3835{
3836 // a track is considered presented when the total number of frames written to audio HAL
3837 // corresponds to the number of frames written when presentationComplete() is called for the
3838 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
3839 if (mPresentationCompleteFrames == 0) {
3840 mPresentationCompleteFrames = framesWritten + audioHalFrames;
3841 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
3842 mPresentationCompleteFrames, audioHalFrames);
3843 }
3844 if (framesWritten >= mPresentationCompleteFrames) {
3845 ALOGV("presentationComplete() session %d complete: framesWritten %d",
3846 mSessionId, framesWritten);
3847 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
3848 mPresentationCompleteFrames = 0;
3849 return true;
3850 }
3851 return false;
3852}
3853
3854void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
3855{
3856 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
3857 if (mSyncEvents[i]->type() == type) {
3858 mSyncEvents[i]->trigger();
3859 mSyncEvents.removeAt(i);
3860 i--;
3861 }
3862 }
3863}
3864
3865
John Grossman4ff14ba2012-02-08 16:37:41 -08003866// timed audio tracks
3867
3868sp<AudioFlinger::PlaybackThread::TimedTrack>
3869AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003870 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003871 const sp<Client>& client,
3872 audio_stream_type_t streamType,
3873 uint32_t sampleRate,
3874 audio_format_t format,
3875 uint32_t channelMask,
3876 int frameCount,
3877 const sp<IMemory>& sharedBuffer,
3878 int sessionId) {
3879 if (!client->reserveTimedTrack())
3880 return NULL;
3881
Glenn Kastena0356762012-03-19 10:38:51 -07003882 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08003883 thread, client, streamType, sampleRate, format, channelMask, frameCount,
3884 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08003885}
3886
3887AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003888 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003889 const sp<Client>& client,
3890 audio_stream_type_t streamType,
3891 uint32_t sampleRate,
3892 audio_format_t format,
3893 uint32_t channelMask,
3894 int frameCount,
3895 const sp<IMemory>& sharedBuffer,
3896 int sessionId)
3897 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07003898 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07003899 mQueueHeadInFlight(false),
3900 mTrimQueueHeadOnRelease(false),
John Grossman4ff14ba2012-02-08 16:37:41 -08003901 mTimedSilenceBuffer(NULL),
3902 mTimedSilenceBufferSize(0),
3903 mTimedAudioOutputOnTime(false),
3904 mMediaTimeTransformValid(false)
3905{
3906 LocalClock lc;
3907 mLocalTimeFreq = lc.getLocalFreq();
3908
3909 mLocalTimeToSampleTransform.a_zero = 0;
3910 mLocalTimeToSampleTransform.b_zero = 0;
3911 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3912 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3913 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3914 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07003915
3916 mMediaTimeToSampleTransform.a_zero = 0;
3917 mMediaTimeToSampleTransform.b_zero = 0;
3918 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
3919 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
3920 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
3921 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08003922}
3923
3924AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3925 mClient->releaseTimedTrack();
3926 delete [] mTimedSilenceBuffer;
3927}
3928
3929status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3930 size_t size, sp<IMemory>* buffer) {
3931
3932 Mutex::Autolock _l(mTimedBufferQueueLock);
3933
3934 trimTimedBufferQueue_l();
3935
3936 // lazily initialize the shared memory heap for timed buffers
3937 if (mTimedMemoryDealer == NULL) {
3938 const int kTimedBufferHeapSize = 512 << 10;
3939
3940 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3941 "AudioFlingerTimed");
3942 if (mTimedMemoryDealer == NULL)
3943 return NO_MEMORY;
3944 }
3945
3946 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3947 if (newBuffer == NULL) {
3948 newBuffer = mTimedMemoryDealer->allocate(size);
3949 if (newBuffer == NULL)
3950 return NO_MEMORY;
3951 }
3952
3953 *buffer = newBuffer;
3954 return NO_ERROR;
3955}
3956
3957// caller must hold mTimedBufferQueueLock
3958void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
3959 int64_t mediaTimeNow;
3960 {
3961 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3962 if (!mMediaTimeTransformValid)
3963 return;
3964
3965 int64_t targetTimeNow;
3966 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
3967 ? mCCHelper.getCommonTime(&targetTimeNow)
3968 : mCCHelper.getLocalTime(&targetTimeNow);
3969
3970 if (OK != res)
3971 return;
3972
3973 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
3974 &mediaTimeNow)) {
3975 return;
3976 }
3977 }
3978
3979 size_t trimIndex;
3980 for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
John Grossman9fbdee12012-03-26 17:51:46 -07003981 int64_t frameCount = mTimedBufferQueue[trimIndex].buffer()->size()
3982 / mCblk->frameSize;
3983 int64_t bufEnd;
3984
3985 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
3986 &bufEnd)) {
3987 ALOGE("Failed to convert frame count of %lld to media time duration"
3988 " (scale factor %d/%u) in %s", frameCount,
3989 mMediaTimeToSampleTransform.a_to_b_numer,
3990 mMediaTimeToSampleTransform.a_to_b_denom,
3991 __PRETTY_FUNCTION__);
John Grossman4ff14ba2012-02-08 16:37:41 -08003992 break;
John Grossman9fbdee12012-03-26 17:51:46 -07003993 }
3994 bufEnd += mTimedBufferQueue[trimIndex].pts();
3995
3996 if (bufEnd > mediaTimeNow)
3997 break;
3998
3999 // Is the buffer we want to use in the middle of a mix operation right
4000 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4001 // from the mixer which should be coming back shortly.
4002 if (!trimIndex && mQueueHeadInFlight) {
4003 mTrimQueueHeadOnRelease = true;
4004 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004005 }
4006
John Grossman9fbdee12012-03-26 17:51:46 -07004007 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
4008 if (trimStart < trimIndex) {
4009 mTimedBufferQueue.removeItemsAt(trimStart, trimIndex);
John Grossman4ff14ba2012-02-08 16:37:41 -08004010 }
4011}
4012
4013status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4014 const sp<IMemory>& buffer, int64_t pts) {
4015
4016 {
4017 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4018 if (!mMediaTimeTransformValid)
4019 return INVALID_OPERATION;
4020 }
4021
4022 Mutex::Autolock _l(mTimedBufferQueueLock);
4023
4024 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4025
4026 return NO_ERROR;
4027}
4028
4029status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4030 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4031
4032 ALOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
4033 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4034 target);
4035
4036 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4037 target == TimedAudioTrack::COMMON_TIME)) {
4038 return BAD_VALUE;
4039 }
4040
4041 Mutex::Autolock lock(mMediaTimeTransformLock);
4042 mMediaTimeTransform = xform;
4043 mMediaTimeTransformTarget = target;
4044 mMediaTimeTransformValid = true;
4045
4046 return NO_ERROR;
4047}
4048
4049#define min(a, b) ((a) < (b) ? (a) : (b))
4050
4051// implementation of getNextBuffer for tracks whose buffers have timestamps
4052status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4053 AudioBufferProvider::Buffer* buffer, int64_t pts)
4054{
4055 if (pts == AudioBufferProvider::kInvalidPTS) {
4056 buffer->raw = 0;
4057 buffer->frameCount = 0;
4058 return INVALID_OPERATION;
4059 }
4060
John Grossman4ff14ba2012-02-08 16:37:41 -08004061 Mutex::Autolock _l(mTimedBufferQueueLock);
4062
John Grossman9fbdee12012-03-26 17:51:46 -07004063 ALOG_ASSERT(!mQueueHeadInFlight,
4064 "getNextBuffer called without releaseBuffer!");
4065
John Grossman4ff14ba2012-02-08 16:37:41 -08004066 while (true) {
4067
4068 // if we have no timed buffers, then fail
4069 if (mTimedBufferQueue.isEmpty()) {
4070 buffer->raw = 0;
4071 buffer->frameCount = 0;
4072 return NOT_ENOUGH_DATA;
4073 }
4074
4075 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4076
4077 // calculate the PTS of the head of the timed buffer queue expressed in
4078 // local time
4079 int64_t headLocalPTS;
4080 {
4081 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4082
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004083 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08004084
4085 if (mMediaTimeTransform.a_to_b_denom == 0) {
4086 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07004087 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004088 return NO_ERROR;
4089 }
4090
4091 int64_t transformedPTS;
4092 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4093 &transformedPTS)) {
4094 // the transform failed. this shouldn't happen, but if it does
4095 // then just drop this buffer
4096 ALOGW("timedGetNextBuffer transform failed");
4097 buffer->raw = 0;
4098 buffer->frameCount = 0;
4099 mTimedBufferQueue.removeAt(0);
4100 return NO_ERROR;
4101 }
4102
4103 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
4104 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
4105 &headLocalPTS)) {
4106 buffer->raw = 0;
4107 buffer->frameCount = 0;
4108 return INVALID_OPERATION;
4109 }
4110 } else {
4111 headLocalPTS = transformedPTS;
4112 }
4113 }
4114
4115 // adjust the head buffer's PTS to reflect the portion of the head buffer
4116 // that has already been consumed
4117 int64_t effectivePTS = headLocalPTS +
4118 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4119
4120 // Calculate the delta in samples between the head of the input buffer
4121 // queue and the start of the next output buffer that will be written.
4122 // If the transformation fails because of over or underflow, it means
4123 // that the sample's position in the output stream is so far out of
4124 // whack that it should just be dropped.
4125 int64_t sampleDelta;
4126 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4127 ALOGV("*** head buffer is too far from PTS: dropped buffer");
4128 mTimedBufferQueue.removeAt(0);
4129 continue;
4130 }
4131 if (!mLocalTimeToSampleTransform.doForwardTransform(
4132 (effectivePTS - pts) << 32, &sampleDelta)) {
4133 ALOGV("*** too late during sample rate transform: dropped buffer");
4134 mTimedBufferQueue.removeAt(0);
4135 continue;
4136 }
4137
4138 ALOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
4139 __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
4140 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
4141 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
4142
4143 // if the delta between the ideal placement for the next input sample and
4144 // the current output position is within this threshold, then we will
4145 // concatenate the next input samples to the previous output
4146 const int64_t kSampleContinuityThreshold =
4147 (static_cast<int64_t>(sampleRate()) << 32) / 10;
4148
4149 // if this is the first buffer of audio that we're emitting from this track
4150 // then it should be almost exactly on time.
4151 const int64_t kSampleStartupThreshold = 1LL << 32;
4152
4153 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
4154 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
4155 // the next input is close enough to being on time, so concatenate it
4156 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07004157 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004158
4159 ALOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4160 return NO_ERROR;
4161 } else if (sampleDelta > 0) {
4162 // the gap between the current output position and the proper start of
4163 // the next input sample is too big, so fill it with silence
4164 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4165
John Grossman9fbdee12012-03-26 17:51:46 -07004166 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004167 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4168 return NO_ERROR;
4169 } else {
4170 // the next input sample is late
4171 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4172 size_t onTimeSamplePosition =
4173 head.position() + lateFrames * mCblk->frameSize;
4174
4175 if (onTimeSamplePosition > head.buffer()->size()) {
4176 // all the remaining samples in the head are too late, so
4177 // drop it and move on
4178 ALOGV("*** too late: dropped buffer");
4179 mTimedBufferQueue.removeAt(0);
4180 continue;
4181 } else {
4182 // skip over the late samples
4183 head.setPosition(onTimeSamplePosition);
4184
4185 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07004186 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004187
4188 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4189 return NO_ERROR;
4190 }
4191 }
4192 }
4193}
4194
4195// Yield samples from the timed buffer queue head up to the given output
4196// buffer's capacity.
4197//
4198// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004199void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004200 AudioBufferProvider::Buffer* buffer) {
4201
4202 const TimedBuffer& head = mTimedBufferQueue[0];
4203
4204 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4205 head.position());
4206
4207 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4208 mCblk->frameSize);
4209 size_t framesRequested = buffer->frameCount;
4210 buffer->frameCount = min(framesLeftInHead, framesRequested);
4211
John Grossman9fbdee12012-03-26 17:51:46 -07004212 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08004213 mTimedAudioOutputOnTime = true;
4214}
4215
4216// Yield samples of silence up to the given output buffer's capacity
4217//
4218// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004219void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004220 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4221
4222 // lazily allocate a buffer filled with silence
4223 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4224 delete [] mTimedSilenceBuffer;
4225 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4226 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4227 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4228 }
4229
4230 buffer->raw = mTimedSilenceBuffer;
4231 size_t framesRequested = buffer->frameCount;
4232 buffer->frameCount = min(numFrames, framesRequested);
4233
4234 mTimedAudioOutputOnTime = false;
4235}
4236
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004237// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004238void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4239 AudioBufferProvider::Buffer* buffer) {
4240
4241 Mutex::Autolock _l(mTimedBufferQueueLock);
4242
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004243 // If the buffer which was just released is part of the buffer at the head
4244 // of the queue, be sure to update the amt of the buffer which has been
4245 // consumed. If the buffer being returned is not part of the head of the
4246 // queue, its either because the buffer is part of the silence buffer, or
4247 // because the head of the timed queue was trimmed after the mixer called
4248 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07004249 if (buffer->raw == mTimedSilenceBuffer) {
4250 ALOG_ASSERT(!mQueueHeadInFlight,
4251 "Queue head in flight during release of silence buffer!");
4252 goto done;
4253 }
4254
4255 ALOG_ASSERT(mQueueHeadInFlight,
4256 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
4257 " head in flight.");
4258
4259 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004260 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004261
4262 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07004263 void* end = reinterpret_cast<void*>(
4264 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
4265 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004266
John Grossman9fbdee12012-03-26 17:51:46 -07004267 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
4268 "released buffer not within the head of the timed buffer"
4269 " queue; qHead = [%p, %p], released buffer = %p",
4270 start, end, buffer->raw);
4271
4272 head.setPosition(head.position() +
4273 (buffer->frameCount * mCblk->frameSize));
4274 mQueueHeadInFlight = false;
4275
4276 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
4277 || mTrimQueueHeadOnRelease) {
4278 mTimedBufferQueue.removeAt(0);
4279 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004280 }
John Grossman9fbdee12012-03-26 17:51:46 -07004281 } else {
4282 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
4283 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08004284 }
4285
John Grossman9fbdee12012-03-26 17:51:46 -07004286done:
John Grossman4ff14ba2012-02-08 16:37:41 -08004287 buffer->raw = 0;
4288 buffer->frameCount = 0;
4289}
4290
4291uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4292 Mutex::Autolock _l(mTimedBufferQueueLock);
4293
4294 uint32_t frames = 0;
4295 for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4296 const TimedBuffer& tb = mTimedBufferQueue[i];
4297 frames += (tb.buffer()->size() - tb.position()) / mCblk->frameSize;
4298 }
4299
4300 return frames;
4301}
4302
4303AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4304 : mPTS(0), mPosition(0) {}
4305
4306AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4307 const sp<IMemory>& buffer, int64_t pts)
4308 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4309
Mathias Agopian65ab4712010-07-14 17:59:35 -07004310// ----------------------------------------------------------------------------
4311
4312// RecordTrack constructor must be called with AudioFlinger::mLock held
4313AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004314 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004315 const sp<Client>& client,
4316 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004317 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004318 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004319 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004320 int sessionId)
4321 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004322 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004323 mOverflow(false)
4324{
4325 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004326 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
4327 if (format == AUDIO_FORMAT_PCM_16_BIT) {
4328 mCblk->frameSize = mChannelCount * sizeof(int16_t);
4329 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
4330 mCblk->frameSize = mChannelCount * sizeof(int8_t);
4331 } else {
4332 mCblk->frameSize = sizeof(int8_t);
4333 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004334 }
4335}
4336
4337AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4338{
4339 sp<ThreadBase> thread = mThread.promote();
4340 if (thread != 0) {
4341 AudioSystem::releaseInput(thread->id());
4342 }
4343}
4344
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004345// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004346status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004347{
4348 audio_track_cblk_t* cblk = this->cblk();
4349 uint32_t framesAvail;
4350 uint32_t framesReq = buffer->frameCount;
4351
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004352 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004353 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004354 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004355 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004356 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004357 }
4358
4359 framesAvail = cblk->framesAvailable_l();
4360
Glenn Kastenf6b16782011-12-15 09:51:17 -08004361 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004362 uint32_t s = cblk->server;
4363 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4364
4365 if (framesReq > framesAvail) {
4366 framesReq = framesAvail;
4367 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004368 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004369 framesReq = bufferEnd - s;
4370 }
4371
4372 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004373 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004374
4375 buffer->frameCount = framesReq;
4376 return NO_ERROR;
4377 }
4378
4379getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004380 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004381 buffer->frameCount = 0;
4382 return NOT_ENOUGH_DATA;
4383}
4384
Eric Laurenta011e352012-03-29 15:51:43 -07004385status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid,
4386 AudioSystem::sync_event_t event,
4387 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004388{
4389 sp<ThreadBase> thread = mThread.promote();
4390 if (thread != 0) {
4391 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurenta011e352012-03-29 15:51:43 -07004392 return recordThread->start(this, tid, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004393 } else {
4394 return BAD_VALUE;
4395 }
4396}
4397
4398void AudioFlinger::RecordThread::RecordTrack::stop()
4399{
4400 sp<ThreadBase> thread = mThread.promote();
4401 if (thread != 0) {
4402 RecordThread *recordThread = (RecordThread *)thread.get();
4403 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004404 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08004405 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07004406 // read from buffer
4407 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004408 }
4409}
4410
4411void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4412{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004413 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004414 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004415 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004416 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004417 mSessionId,
4418 mFrameCount,
4419 mState,
4420 mCblk->sampleRate,
4421 mCblk->server,
4422 mCblk->user);
4423}
4424
4425
4426// ----------------------------------------------------------------------------
4427
4428AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004429 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004430 DuplicatingThread *sourceThread,
4431 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004432 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004433 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004434 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07004435 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
4436 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004437 mActive(false), mSourceThread(sourceThread)
4438{
4439
Mathias Agopian65ab4712010-07-14 17:59:35 -07004440 if (mCblk != NULL) {
4441 mCblk->flags |= CBLK_DIRECTION_OUT;
4442 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004443 mOutBuffer.frameCount = 0;
4444 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01004445 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004446 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4447 mCblk, mBuffer, mCblk->buffers,
4448 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004449 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004450 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004451 }
4452}
4453
4454AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4455{
4456 clearBufferQueue();
4457}
4458
Eric Laurenta011e352012-03-29 15:51:43 -07004459status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid,
4460 AudioSystem::sync_event_t event,
4461 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004462{
Eric Laurenta011e352012-03-29 15:51:43 -07004463 status_t status = Track::start(tid, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004464 if (status != NO_ERROR) {
4465 return status;
4466 }
4467
4468 mActive = true;
4469 mRetryCount = 127;
4470 return status;
4471}
4472
4473void AudioFlinger::PlaybackThread::OutputTrack::stop()
4474{
4475 Track::stop();
4476 clearBufferQueue();
4477 mOutBuffer.frameCount = 0;
4478 mActive = false;
4479}
4480
4481bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4482{
4483 Buffer *pInBuffer;
4484 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004485 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004486 bool outputBufferFull = false;
4487 inBuffer.frameCount = frames;
4488 inBuffer.i16 = data;
4489
4490 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4491
4492 if (!mActive && frames != 0) {
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004493 start(0);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004494 sp<ThreadBase> thread = mThread.promote();
4495 if (thread != 0) {
4496 MixerThread *mixerThread = (MixerThread *)thread.get();
4497 if (mCblk->frameCount > frames){
4498 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4499 uint32_t startFrames = (mCblk->frameCount - frames);
4500 pInBuffer = new Buffer;
4501 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4502 pInBuffer->frameCount = startFrames;
4503 pInBuffer->i16 = pInBuffer->mBuffer;
4504 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4505 mBufferQueue.add(pInBuffer);
4506 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004507 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004508 }
4509 }
4510 }
4511 }
4512
4513 while (waitTimeLeftMs) {
4514 // First write pending buffers, then new data
4515 if (mBufferQueue.size()) {
4516 pInBuffer = mBufferQueue.itemAt(0);
4517 } else {
4518 pInBuffer = &inBuffer;
4519 }
4520
4521 if (pInBuffer->frameCount == 0) {
4522 break;
4523 }
4524
4525 if (mOutBuffer.frameCount == 0) {
4526 mOutBuffer.frameCount = pInBuffer->frameCount;
4527 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08004528 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01004529 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004530 outputBufferFull = true;
4531 break;
4532 }
4533 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4534 if (waitTimeLeftMs >= waitTimeMs) {
4535 waitTimeLeftMs -= waitTimeMs;
4536 } else {
4537 waitTimeLeftMs = 0;
4538 }
4539 }
4540
4541 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4542 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4543 mCblk->stepUser(outFrames);
4544 pInBuffer->frameCount -= outFrames;
4545 pInBuffer->i16 += outFrames * channelCount;
4546 mOutBuffer.frameCount -= outFrames;
4547 mOutBuffer.i16 += outFrames * channelCount;
4548
4549 if (pInBuffer->frameCount == 0) {
4550 if (mBufferQueue.size()) {
4551 mBufferQueue.removeAt(0);
4552 delete [] pInBuffer->mBuffer;
4553 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01004554 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004555 } else {
4556 break;
4557 }
4558 }
4559 }
4560
4561 // If we could not write all frames, allocate a buffer and queue it for next time.
4562 if (inBuffer.frameCount) {
4563 sp<ThreadBase> thread = mThread.promote();
4564 if (thread != 0 && !thread->standby()) {
4565 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4566 pInBuffer = new Buffer;
4567 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4568 pInBuffer->frameCount = inBuffer.frameCount;
4569 pInBuffer->i16 = pInBuffer->mBuffer;
4570 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4571 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01004572 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004573 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004574 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004575 }
4576 }
4577 }
4578
4579 // Calling write() with a 0 length buffer, means that no more data will be written:
4580 // If no more buffers are pending, fill output track buffer to make sure it is started
4581 // by output mixer.
4582 if (frames == 0 && mBufferQueue.size() == 0) {
4583 if (mCblk->user < mCblk->frameCount) {
4584 frames = mCblk->frameCount - mCblk->user;
4585 pInBuffer = new Buffer;
4586 pInBuffer->mBuffer = new int16_t[frames * channelCount];
4587 pInBuffer->frameCount = frames;
4588 pInBuffer->i16 = pInBuffer->mBuffer;
4589 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4590 mBufferQueue.add(pInBuffer);
4591 } else if (mActive) {
4592 stop();
4593 }
4594 }
4595
4596 return outputBufferFull;
4597}
4598
4599status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4600{
4601 int active;
4602 status_t result;
4603 audio_track_cblk_t* cblk = mCblk;
4604 uint32_t framesReq = buffer->frameCount;
4605
Steve Block3856b092011-10-20 11:56:00 +01004606// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004607 buffer->frameCount = 0;
4608
4609 uint32_t framesAvail = cblk->framesAvailable();
4610
4611
4612 if (framesAvail == 0) {
4613 Mutex::Autolock _l(cblk->lock);
4614 goto start_loop_here;
4615 while (framesAvail == 0) {
4616 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004617 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004618 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004619 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004620 }
4621 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4622 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004623 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004624 }
4625 // read the server count again
4626 start_loop_here:
4627 framesAvail = cblk->framesAvailable_l();
4628 }
4629 }
4630
4631// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004632// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004633// }
4634
4635 if (framesReq > framesAvail) {
4636 framesReq = framesAvail;
4637 }
4638
4639 uint32_t u = cblk->user;
4640 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4641
Marco Nelissena1472d92012-03-30 14:36:54 -07004642 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004643 framesReq = bufferEnd - u;
4644 }
4645
4646 buffer->frameCount = framesReq;
4647 buffer->raw = (void *)cblk->buffer(u);
4648 return NO_ERROR;
4649}
4650
4651
4652void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4653{
4654 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004655
4656 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004657 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004658 delete [] pBuffer->mBuffer;
4659 delete pBuffer;
4660 }
4661 mBufferQueue.clear();
4662}
4663
4664// ----------------------------------------------------------------------------
4665
4666AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4667 : RefBase(),
4668 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08004669 // 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 -07004670 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08004671 mPid(pid),
4672 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004673{
4674 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4675}
4676
4677// Client destructor must be called with AudioFlinger::mLock held
4678AudioFlinger::Client::~Client()
4679{
4680 mAudioFlinger->removeClient_l(mPid);
4681}
4682
Glenn Kasten435dbe62012-01-30 10:15:48 -08004683sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004684{
4685 return mMemoryDealer;
4686}
4687
John Grossman4ff14ba2012-02-08 16:37:41 -08004688// Reserve one of the limited slots for a timed audio track associated
4689// with this client
4690bool AudioFlinger::Client::reserveTimedTrack()
4691{
4692 const int kMaxTimedTracksPerClient = 4;
4693
4694 Mutex::Autolock _l(mTimedTrackLock);
4695
4696 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4697 ALOGW("can not create timed track - pid %d has exceeded the limit",
4698 mPid);
4699 return false;
4700 }
4701
4702 mTimedTrackCount++;
4703 return true;
4704}
4705
4706// Release a slot for a timed audio track
4707void AudioFlinger::Client::releaseTimedTrack()
4708{
4709 Mutex::Autolock _l(mTimedTrackLock);
4710 mTimedTrackCount--;
4711}
4712
Mathias Agopian65ab4712010-07-14 17:59:35 -07004713// ----------------------------------------------------------------------------
4714
4715AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4716 const sp<IAudioFlingerClient>& client,
4717 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004718 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004719{
4720}
4721
4722AudioFlinger::NotificationClient::~NotificationClient()
4723{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004724}
4725
4726void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4727{
4728 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08004729 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004730}
4731
4732// ----------------------------------------------------------------------------
4733
4734AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4735 : BnAudioTrack(),
4736 mTrack(track)
4737{
4738}
4739
4740AudioFlinger::TrackHandle::~TrackHandle() {
4741 // just stop the track on deletion, associated resources
4742 // will be freed from the main thread once all pending buffers have
4743 // been played. Unless it's not in the active track list, in which
4744 // case we free everything now...
4745 mTrack->destroy();
4746}
4747
Glenn Kasten90716c52012-01-26 13:40:12 -08004748sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4749 return mTrack->getCblk();
4750}
4751
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004752status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4753 return mTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004754}
4755
4756void AudioFlinger::TrackHandle::stop() {
4757 mTrack->stop();
4758}
4759
4760void AudioFlinger::TrackHandle::flush() {
4761 mTrack->flush();
4762}
4763
4764void AudioFlinger::TrackHandle::mute(bool e) {
4765 mTrack->mute(e);
4766}
4767
4768void AudioFlinger::TrackHandle::pause() {
4769 mTrack->pause();
4770}
4771
Mathias Agopian65ab4712010-07-14 17:59:35 -07004772status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4773{
4774 return mTrack->attachAuxEffect(EffectId);
4775}
4776
John Grossman4ff14ba2012-02-08 16:37:41 -08004777status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4778 sp<IMemory>* buffer) {
4779 if (!mTrack->isTimedTrack())
4780 return INVALID_OPERATION;
4781
4782 PlaybackThread::TimedTrack* tt =
4783 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4784 return tt->allocateTimedBuffer(size, buffer);
4785}
4786
4787status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4788 int64_t pts) {
4789 if (!mTrack->isTimedTrack())
4790 return INVALID_OPERATION;
4791
4792 PlaybackThread::TimedTrack* tt =
4793 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4794 return tt->queueTimedBuffer(buffer, pts);
4795}
4796
4797status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4798 const LinearTransform& xform, int target) {
4799
4800 if (!mTrack->isTimedTrack())
4801 return INVALID_OPERATION;
4802
4803 PlaybackThread::TimedTrack* tt =
4804 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4805 return tt->setMediaTimeTransform(
4806 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4807}
4808
Mathias Agopian65ab4712010-07-14 17:59:35 -07004809status_t AudioFlinger::TrackHandle::onTransact(
4810 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4811{
4812 return BnAudioTrack::onTransact(code, data, reply, flags);
4813}
4814
4815// ----------------------------------------------------------------------------
4816
4817sp<IAudioRecord> AudioFlinger::openRecord(
4818 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004819 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004820 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004821 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004822 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004823 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08004824 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004825 int *sessionId,
4826 status_t *status)
4827{
4828 sp<RecordThread::RecordTrack> recordTrack;
4829 sp<RecordHandle> recordHandle;
4830 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004831 status_t lStatus;
4832 RecordThread *thread;
4833 size_t inFrameCount;
4834 int lSessionId;
4835
4836 // check calling permissions
4837 if (!recordingAllowed()) {
4838 lStatus = PERMISSION_DENIED;
4839 goto Exit;
4840 }
4841
4842 // add client to list
4843 { // scope for mLock
4844 Mutex::Autolock _l(mLock);
4845 thread = checkRecordThread_l(input);
4846 if (thread == NULL) {
4847 lStatus = BAD_VALUE;
4848 goto Exit;
4849 }
4850
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004851 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004852
4853 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004854 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004855 lSessionId = *sessionId;
4856 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004857 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004858 if (sessionId != NULL) {
4859 *sessionId = lSessionId;
4860 }
4861 }
4862 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004863 recordTrack = thread->createRecordTrack_l(client,
4864 sampleRate,
4865 format,
4866 channelMask,
4867 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004868 lSessionId,
4869 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004870 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004871 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004872 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4873 // destructor is called by the TrackBase destructor with mLock held
4874 client.clear();
4875 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004876 goto Exit;
4877 }
4878
4879 // return to handle to client
4880 recordHandle = new RecordHandle(recordTrack);
4881 lStatus = NO_ERROR;
4882
4883Exit:
4884 if (status) {
4885 *status = lStatus;
4886 }
4887 return recordHandle;
4888}
4889
4890// ----------------------------------------------------------------------------
4891
4892AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4893 : BnAudioRecord(),
4894 mRecordTrack(recordTrack)
4895{
4896}
4897
4898AudioFlinger::RecordHandle::~RecordHandle() {
4899 stop();
4900}
4901
Glenn Kasten90716c52012-01-26 13:40:12 -08004902sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4903 return mRecordTrack->getCblk();
4904}
4905
Eric Laurenta011e352012-03-29 15:51:43 -07004906status_t AudioFlinger::RecordHandle::start(pid_t tid, int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01004907 ALOGV("RecordHandle::start()");
Eric Laurenta011e352012-03-29 15:51:43 -07004908 return mRecordTrack->start(tid, (AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004909}
4910
4911void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004912 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004913 mRecordTrack->stop();
4914}
4915
Mathias Agopian65ab4712010-07-14 17:59:35 -07004916status_t AudioFlinger::RecordHandle::onTransact(
4917 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4918{
4919 return BnAudioRecord::onTransact(code, data, reply, flags);
4920}
4921
4922// ----------------------------------------------------------------------------
4923
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004924AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4925 AudioStreamIn *input,
4926 uint32_t sampleRate,
4927 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004928 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004929 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004930 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004931 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4932 // mRsmpInIndex and mInputBytes set by readInputParameters()
4933 mReqChannelCount(popcount(channels)),
4934 mReqSampleRate(sampleRate)
4935 // mBytesRead is only meaningful while active, and so is cleared in start()
4936 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004937{
Glenn Kasten480b4682012-02-28 12:30:08 -08004938 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07004939
Mathias Agopian65ab4712010-07-14 17:59:35 -07004940 readInputParameters();
4941}
4942
4943
4944AudioFlinger::RecordThread::~RecordThread()
4945{
4946 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004947 delete mResampler;
4948 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004949}
4950
4951void AudioFlinger::RecordThread::onFirstRef()
4952{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004953 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004954}
4955
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004956status_t AudioFlinger::RecordThread::readyToRun()
4957{
4958 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004959 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004960 return status;
4961}
4962
Mathias Agopian65ab4712010-07-14 17:59:35 -07004963bool AudioFlinger::RecordThread::threadLoop()
4964{
4965 AudioBufferProvider::Buffer buffer;
4966 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004967 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004968
Eric Laurent44d98482010-09-30 16:12:31 -07004969 nsecs_t lastWarning = 0;
4970
Eric Laurentfeb0db62011-07-22 09:04:31 -07004971 acquireWakeLock();
4972
Mathias Agopian65ab4712010-07-14 17:59:35 -07004973 // start recording
4974 while (!exitPending()) {
4975
4976 processConfigEvents();
4977
4978 { // scope for mLock
4979 Mutex::Autolock _l(mLock);
4980 checkForNewParameters_l();
4981 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4982 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004983 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004984 mStandby = true;
4985 }
4986
4987 if (exitPending()) break;
4988
Eric Laurentfeb0db62011-07-22 09:04:31 -07004989 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004990 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004991 // go to sleep
4992 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004993 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004994 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004995 continue;
4996 }
4997 if (mActiveTrack != 0) {
4998 if (mActiveTrack->mState == TrackBase::PAUSING) {
4999 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005000 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005001 mStandby = true;
5002 }
5003 mActiveTrack.clear();
5004 mStartStopCond.broadcast();
5005 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5006 if (mReqChannelCount != mActiveTrack->channelCount()) {
5007 mActiveTrack.clear();
5008 mStartStopCond.broadcast();
5009 } else if (mBytesRead != 0) {
5010 // record start succeeds only if first read from audio input
5011 // succeeds
5012 if (mBytesRead > 0) {
5013 mActiveTrack->mState = TrackBase::ACTIVE;
5014 } else {
5015 mActiveTrack.clear();
5016 }
5017 mStartStopCond.broadcast();
5018 }
5019 mStandby = false;
5020 }
5021 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005022 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005023 }
5024
5025 if (mActiveTrack != 0) {
5026 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5027 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005028 unlockEffectChains(effectChains);
5029 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005030 continue;
5031 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005032 for (size_t i = 0; i < effectChains.size(); i ++) {
5033 effectChains[i]->process_l();
5034 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005035
Mathias Agopian65ab4712010-07-14 17:59:35 -07005036 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005037 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005038 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08005039 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005040 // no resampling
5041 while (framesOut) {
5042 size_t framesIn = mFrameCount - mRsmpInIndex;
5043 if (framesIn) {
5044 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
5045 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
5046 if (framesIn > framesOut)
5047 framesIn = framesOut;
5048 mRsmpInIndex += framesIn;
5049 framesOut -= framesIn;
5050 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07005051 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005052 memcpy(dst, src, framesIn * mFrameSize);
5053 } else {
5054 int16_t *src16 = (int16_t *)src;
5055 int16_t *dst16 = (int16_t *)dst;
5056 if (mChannelCount == 1) {
5057 while (framesIn--) {
5058 *dst16++ = *src16;
5059 *dst16++ = *src16++;
5060 }
5061 } else {
5062 while (framesIn--) {
5063 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
5064 src16 += 2;
5065 }
5066 }
5067 }
5068 }
5069 if (framesOut && mFrameCount == mRsmpInIndex) {
5070 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005071 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005072 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005073 framesOut = 0;
5074 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07005075 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005076 mRsmpInIndex = 0;
5077 }
5078 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005079 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005080 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5081 // Force input into standby so that it tries to
5082 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005083 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005084 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005085 }
5086 mRsmpInIndex = mFrameCount;
5087 framesOut = 0;
5088 buffer.frameCount = 0;
5089 }
5090 }
5091 }
5092 } else {
5093 // resampling
5094
5095 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
5096 // alter output frame count as if we were expecting stereo samples
5097 if (mChannelCount == 1 && mReqChannelCount == 1) {
5098 framesOut >>= 1;
5099 }
5100 mResampler->resample(mRsmpOutBuffer, framesOut, this);
5101 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
5102 // are 32 bit aligned which should be always true.
5103 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005104 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005105 // the resampler always outputs stereo samples: do post stereo to mono conversion
5106 int16_t *src = (int16_t *)mRsmpOutBuffer;
5107 int16_t *dst = buffer.i16;
5108 while (framesOut--) {
5109 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
5110 src += 2;
5111 }
5112 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005113 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005114 }
5115
5116 }
Eric Laurenta011e352012-03-29 15:51:43 -07005117 if (mFramestoDrop == 0) {
5118 mActiveTrack->releaseBuffer(&buffer);
5119 } else {
5120 if (mFramestoDrop > 0) {
5121 mFramestoDrop -= buffer.frameCount;
5122 if (mFramestoDrop < 0) {
5123 mFramestoDrop = 0;
5124 }
5125 }
5126 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005127 mActiveTrack->overflow();
5128 }
5129 // client isn't retrieving buffers fast enough
5130 else {
Eric Laurent44d98482010-09-30 16:12:31 -07005131 if (!mActiveTrack->setOverflow()) {
5132 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08005133 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005134 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07005135 lastWarning = now;
5136 }
5137 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005138 // Release the processor for a while before asking for a new buffer.
5139 // This will give the application more chance to read from the buffer and
5140 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005141 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005142 }
5143 }
Eric Laurentec437d82011-07-26 20:54:46 -07005144 // enable changes in effect chain
5145 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005146 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005147 }
5148
5149 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005150 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005151 }
5152 mActiveTrack.clear();
5153
5154 mStartStopCond.broadcast();
5155
Eric Laurentfeb0db62011-07-22 09:04:31 -07005156 releaseWakeLock();
5157
Steve Block3856b092011-10-20 11:56:00 +01005158 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005159 return false;
5160}
5161
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005162
5163sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5164 const sp<AudioFlinger::Client>& client,
5165 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005166 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005167 int channelMask,
5168 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005169 int sessionId,
5170 status_t *status)
5171{
5172 sp<RecordTrack> track;
5173 status_t lStatus;
5174
5175 lStatus = initCheck();
5176 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005177 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005178 goto Exit;
5179 }
5180
5181 { // scope for mLock
5182 Mutex::Autolock _l(mLock);
5183
5184 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005185 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005186
Glenn Kasten7378ca52012-01-20 13:44:40 -08005187 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005188 lStatus = NO_MEMORY;
5189 goto Exit;
5190 }
5191
5192 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005193 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5194 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005195 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005196 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5197 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005198 }
5199 lStatus = NO_ERROR;
5200
5201Exit:
5202 if (status) {
5203 *status = lStatus;
5204 }
5205 return track;
5206}
5207
Eric Laurenta011e352012-03-29 15:51:43 -07005208status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5209 pid_t tid, AudioSystem::sync_event_t event,
5210 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005211{
Eric Laurenta011e352012-03-29 15:51:43 -07005212 ALOGV("RecordThread::start tid=%d, event %d, triggerSession %d", tid, event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005213 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005214 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07005215
5216 if (event == AudioSystem::SYNC_EVENT_NONE) {
5217 mSyncStartEvent.clear();
5218 mFramestoDrop = 0;
5219 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
5220 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
5221 triggerSession,
5222 recordTrack->sessionId(),
5223 syncStartEventCallback,
5224 this);
5225 mFramestoDrop = -1;
5226 }
5227
Mathias Agopian65ab4712010-07-14 17:59:35 -07005228 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005229 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005230 if (mActiveTrack != 0) {
5231 if (recordTrack != mActiveTrack.get()) {
5232 status = -EBUSY;
5233 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5234 mActiveTrack->mState = TrackBase::ACTIVE;
5235 }
5236 return status;
5237 }
5238
5239 recordTrack->mState = TrackBase::IDLE;
5240 mActiveTrack = recordTrack;
5241 mLock.unlock();
5242 status_t status = AudioSystem::startInput(mId);
5243 mLock.lock();
5244 if (status != NO_ERROR) {
5245 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07005246 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005247 return status;
5248 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005249 mRsmpInIndex = mFrameCount;
5250 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005251 if (mResampler != NULL) {
5252 mResampler->reset();
5253 }
5254 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005255 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005256 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005257 mWaitWorkCV.signal();
5258 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005259 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005260 mActiveTrack.clear();
5261 status = INVALID_OPERATION;
5262 goto startError;
5263 }
5264 mStartStopCond.wait(mLock);
5265 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005266 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005267 status = BAD_VALUE;
5268 goto startError;
5269 }
Steve Block3856b092011-10-20 11:56:00 +01005270 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005271 return status;
5272 }
5273startError:
5274 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07005275 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005276 return status;
5277}
5278
Eric Laurenta011e352012-03-29 15:51:43 -07005279void AudioFlinger::RecordThread::clearSyncStartEvent()
5280{
5281 if (mSyncStartEvent != 0) {
5282 mSyncStartEvent->cancel();
5283 }
5284 mSyncStartEvent.clear();
5285}
5286
5287void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5288{
5289 sp<SyncEvent> strongEvent = event.promote();
5290
5291 if (strongEvent != 0) {
5292 RecordThread *me = (RecordThread *)strongEvent->cookie();
5293 me->handleSyncStartEvent(strongEvent);
5294 }
5295}
5296
5297void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
5298{
5299 ALOGV("handleSyncStartEvent() mActiveTrack %p session %d event->listenerSession() %d",
5300 mActiveTrack.get(),
5301 mActiveTrack.get() ? mActiveTrack->sessionId() : 0,
5302 event->listenerSession());
5303
5304 if (mActiveTrack != 0 &&
5305 event == mSyncStartEvent) {
5306 // TODO: use actual buffer filling status instead of 2 buffers when info is available
5307 // from audio HAL
5308 mFramestoDrop = mFrameCount * 2;
5309 mSyncStartEvent.clear();
5310 }
5311}
5312
Mathias Agopian65ab4712010-07-14 17:59:35 -07005313void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005314 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005315 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005316 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005317 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005318 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5319 mActiveTrack->mState = TrackBase::PAUSING;
5320 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005321 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005322 return;
5323 }
5324 mStartStopCond.wait(mLock);
5325 // if we have been restarted, recordTrack == mActiveTrack.get() here
5326 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5327 mLock.unlock();
5328 AudioSystem::stopInput(mId);
5329 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005330 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005331 }
5332 }
5333 }
5334}
5335
Eric Laurenta011e352012-03-29 15:51:43 -07005336bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
5337{
5338 return false;
5339}
5340
5341status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
5342{
5343 if (!isValidSyncEvent(event)) {
5344 return BAD_VALUE;
5345 }
5346
5347 Mutex::Autolock _l(mLock);
5348
5349 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
5350 mTrack->setSyncEvent(event);
5351 return NO_ERROR;
5352 }
5353 return NAME_NOT_FOUND;
5354}
5355
Mathias Agopian65ab4712010-07-14 17:59:35 -07005356status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5357{
5358 const size_t SIZE = 256;
5359 char buffer[SIZE];
5360 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005361
5362 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5363 result.append(buffer);
5364
5365 if (mActiveTrack != 0) {
5366 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005367 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005368 mActiveTrack->dump(buffer, SIZE);
5369 result.append(buffer);
5370
5371 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5372 result.append(buffer);
5373 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5374 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005375 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005376 result.append(buffer);
5377 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5378 result.append(buffer);
5379 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5380 result.append(buffer);
5381
5382
5383 } else {
5384 result.append("No record client\n");
5385 }
5386 write(fd, result.string(), result.size());
5387
5388 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005389 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005390
5391 return NO_ERROR;
5392}
5393
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005394// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005395status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005396{
5397 size_t framesReq = buffer->frameCount;
5398 size_t framesReady = mFrameCount - mRsmpInIndex;
5399 int channelCount;
5400
5401 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005402 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005403 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005404 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005405 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5406 // Force input into standby so that it tries to
5407 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005408 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005409 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005410 }
Glenn Kastene0feee32011-12-13 11:53:26 -08005411 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005412 buffer->frameCount = 0;
5413 return NOT_ENOUGH_DATA;
5414 }
5415 mRsmpInIndex = 0;
5416 framesReady = mFrameCount;
5417 }
5418
5419 if (framesReq > framesReady) {
5420 framesReq = framesReady;
5421 }
5422
5423 if (mChannelCount == 1 && mReqChannelCount == 2) {
5424 channelCount = 1;
5425 } else {
5426 channelCount = 2;
5427 }
5428 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5429 buffer->frameCount = framesReq;
5430 return NO_ERROR;
5431}
5432
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005433// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07005434void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5435{
5436 mRsmpInIndex += buffer->frameCount;
5437 buffer->frameCount = 0;
5438}
5439
5440bool AudioFlinger::RecordThread::checkForNewParameters_l()
5441{
5442 bool reconfig = false;
5443
5444 while (!mNewParameters.isEmpty()) {
5445 status_t status = NO_ERROR;
5446 String8 keyValuePair = mNewParameters[0];
5447 AudioParameter param = AudioParameter(keyValuePair);
5448 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08005449 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005450 int reqSamplingRate = mReqSampleRate;
5451 int reqChannelCount = mReqChannelCount;
5452
5453 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5454 reqSamplingRate = value;
5455 reconfig = true;
5456 }
5457 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08005458 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005459 reconfig = true;
5460 }
5461 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005462 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005463 reconfig = true;
5464 }
5465 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5466 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08005467 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005468 // if frame count is changed after track creation
5469 if (mActiveTrack != 0) {
5470 status = INVALID_OPERATION;
5471 } else {
5472 reconfig = true;
5473 }
5474 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005475 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5476 // forward device change to effects that have requested to be
5477 // aware of attached audio device.
5478 for (size_t i = 0; i < mEffectChains.size(); i++) {
5479 mEffectChains[i]->setDevice_l(value);
5480 }
5481 // store input device and output device but do not forward output device to audio HAL.
5482 // Note that status is ignored by the caller for output device
5483 // (see AudioFlinger::setParameters()
5484 if (value & AUDIO_DEVICE_OUT_ALL) {
5485 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5486 status = BAD_VALUE;
5487 } else {
5488 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07005489 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5490 if (mTrack != NULL) {
5491 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005492 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005493 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5494 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5495 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005496 }
5497 mDevice |= (uint32_t)value;
5498 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005499 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005500 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005501 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005502 mInput->stream->common.standby(&mInput->stream->common);
5503 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5504 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005505 }
5506 if (reconfig) {
5507 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005508 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005509 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005510 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08005511 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
5512 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005513 status = NO_ERROR;
5514 }
5515 if (status == NO_ERROR) {
5516 readInputParameters();
5517 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5518 }
5519 }
5520 }
5521
5522 mNewParameters.removeAt(0);
5523
5524 mParamStatus = status;
5525 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07005526 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5527 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08005528 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005529 }
5530 return reconfig;
5531}
5532
5533String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5534{
Dima Zavinfce7a472011-04-19 22:30:36 -07005535 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005536 String8 out_s8 = String8();
5537
5538 Mutex::Autolock _l(mLock);
5539 if (initCheck() != NO_ERROR) {
5540 return out_s8;
5541 }
Dima Zavinfce7a472011-04-19 22:30:36 -07005542
Dima Zavin799a70e2011-04-18 16:57:27 -07005543 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07005544 out_s8 = String8(s);
5545 free(s);
5546 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005547}
5548
5549void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5550 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08005551 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005552
5553 switch (event) {
5554 case AudioSystem::INPUT_OPENED:
5555 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005556 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005557 desc.samplingRate = mSampleRate;
5558 desc.format = mFormat;
5559 desc.frameCount = mFrameCount;
5560 desc.latency = 0;
5561 param2 = &desc;
5562 break;
5563
5564 case AudioSystem::INPUT_CLOSED:
5565 default:
5566 break;
5567 }
5568 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5569}
5570
5571void AudioFlinger::RecordThread::readInputParameters()
5572{
Glenn Kastene9dd0172012-01-27 18:08:45 -08005573 delete mRsmpInBuffer;
5574 // mRsmpInBuffer is always assigned a new[] below
5575 delete mRsmpOutBuffer;
5576 mRsmpOutBuffer = NULL;
5577 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08005578 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005579
Dima Zavin799a70e2011-04-18 16:57:27 -07005580 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005581 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5582 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07005583 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08005584 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07005585 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005586 mFrameCount = mInputBytes / mFrameSize;
5587 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5588
Glenn Kasten53d76db2012-03-08 12:32:47 -08005589 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005590 {
5591 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005592 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5593 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005594 if (mChannelCount == 1 && mReqChannelCount == 2) {
5595 channelCount = 1;
5596 } else {
5597 channelCount = 2;
5598 }
5599 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5600 mResampler->setSampleRate(mSampleRate);
5601 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5602 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5603
5604 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5605 if (mChannelCount == 1 && mReqChannelCount == 1) {
5606 mFrameCount >>= 1;
5607 }
5608
5609 }
5610 mRsmpInIndex = mFrameCount;
5611}
5612
5613unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5614{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005615 Mutex::Autolock _l(mLock);
5616 if (initCheck() != NO_ERROR) {
5617 return 0;
5618 }
5619
Dima Zavin799a70e2011-04-18 16:57:27 -07005620 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005621}
5622
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005623uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5624{
5625 Mutex::Autolock _l(mLock);
5626 uint32_t result = 0;
5627 if (getEffectChain_l(sessionId) != 0) {
5628 result = EFFECT_SESSION;
5629 }
5630
5631 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5632 result |= TRACK_SESSION;
5633 }
5634
5635 return result;
5636}
5637
Eric Laurent59bd0da2011-08-01 09:52:20 -07005638AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5639{
5640 Mutex::Autolock _l(mLock);
5641 return mTrack;
5642}
5643
Glenn Kastenaed850d2012-01-26 09:46:34 -08005644AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005645{
5646 Mutex::Autolock _l(mLock);
5647 return mInput;
5648}
5649
5650AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5651{
5652 Mutex::Autolock _l(mLock);
5653 AudioStreamIn *input = mInput;
5654 mInput = NULL;
5655 return input;
5656}
5657
5658// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08005659audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005660{
5661 if (mInput == NULL) {
5662 return NULL;
5663 }
5664 return &mInput->stream->common;
5665}
5666
5667
Mathias Agopian65ab4712010-07-14 17:59:35 -07005668// ----------------------------------------------------------------------------
5669
Eric Laurenta4c5a552012-03-29 10:12:40 -07005670audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
5671{
5672 if (!settingsAllowed()) {
5673 return 0;
5674 }
5675 Mutex::Autolock _l(mLock);
5676 return loadHwModule_l(name);
5677}
5678
5679// loadHwModule_l() must be called with AudioFlinger::mLock held
5680audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
5681{
5682 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
5683 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
5684 ALOGW("loadHwModule() module %s already loaded", name);
5685 return mAudioHwDevs.keyAt(i);
5686 }
5687 }
5688
5689 const hw_module_t *mod;
5690 audio_hw_device_t *dev;
5691
5692 int rc = load_audio_interface(name, &mod, &dev);
5693 if (rc) {
5694 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
5695 return 0;
5696 }
5697
5698 mHardwareStatus = AUDIO_HW_INIT;
5699 rc = dev->init_check(dev);
5700 mHardwareStatus = AUDIO_HW_IDLE;
5701 if (rc) {
5702 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
5703 return 0;
5704 }
5705
5706 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
5707 (NULL != dev->set_master_volume)) {
5708 AutoMutex lock(mHardwareLock);
5709 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
5710 dev->set_master_volume(dev, mMasterVolume);
5711 mHardwareStatus = AUDIO_HW_IDLE;
5712 }
5713
5714 audio_module_handle_t handle = nextUniqueId();
5715 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
5716
5717 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
5718 name, mod->name, mod->id, handle);
5719
5720 return handle;
5721
5722}
5723
5724audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
5725 audio_devices_t *pDevices,
5726 uint32_t *pSamplingRate,
5727 audio_format_t *pFormat,
5728 audio_channel_mask_t *pChannelMask,
5729 uint32_t *pLatencyMs,
5730 audio_policy_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005731{
5732 status_t status;
5733 PlaybackThread *thread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005734 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005735 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Eric Laurenta4c5a552012-03-29 10:12:40 -07005736 audio_channel_mask_t channelMask = pChannelMask ? *pChannelMask : 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005737 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07005738 audio_stream_out_t *outStream;
5739 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005740
Eric Laurenta4c5a552012-03-29 10:12:40 -07005741 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
5742 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07005743 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurenta4c5a552012-03-29 10:12:40 -07005744 samplingRate,
5745 format,
5746 channelMask,
5747 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005748
5749 if (pDevices == NULL || *pDevices == 0) {
5750 return 0;
5751 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005752
Mathias Agopian65ab4712010-07-14 17:59:35 -07005753 Mutex::Autolock _l(mLock);
5754
Eric Laurenta4c5a552012-03-29 10:12:40 -07005755 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07005756 if (outHwDev == NULL)
5757 return 0;
5758
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005759 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Glenn Kasten58f30212012-01-12 12:27:51 -08005760 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Eric Laurenta4c5a552012-03-29 10:12:40 -07005761 &channelMask, &samplingRate, &outStream);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005762 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01005763 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005764 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005765 samplingRate,
5766 format,
Eric Laurenta4c5a552012-03-29 10:12:40 -07005767 channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005768 status);
5769
Dima Zavin799a70e2011-04-18 16:57:27 -07005770 if (outStream != NULL) {
5771 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005772 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07005773
Dima Zavinfce7a472011-04-19 22:30:36 -07005774 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5775 (format != AUDIO_FORMAT_PCM_16_BIT) ||
Eric Laurenta4c5a552012-03-29 10:12:40 -07005776 (channelMask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005777 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005778 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005779 } else {
5780 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005781 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005782 }
5783 mPlaybackThreads.add(id, thread);
5784
Glenn Kastena0d68332012-01-27 16:47:15 -08005785 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5786 if (pFormat != NULL) *pFormat = format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07005787 if (pChannelMask != NULL) *pChannelMask = channelMask;
Glenn Kastena0d68332012-01-27 16:47:15 -08005788 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005789
5790 // notify client processes of the new output creation
5791 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07005792
5793 // the first primary output opened designates the primary hw device
5794 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_POLICY_OUTPUT_FLAG_PRIMARY)) {
5795 ALOGI("Using module %d has the primary audio interface", module);
5796 mPrimaryHardwareDev = outHwDev;
5797
5798 AutoMutex lock(mHardwareLock);
5799 mHardwareStatus = AUDIO_HW_SET_MODE;
5800 outHwDev->set_mode(outHwDev, mMode);
5801
5802 // Determine the level of master volume support the primary audio HAL has,
5803 // and set the initial master volume at the same time.
5804 float initialVolume = 1.0;
5805 mMasterVolumeSupportLvl = MVS_NONE;
5806
5807 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
5808 if ((NULL != outHwDev->get_master_volume) &&
5809 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
5810 mMasterVolumeSupportLvl = MVS_FULL;
5811 } else {
5812 mMasterVolumeSupportLvl = MVS_SETONLY;
5813 initialVolume = 1.0;
5814 }
5815
5816 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
5817 if ((NULL == outHwDev->set_master_volume) ||
5818 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
5819 mMasterVolumeSupportLvl = MVS_NONE;
5820 }
5821 // now that we have a primary device, initialize master volume on other devices
5822 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
5823 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
5824
5825 if ((dev != mPrimaryHardwareDev) &&
5826 (NULL != dev->set_master_volume)) {
5827 dev->set_master_volume(dev, initialVolume);
5828 }
5829 }
5830 mHardwareStatus = AUDIO_HW_IDLE;
5831 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
5832 ? initialVolume
5833 : 1.0;
5834 mMasterVolume = initialVolume;
5835 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005836 return id;
5837 }
5838
5839 return 0;
5840}
5841
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005842audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
5843 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005844{
5845 Mutex::Autolock _l(mLock);
5846 MixerThread *thread1 = checkMixerThread_l(output1);
5847 MixerThread *thread2 = checkMixerThread_l(output2);
5848
5849 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005850 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005851 return 0;
5852 }
5853
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005854 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005855 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5856 thread->addOutputTrack(thread2);
5857 mPlaybackThreads.add(id, thread);
5858 // notify client processes of the new output creation
5859 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5860 return id;
5861}
5862
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005863status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005864{
5865 // keep strong reference on the playback thread so that
5866 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005867 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005868 {
5869 Mutex::Autolock _l(mLock);
5870 thread = checkPlaybackThread_l(output);
5871 if (thread == NULL) {
5872 return BAD_VALUE;
5873 }
5874
Steve Block3856b092011-10-20 11:56:00 +01005875 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005876
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005877 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005878 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005879 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005880 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5881 dupThread->removeOutputTrack((MixerThread *)thread.get());
5882 }
5883 }
5884 }
Glenn Kastena1117922012-01-26 10:53:32 -08005885 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005886 mPlaybackThreads.removeItem(output);
5887 }
5888 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005889 // The thread entity (active unit of execution) is no longer running here,
5890 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005891
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005892 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005893 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005894 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005895 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005896 out->hwDev->close_output_stream(out->hwDev, out->stream);
5897 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005898 }
5899 return NO_ERROR;
5900}
5901
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005902status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005903{
5904 Mutex::Autolock _l(mLock);
5905 PlaybackThread *thread = checkPlaybackThread_l(output);
5906
5907 if (thread == NULL) {
5908 return BAD_VALUE;
5909 }
5910
Steve Block3856b092011-10-20 11:56:00 +01005911 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005912 thread->suspend();
5913
5914 return NO_ERROR;
5915}
5916
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005917status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005918{
5919 Mutex::Autolock _l(mLock);
5920 PlaybackThread *thread = checkPlaybackThread_l(output);
5921
5922 if (thread == NULL) {
5923 return BAD_VALUE;
5924 }
5925
Steve Block3856b092011-10-20 11:56:00 +01005926 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005927
5928 thread->restore();
5929
5930 return NO_ERROR;
5931}
5932
Eric Laurenta4c5a552012-03-29 10:12:40 -07005933audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
5934 audio_devices_t *pDevices,
5935 uint32_t *pSamplingRate,
5936 audio_format_t *pFormat,
5937 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005938{
5939 status_t status;
5940 RecordThread *thread = NULL;
5941 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005942 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Eric Laurenta4c5a552012-03-29 10:12:40 -07005943 audio_channel_mask_t channelMask = pChannelMask ? *pChannelMask : 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005944 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005945 audio_format_t reqFormat = format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07005946 audio_channel_mask_t reqChannels = channelMask;
Dima Zavin799a70e2011-04-18 16:57:27 -07005947 audio_stream_in_t *inStream;
5948 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005949
5950 if (pDevices == NULL || *pDevices == 0) {
5951 return 0;
5952 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005953
Mathias Agopian65ab4712010-07-14 17:59:35 -07005954 Mutex::Autolock _l(mLock);
5955
Eric Laurenta4c5a552012-03-29 10:12:40 -07005956 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07005957 if (inHwDev == NULL)
5958 return 0;
5959
Glenn Kasten58f30212012-01-12 12:27:51 -08005960 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Eric Laurenta4c5a552012-03-29 10:12:40 -07005961 &channelMask, &samplingRate,
5962 (audio_in_acoustics_t)0,
Dima Zavin799a70e2011-04-18 16:57:27 -07005963 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07005964 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005965 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005966 samplingRate,
5967 format,
Eric Laurenta4c5a552012-03-29 10:12:40 -07005968 channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005969 status);
5970
5971 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5972 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5973 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005974 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005975 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005976 (samplingRate <= 2 * reqSamplingRate) &&
Eric Laurenta4c5a552012-03-29 10:12:40 -07005977 (popcount(channelMask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01005978 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005979 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Eric Laurenta4c5a552012-03-29 10:12:40 -07005980 &channelMask, &samplingRate,
5981 (audio_in_acoustics_t)0,
Dima Zavin799a70e2011-04-18 16:57:27 -07005982 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005983 }
5984
Dima Zavin799a70e2011-04-18 16:57:27 -07005985 if (inStream != NULL) {
5986 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5987
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005988 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005989 // Start record thread
5990 // RecorThread require both input and output device indication to forward to audio
5991 // pre processing modules
5992 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5993 thread = new RecordThread(this,
5994 input,
5995 reqSamplingRate,
5996 reqChannels,
5997 id,
5998 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005999 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006000 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006001 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
6002 if (pFormat != NULL) *pFormat = format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006003 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006004
Dima Zavin799a70e2011-04-18 16:57:27 -07006005 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006006
6007 // notify client processes of the new input creation
6008 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
6009 return id;
6010 }
6011
6012 return 0;
6013}
6014
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006015status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006016{
6017 // keep strong reference on the record thread so that
6018 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006019 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006020 {
6021 Mutex::Autolock _l(mLock);
6022 thread = checkRecordThread_l(input);
6023 if (thread == NULL) {
6024 return BAD_VALUE;
6025 }
6026
Steve Block3856b092011-10-20 11:56:00 +01006027 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08006028 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006029 mRecordThreads.removeItem(input);
6030 }
6031 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006032 // The thread entity (active unit of execution) is no longer running here,
6033 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006034
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006035 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006036 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006037 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006038 in->hwDev->close_input_stream(in->hwDev, in->stream);
6039 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006040
6041 return NO_ERROR;
6042}
6043
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006044status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006045{
6046 Mutex::Autolock _l(mLock);
6047 MixerThread *dstThread = checkMixerThread_l(output);
6048 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006049 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006050 return BAD_VALUE;
6051 }
6052
Steve Block3856b092011-10-20 11:56:00 +01006053 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006054 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
6055
6056 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6057 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08006058 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006059 MixerThread *srcThread = (MixerThread *)thread;
6060 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006061 }
Eric Laurentde070132010-07-13 04:45:46 -07006062 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006063
6064 return NO_ERROR;
6065}
6066
6067
6068int AudioFlinger::newAudioSessionId()
6069{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006070 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006071}
6072
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006073void AudioFlinger::acquireAudioSessionId(int audioSession)
6074{
6075 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006076 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006077 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006078 size_t num = mAudioSessionRefs.size();
6079 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006080 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006081 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6082 ref->mCnt++;
6083 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006084 return;
6085 }
6086 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006087 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
6088 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006089}
6090
6091void AudioFlinger::releaseAudioSessionId(int audioSession)
6092{
6093 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006094 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006095 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006096 size_t num = mAudioSessionRefs.size();
6097 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006098 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006099 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6100 ref->mCnt--;
6101 ALOGV(" decremented refcount to %d", ref->mCnt);
6102 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006103 mAudioSessionRefs.removeAt(i);
6104 delete ref;
6105 purgeStaleEffects_l();
6106 }
6107 return;
6108 }
6109 }
Steve Block5ff1dd52012-01-05 23:22:43 +00006110 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006111}
6112
6113void AudioFlinger::purgeStaleEffects_l() {
6114
Steve Block3856b092011-10-20 11:56:00 +01006115 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006116
6117 Vector< sp<EffectChain> > chains;
6118
6119 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6120 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
6121 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6122 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07006123 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
6124 chains.push(ec);
6125 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006126 }
6127 }
6128 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6129 sp<RecordThread> t = mRecordThreads.valueAt(i);
6130 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6131 sp<EffectChain> ec = t->mEffectChains[j];
6132 chains.push(ec);
6133 }
6134 }
6135
6136 for (size_t i = 0; i < chains.size(); i++) {
6137 sp<EffectChain> ec = chains[i];
6138 int sessionid = ec->sessionId();
6139 sp<ThreadBase> t = ec->mThread.promote();
6140 if (t == 0) {
6141 continue;
6142 }
6143 size_t numsessionrefs = mAudioSessionRefs.size();
6144 bool found = false;
6145 for (size_t k = 0; k < numsessionrefs; k++) {
6146 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006147 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01006148 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006149 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006150 found = true;
6151 break;
6152 }
6153 }
6154 if (!found) {
6155 // remove all effects from the chain
6156 while (ec->mEffects.size()) {
6157 sp<EffectModule> effect = ec->mEffects[0];
6158 effect->unPin();
6159 Mutex::Autolock _l (t->mLock);
6160 t->removeEffect_l(effect);
6161 for (size_t j = 0; j < effect->mHandles.size(); j++) {
6162 sp<EffectHandle> handle = effect->mHandles[j].promote();
6163 if (handle != 0) {
6164 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07006165 if (handle->mHasControl && handle->mEnabled) {
6166 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
6167 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006168 }
6169 }
6170 AudioSystem::unregisterEffect(effect->id());
6171 }
6172 }
6173 }
6174 return;
6175}
6176
Mathias Agopian65ab4712010-07-14 17:59:35 -07006177// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006178AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006179{
Glenn Kastena1117922012-01-26 10:53:32 -08006180 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006181}
6182
6183// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006184AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006185{
6186 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08006187 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006188}
6189
6190// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006191AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006192{
Glenn Kastena1117922012-01-26 10:53:32 -08006193 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006194}
6195
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006196uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07006197{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006198 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006199}
6200
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006201AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006202{
6203 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6204 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006205 AudioStreamOut *output = thread->getOutput();
6206 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006207 return thread;
6208 }
6209 }
6210 return NULL;
6211}
6212
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006213uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006214{
6215 PlaybackThread *thread = primaryPlaybackThread_l();
6216
6217 if (thread == NULL) {
6218 return 0;
6219 }
6220
6221 return thread->device();
6222}
6223
Eric Laurenta011e352012-03-29 15:51:43 -07006224sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
6225 int triggerSession,
6226 int listenerSession,
6227 sync_event_callback_t callBack,
6228 void *cookie)
6229{
6230 Mutex::Autolock _l(mLock);
6231
6232 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
6233 status_t playStatus = NAME_NOT_FOUND;
6234 status_t recStatus = NAME_NOT_FOUND;
6235 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6236 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
6237 if (playStatus == NO_ERROR) {
6238 return event;
6239 }
6240 }
6241 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6242 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
6243 if (recStatus == NO_ERROR) {
6244 return event;
6245 }
6246 }
6247 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
6248 mPendingSyncEvents.add(event);
6249 } else {
6250 ALOGV("createSyncEvent() invalid event %d", event->type());
6251 event.clear();
6252 }
6253 return event;
6254}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006255
Mathias Agopian65ab4712010-07-14 17:59:35 -07006256// ----------------------------------------------------------------------------
6257// Effect management
6258// ----------------------------------------------------------------------------
6259
6260
Glenn Kastenf587ba52012-01-26 16:25:10 -08006261status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006262{
6263 Mutex::Autolock _l(mLock);
6264 return EffectQueryNumberEffects(numEffects);
6265}
6266
Glenn Kastenf587ba52012-01-26 16:25:10 -08006267status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006268{
6269 Mutex::Autolock _l(mLock);
6270 return EffectQueryEffect(index, descriptor);
6271}
6272
Glenn Kasten5e92a782012-01-30 07:40:52 -08006273status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08006274 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006275{
6276 Mutex::Autolock _l(mLock);
6277 return EffectGetDescriptor(pUuid, descriptor);
6278}
6279
6280
Mathias Agopian65ab4712010-07-14 17:59:35 -07006281sp<IEffect> AudioFlinger::createEffect(pid_t pid,
6282 effect_descriptor_t *pDesc,
6283 const sp<IEffectClient>& effectClient,
6284 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006285 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006286 int sessionId,
6287 status_t *status,
6288 int *id,
6289 int *enabled)
6290{
6291 status_t lStatus = NO_ERROR;
6292 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006293 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006294
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006295 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006296 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006297
6298 if (pDesc == NULL) {
6299 lStatus = BAD_VALUE;
6300 goto Exit;
6301 }
6302
Eric Laurent84e9a102010-09-23 16:10:16 -07006303 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006304 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006305 lStatus = PERMISSION_DENIED;
6306 goto Exit;
6307 }
6308
Dima Zavinfce7a472011-04-19 22:30:36 -07006309 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07006310 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08006311 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006312 lStatus = PERMISSION_DENIED;
6313 goto Exit;
6314 }
6315
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006316 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006317 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006318 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07006319 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07006320 lStatus = BAD_VALUE;
6321 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07006322 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006323 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006324 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07006325 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006326 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07006327 }
6328 }
6329
Mathias Agopian65ab4712010-07-14 17:59:35 -07006330 {
6331 Mutex::Autolock _l(mLock);
6332
Mathias Agopian65ab4712010-07-14 17:59:35 -07006333
6334 if (!EffectIsNullUuid(&pDesc->uuid)) {
6335 // if uuid is specified, request effect descriptor
6336 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
6337 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006338 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006339 goto Exit;
6340 }
6341 } else {
6342 // if uuid is not specified, look for an available implementation
6343 // of the required type in effect factory
6344 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006345 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006346 lStatus = BAD_VALUE;
6347 goto Exit;
6348 }
6349 uint32_t numEffects = 0;
6350 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006351 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07006352 bool found = false;
6353
6354 lStatus = EffectQueryNumberEffects(&numEffects);
6355 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006356 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006357 goto Exit;
6358 }
6359 for (uint32_t i = 0; i < numEffects; i++) {
6360 lStatus = EffectQueryEffect(i, &desc);
6361 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006362 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006363 continue;
6364 }
6365 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
6366 // If matching type found save effect descriptor. If the session is
6367 // 0 and the effect is not auxiliary, continue enumeration in case
6368 // an auxiliary version of this effect type is available
6369 found = true;
6370 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07006371 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006372 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6373 break;
6374 }
6375 }
6376 }
6377 if (!found) {
6378 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00006379 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006380 goto Exit;
6381 }
6382 // For same effect type, chose auxiliary version over insert version if
6383 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07006384 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006385 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
6386 memcpy(&desc, &d, sizeof(effect_descriptor_t));
6387 }
6388 }
6389
6390 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07006391 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006392 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6393 lStatus = INVALID_OPERATION;
6394 goto Exit;
6395 }
6396
Eric Laurent59255e42011-07-27 19:49:51 -07006397 // check recording permission for visualizer
6398 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
6399 !recordingAllowed()) {
6400 lStatus = PERMISSION_DENIED;
6401 goto Exit;
6402 }
6403
Mathias Agopian65ab4712010-07-14 17:59:35 -07006404 // return effect descriptor
6405 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
6406
6407 // If output is not specified try to find a matching audio session ID in one of the
6408 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07006409 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
6410 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006411 // Note: io is never 0 when creating an effect on an input
6412 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006413 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07006414 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6415 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006416 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07006417 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07006418 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006419 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006420 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006421 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6422 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6423 io = mRecordThreads.keyAt(i);
6424 break;
6425 }
6426 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006427 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006428 // If no output thread contains the requested session ID, default to
6429 // first output. The effect chain will be moved to the correct output
6430 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006431 if (io == 0 && mPlaybackThreads.size()) {
6432 io = mPlaybackThreads.keyAt(0);
6433 }
Steve Block3856b092011-10-20 11:56:00 +01006434 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006435 }
6436 ThreadBase *thread = checkRecordThread_l(io);
6437 if (thread == NULL) {
6438 thread = checkPlaybackThread_l(io);
6439 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00006440 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006441 lStatus = BAD_VALUE;
6442 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07006443 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006444 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006445
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006446 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006447
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006448 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07006449 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6450 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006451 if (handle != 0 && id != NULL) {
6452 *id = handle->id();
6453 }
6454 }
6455
6456Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006457 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006458 *status = lStatus;
6459 }
6460 return handle;
6461}
6462
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006463status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
6464 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07006465{
Steve Block3856b092011-10-20 11:56:00 +01006466 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07006467 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006468 Mutex::Autolock _l(mLock);
6469 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006470 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006471 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006472 }
Eric Laurentde070132010-07-13 04:45:46 -07006473 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6474 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006475 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006476 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006477 }
Eric Laurentde070132010-07-13 04:45:46 -07006478 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6479 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006480 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006481 return BAD_VALUE;
6482 }
6483
6484 Mutex::Autolock _dl(dstThread->mLock);
6485 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07006486 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07006487
Mathias Agopian65ab4712010-07-14 17:59:35 -07006488 return NO_ERROR;
6489}
6490
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006491// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07006492status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07006493 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07006494 AudioFlinger::PlaybackThread *dstThread,
6495 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07006496{
Steve Block3856b092011-10-20 11:56:00 +01006497 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006498 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07006499
Eric Laurent59255e42011-07-27 19:49:51 -07006500 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006501 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006502 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006503 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07006504 return INVALID_OPERATION;
6505 }
6506
Eric Laurent39e94f82010-07-28 01:32:47 -07006507 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07006508 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07006509 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07006510 // removed.
6511 srcThread->removeEffectChain_l(chain);
6512
6513 // transfer all effects one by one so that new effect chain is created on new thread with
6514 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006515 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07006516 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006517 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07006518 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6519 while (effect != 0) {
6520 srcThread->removeEffect_l(effect);
6521 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07006522 // removeEffect_l() has stopped the effect if it was active so it must be restarted
6523 if (effect->state() == EffectModule::ACTIVE ||
6524 effect->state() == EffectModule::STOPPING) {
6525 effect->start();
6526 }
Eric Laurent39e94f82010-07-28 01:32:47 -07006527 // if the move request is not received from audio policy manager, the effect must be
6528 // re-registered with the new strategy and output
6529 if (dstChain == 0) {
6530 dstChain = effect->chain().promote();
6531 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006532 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07006533 srcThread->addEffect_l(effect);
6534 return NO_INIT;
6535 }
6536 strategy = dstChain->strategy();
6537 }
6538 if (reRegister) {
6539 AudioSystem::unregisterEffect(effect->id());
6540 AudioSystem::registerEffect(&effect->desc(),
6541 dstOutput,
6542 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07006543 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07006544 effect->id());
6545 }
Eric Laurentde070132010-07-13 04:45:46 -07006546 effect = chain->getEffectFromId_l(0);
6547 }
6548
6549 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006550}
6551
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006552
Mathias Agopian65ab4712010-07-14 17:59:35 -07006553// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006554sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07006555 const sp<AudioFlinger::Client>& client,
6556 const sp<IEffectClient>& effectClient,
6557 int32_t priority,
6558 int sessionId,
6559 effect_descriptor_t *desc,
6560 int *enabled,
6561 status_t *status
6562 )
6563{
6564 sp<EffectModule> effect;
6565 sp<EffectHandle> handle;
6566 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006567 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07006568 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006569 bool effectCreated = false;
6570 bool effectRegistered = false;
6571
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006572 lStatus = initCheck();
6573 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006574 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006575 goto Exit;
6576 }
6577
6578 // Do not allow effects with session ID 0 on direct output or duplicating threads
6579 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07006580 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006581 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07006582 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006583 lStatus = BAD_VALUE;
6584 goto Exit;
6585 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006586 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08006587 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006588 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006589 desc->name, desc->flags, mType);
6590 lStatus = BAD_VALUE;
6591 goto Exit;
6592 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006593
Steve Block3856b092011-10-20 11:56:00 +01006594 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006595
6596 { // scope for mLock
6597 Mutex::Autolock _l(mLock);
6598
6599 // check for existing effect chain with the requested audio session
6600 chain = getEffectChain_l(sessionId);
6601 if (chain == 0) {
6602 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006603 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006604 chain = new EffectChain(this, sessionId);
6605 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07006606 chain->setStrategy(getStrategyForSession_l(sessionId));
6607 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006608 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07006609 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006610 }
6611
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08006612 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006613
6614 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006615 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006616 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07006617 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006618 if (lStatus != NO_ERROR) {
6619 goto Exit;
6620 }
6621 effectRegistered = true;
6622 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07006623 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006624 lStatus = effect->status();
6625 if (lStatus != NO_ERROR) {
6626 goto Exit;
6627 }
Eric Laurentcab11242010-07-15 12:50:15 -07006628 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006629 if (lStatus != NO_ERROR) {
6630 goto Exit;
6631 }
6632 effectCreated = true;
6633
6634 effect->setDevice(mDevice);
6635 effect->setMode(mAudioFlinger->getMode());
6636 }
6637 // create effect handle and connect it to effect module
6638 handle = new EffectHandle(effect, client, effectClient, priority);
6639 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08006640 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006641 *enabled = (int)effect->isEnabled();
6642 }
6643 }
6644
6645Exit:
6646 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07006647 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006648 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07006649 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006650 }
6651 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07006652 AudioSystem::unregisterEffect(effect->id());
6653 }
6654 if (chainCreated) {
6655 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006656 }
6657 handle.clear();
6658 }
6659
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006660 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006661 *status = lStatus;
6662 }
6663 return handle;
6664}
6665
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006666sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6667{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006668 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08006669 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006670}
6671
Eric Laurentde070132010-07-13 04:45:46 -07006672// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6673// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006674status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07006675{
6676 // check for existing effect chain with the requested audio session
6677 int sessionId = effect->sessionId();
6678 sp<EffectChain> chain = getEffectChain_l(sessionId);
6679 bool chainCreated = false;
6680
6681 if (chain == 0) {
6682 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006683 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006684 chain = new EffectChain(this, sessionId);
6685 addEffectChain_l(chain);
6686 chain->setStrategy(getStrategyForSession_l(sessionId));
6687 chainCreated = true;
6688 }
Steve Block3856b092011-10-20 11:56:00 +01006689 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006690
6691 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006692 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07006693 this, effect->desc().name, chain.get());
6694 return BAD_VALUE;
6695 }
6696
6697 status_t status = chain->addEffect_l(effect);
6698 if (status != NO_ERROR) {
6699 if (chainCreated) {
6700 removeEffectChain_l(chain);
6701 }
6702 return status;
6703 }
6704
6705 effect->setDevice(mDevice);
6706 effect->setMode(mAudioFlinger->getMode());
6707 return NO_ERROR;
6708}
6709
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006710void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07006711
Steve Block3856b092011-10-20 11:56:00 +01006712 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006713 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07006714 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6715 detachAuxEffect_l(effect->id());
6716 }
6717
6718 sp<EffectChain> chain = effect->chain().promote();
6719 if (chain != 0) {
6720 // remove effect chain if removing last effect
6721 if (chain->removeEffect_l(effect) == 0) {
6722 removeEffectChain_l(chain);
6723 }
6724 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00006725 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006726 }
6727}
6728
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006729void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006730 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006731{
6732 effectChains = mEffectChains;
6733 for (size_t i = 0; i < mEffectChains.size(); i++) {
6734 mEffectChains[i]->lock();
6735 }
6736}
6737
6738void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006739 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006740{
6741 for (size_t i = 0; i < effectChains.size(); i++) {
6742 effectChains[i]->unlock();
6743 }
6744}
6745
6746sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6747{
6748 Mutex::Autolock _l(mLock);
6749 return getEffectChain_l(sessionId);
6750}
6751
6752sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6753{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006754 size_t size = mEffectChains.size();
6755 for (size_t i = 0; i < size; i++) {
6756 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08006757 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006758 }
6759 }
Glenn Kasten090f0192012-01-30 13:00:02 -08006760 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006761}
6762
Glenn Kastenf78aee72012-01-04 11:00:47 -08006763void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006764{
6765 Mutex::Autolock _l(mLock);
6766 size_t size = mEffectChains.size();
6767 for (size_t i = 0; i < size; i++) {
6768 mEffectChains[i]->setMode_l(mode);
6769 }
6770}
6771
6772void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006773 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08006774 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07006775
Mathias Agopian65ab4712010-07-14 17:59:35 -07006776 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006777 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006778 // delete the effect module if removing last handle on it
6779 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006780 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006781 removeEffect_l(effect);
6782 AudioSystem::unregisterEffect(effect->id());
6783 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006784 }
6785}
6786
6787status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6788{
6789 int session = chain->sessionId();
6790 int16_t *buffer = mMixBuffer;
6791 bool ownsBuffer = false;
6792
Steve Block3856b092011-10-20 11:56:00 +01006793 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006794 if (session > 0) {
6795 // Only one effect chain can be present in direct output thread and it uses
6796 // the mix buffer as input
6797 if (mType != DIRECT) {
6798 size_t numSamples = mFrameCount * mChannelCount;
6799 buffer = new int16_t[numSamples];
6800 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01006801 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006802 ownsBuffer = true;
6803 }
6804
6805 // Attach all tracks with same session ID to this chain.
6806 for (size_t i = 0; i < mTracks.size(); ++i) {
6807 sp<Track> track = mTracks[i];
6808 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006809 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006810 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006811 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006812 }
6813 }
6814
6815 // indicate all active tracks in the chain
6816 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6817 sp<Track> track = mActiveTracks[i].promote();
6818 if (track == 0) continue;
6819 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006820 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07006821 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006822 }
6823 }
6824 }
6825
6826 chain->setInBuffer(buffer, ownsBuffer);
6827 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006828 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006829 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006830 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6831 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006832 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006833 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6834 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006835 // Effect chain for other sessions are inserted at beginning of effect
6836 // chains list to be processed before output mix effects. Relative order between other
6837 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006838 size_t size = mEffectChains.size();
6839 size_t i = 0;
6840 for (i = 0; i < size; i++) {
6841 if (mEffectChains[i]->sessionId() < session) break;
6842 }
6843 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006844 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006845
6846 return NO_ERROR;
6847}
6848
6849size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6850{
6851 int session = chain->sessionId();
6852
Steve Block3856b092011-10-20 11:56:00 +01006853 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006854
6855 for (size_t i = 0; i < mEffectChains.size(); i++) {
6856 if (chain == mEffectChains[i]) {
6857 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006858 // detach all active tracks from the chain
6859 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6860 sp<Track> track = mActiveTracks[i].promote();
6861 if (track == 0) continue;
6862 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006863 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006864 chain.get(), session);
6865 chain->decActiveTrackCnt();
6866 }
6867 }
6868
Mathias Agopian65ab4712010-07-14 17:59:35 -07006869 // detach all tracks with same session ID from this chain
6870 for (size_t i = 0; i < mTracks.size(); ++i) {
6871 sp<Track> track = mTracks[i];
6872 if (session == track->sessionId()) {
6873 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006874 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006875 }
6876 }
Eric Laurentde070132010-07-13 04:45:46 -07006877 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006878 }
6879 }
6880 return mEffectChains.size();
6881}
6882
Eric Laurentde070132010-07-13 04:45:46 -07006883status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6884 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006885{
6886 Mutex::Autolock _l(mLock);
6887 return attachAuxEffect_l(track, EffectId);
6888}
6889
Eric Laurentde070132010-07-13 04:45:46 -07006890status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6891 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006892{
6893 status_t status = NO_ERROR;
6894
6895 if (EffectId == 0) {
6896 track->setAuxBuffer(0, NULL);
6897 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006898 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6899 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006900 if (effect != 0) {
6901 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6902 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6903 } else {
6904 status = INVALID_OPERATION;
6905 }
6906 } else {
6907 status = BAD_VALUE;
6908 }
6909 }
6910 return status;
6911}
6912
6913void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6914{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006915 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006916 sp<Track> track = mTracks[i];
6917 if (track->auxEffectId() == effectId) {
6918 attachAuxEffect_l(track, 0);
6919 }
6920 }
6921}
6922
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006923status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6924{
6925 // only one chain per input thread
6926 if (mEffectChains.size() != 0) {
6927 return INVALID_OPERATION;
6928 }
Steve Block3856b092011-10-20 11:56:00 +01006929 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006930
6931 chain->setInBuffer(NULL);
6932 chain->setOutBuffer(NULL);
6933
Eric Laurent59255e42011-07-27 19:49:51 -07006934 checkSuspendOnAddEffectChain_l(chain);
6935
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006936 mEffectChains.add(chain);
6937
6938 return NO_ERROR;
6939}
6940
6941size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6942{
Steve Block3856b092011-10-20 11:56:00 +01006943 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006944 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006945 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6946 chain.get(), mEffectChains.size(), this);
6947 if (mEffectChains.size() == 1) {
6948 mEffectChains.removeAt(0);
6949 }
6950 return 0;
6951}
6952
Mathias Agopian65ab4712010-07-14 17:59:35 -07006953// ----------------------------------------------------------------------------
6954// EffectModule implementation
6955// ----------------------------------------------------------------------------
6956
6957#undef LOG_TAG
6958#define LOG_TAG "AudioFlinger::EffectModule"
6959
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006960AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006961 const wp<AudioFlinger::EffectChain>& chain,
6962 effect_descriptor_t *desc,
6963 int id,
6964 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006965 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006966 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006967{
Steve Block3856b092011-10-20 11:56:00 +01006968 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006969 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006970 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006971 return;
6972 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006973
6974 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6975
6976 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006977 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006978
6979 if (mStatus != NO_ERROR) {
6980 return;
6981 }
6982 lStatus = init();
6983 if (lStatus < 0) {
6984 mStatus = lStatus;
6985 goto Error;
6986 }
6987
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006988 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6989 mPinned = true;
6990 }
Steve Block3856b092011-10-20 11:56:00 +01006991 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006992 return;
6993Error:
6994 EffectRelease(mEffectInterface);
6995 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006996 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006997}
6998
6999AudioFlinger::EffectModule::~EffectModule()
7000{
Steve Block3856b092011-10-20 11:56:00 +01007001 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007002 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007003 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7004 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7005 sp<ThreadBase> thread = mThread.promote();
7006 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007007 audio_stream_t *stream = thread->stream();
7008 if (stream != NULL) {
7009 stream->remove_audio_effect(stream, mEffectInterface);
7010 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007011 }
7012 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007013 // release effect engine
7014 EffectRelease(mEffectInterface);
7015 }
7016}
7017
Glenn Kasten435dbe62012-01-30 10:15:48 -08007018status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007019{
7020 status_t status;
7021
7022 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007023 int priority = handle->priority();
7024 size_t size = mHandles.size();
7025 sp<EffectHandle> h;
7026 size_t i;
7027 for (i = 0; i < size; i++) {
7028 h = mHandles[i].promote();
7029 if (h == 0) continue;
7030 if (h->priority() <= priority) break;
7031 }
7032 // if inserted in first place, move effect control from previous owner to this handle
7033 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007034 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007035 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007036 enabled = h->enabled();
7037 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007038 }
Eric Laurent59255e42011-07-27 19:49:51 -07007039 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007040 status = NO_ERROR;
7041 } else {
7042 status = ALREADY_EXISTS;
7043 }
Steve Block3856b092011-10-20 11:56:00 +01007044 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007045 mHandles.insertAt(handle, i);
7046 return status;
7047}
7048
7049size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
7050{
7051 Mutex::Autolock _l(mLock);
7052 size_t size = mHandles.size();
7053 size_t i;
7054 for (i = 0; i < size; i++) {
7055 if (mHandles[i] == handle) break;
7056 }
7057 if (i == size) {
7058 return size;
7059 }
Steve Block3856b092011-10-20 11:56:00 +01007060 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07007061
7062 bool enabled = false;
7063 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08007064 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01007065 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07007066 enabled = hdl->enabled();
7067 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007068 mHandles.removeAt(i);
7069 size = mHandles.size();
7070 // if removed from first place, move effect control from this handle to next in line
7071 if (i == 0 && size != 0) {
7072 sp<EffectHandle> h = mHandles[0].promote();
7073 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007074 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007075 }
7076 }
7077
Eric Laurentec437d82011-07-26 20:54:46 -07007078 // Prevent calls to process() and other functions on effect interface from now on.
7079 // The effect engine will be released by the destructor when the last strong reference on
7080 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007081 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07007082 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07007083 }
7084
Mathias Agopian65ab4712010-07-14 17:59:35 -07007085 return size;
7086}
7087
Eric Laurent59255e42011-07-27 19:49:51 -07007088sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
7089{
7090 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08007091 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007092}
7093
Glenn Kasten58123c32012-02-03 10:32:24 -08007094void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007095{
Glenn Kasten90bebef2012-01-27 15:24:38 -08007096 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007097 // keep a strong reference on this EffectModule to avoid calling the
7098 // destructor before we exit
7099 sp<EffectModule> keep(this);
7100 {
7101 sp<ThreadBase> thread = mThread.promote();
7102 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007103 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007104 }
7105 }
7106}
7107
7108void AudioFlinger::EffectModule::updateState() {
7109 Mutex::Autolock _l(mLock);
7110
7111 switch (mState) {
7112 case RESTART:
7113 reset_l();
7114 // FALL THROUGH
7115
7116 case STARTING:
7117 // clear auxiliary effect input buffer for next accumulation
7118 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7119 memset(mConfig.inputCfg.buffer.raw,
7120 0,
7121 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
7122 }
7123 start_l();
7124 mState = ACTIVE;
7125 break;
7126 case STOPPING:
7127 stop_l();
7128 mDisableWaitCnt = mMaxDisableWaitCnt;
7129 mState = STOPPED;
7130 break;
7131 case STOPPED:
7132 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
7133 // turn off sequence.
7134 if (--mDisableWaitCnt == 0) {
7135 reset_l();
7136 mState = IDLE;
7137 }
7138 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007139 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07007140 break;
7141 }
7142}
7143
7144void AudioFlinger::EffectModule::process()
7145{
7146 Mutex::Autolock _l(mLock);
7147
Eric Laurentec437d82011-07-26 20:54:46 -07007148 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007149 mConfig.inputCfg.buffer.raw == NULL ||
7150 mConfig.outputCfg.buffer.raw == NULL) {
7151 return;
7152 }
7153
Eric Laurent8f45bd72010-08-31 13:50:07 -07007154 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007155 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
7156 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08007157 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007158 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07007159 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007160 }
7161
7162 // do the actual processing in the effect engine
7163 int ret = (*mEffectInterface)->process(mEffectInterface,
7164 &mConfig.inputCfg.buffer,
7165 &mConfig.outputCfg.buffer);
7166
7167 // force transition to IDLE state when engine is ready
7168 if (mState == STOPPED && ret == -ENODATA) {
7169 mDisableWaitCnt = 1;
7170 }
7171
7172 // clear auxiliary effect input buffer for next accumulation
7173 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08007174 memset(mConfig.inputCfg.buffer.raw, 0,
7175 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007176 }
7177 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08007178 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7179 // If an insert effect is idle and input buffer is different from output buffer,
7180 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07007181 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07007182 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08007183 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
7184 int16_t *in = mConfig.inputCfg.buffer.s16;
7185 int16_t *out = mConfig.outputCfg.buffer.s16;
7186 for (size_t i = 0; i < frameCnt; i++) {
7187 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007188 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007189 }
7190 }
7191}
7192
7193void AudioFlinger::EffectModule::reset_l()
7194{
7195 if (mEffectInterface == NULL) {
7196 return;
7197 }
7198 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
7199}
7200
7201status_t AudioFlinger::EffectModule::configure()
7202{
7203 uint32_t channels;
7204 if (mEffectInterface == NULL) {
7205 return NO_INIT;
7206 }
7207
7208 sp<ThreadBase> thread = mThread.promote();
7209 if (thread == 0) {
7210 return DEAD_OBJECT;
7211 }
7212
7213 // TODO: handle configuration of effects replacing track process
7214 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007215 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007216 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07007217 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007218 }
7219
7220 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007221 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007222 } else {
7223 mConfig.inputCfg.channels = channels;
7224 }
7225 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07007226 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
7227 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007228 mConfig.inputCfg.samplingRate = thread->sampleRate();
7229 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
7230 mConfig.inputCfg.bufferProvider.cookie = NULL;
7231 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
7232 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
7233 mConfig.outputCfg.bufferProvider.cookie = NULL;
7234 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
7235 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
7236 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
7237 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07007238 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07007239 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07007240 // - in other sessions:
7241 // last effect in the chain accumulates in output buffer: input buffer != output buffer
7242 // other effect: overwrites output buffer: input buffer == output buffer
7243 // Auxiliary effect:
7244 // accumulates in output buffer: input buffer != output buffer
7245 // Therefore: accumulate <=> input buffer != output buffer
7246 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7247 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
7248 } else {
7249 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
7250 }
7251 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
7252 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
7253 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
7254 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
7255
Steve Block3856b092011-10-20 11:56:00 +01007256 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07007257 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
7258
Mathias Agopian65ab4712010-07-14 17:59:35 -07007259 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007260 uint32_t size = sizeof(int);
7261 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08007262 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07007263 sizeof(effect_config_t),
7264 &mConfig,
7265 &size,
7266 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007267 if (status == 0) {
7268 status = cmdStatus;
7269 }
7270
7271 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
7272 (1000 * mConfig.outputCfg.buffer.frameCount);
7273
7274 return status;
7275}
7276
7277status_t AudioFlinger::EffectModule::init()
7278{
7279 Mutex::Autolock _l(mLock);
7280 if (mEffectInterface == NULL) {
7281 return NO_INIT;
7282 }
7283 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007284 uint32_t size = sizeof(status_t);
7285 status_t status = (*mEffectInterface)->command(mEffectInterface,
7286 EFFECT_CMD_INIT,
7287 0,
7288 NULL,
7289 &size,
7290 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007291 if (status == 0) {
7292 status = cmdStatus;
7293 }
7294 return status;
7295}
7296
Eric Laurentec35a142011-10-05 17:42:25 -07007297status_t AudioFlinger::EffectModule::start()
7298{
7299 Mutex::Autolock _l(mLock);
7300 return start_l();
7301}
7302
Mathias Agopian65ab4712010-07-14 17:59:35 -07007303status_t AudioFlinger::EffectModule::start_l()
7304{
7305 if (mEffectInterface == NULL) {
7306 return NO_INIT;
7307 }
7308 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007309 uint32_t size = sizeof(status_t);
7310 status_t status = (*mEffectInterface)->command(mEffectInterface,
7311 EFFECT_CMD_ENABLE,
7312 0,
7313 NULL,
7314 &size,
7315 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007316 if (status == 0) {
7317 status = cmdStatus;
7318 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007319 if (status == 0 &&
7320 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7321 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7322 sp<ThreadBase> thread = mThread.promote();
7323 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007324 audio_stream_t *stream = thread->stream();
7325 if (stream != NULL) {
7326 stream->add_audio_effect(stream, mEffectInterface);
7327 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007328 }
7329 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007330 return status;
7331}
7332
Eric Laurentec437d82011-07-26 20:54:46 -07007333status_t AudioFlinger::EffectModule::stop()
7334{
7335 Mutex::Autolock _l(mLock);
7336 return stop_l();
7337}
7338
Mathias Agopian65ab4712010-07-14 17:59:35 -07007339status_t AudioFlinger::EffectModule::stop_l()
7340{
7341 if (mEffectInterface == NULL) {
7342 return NO_INIT;
7343 }
7344 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007345 uint32_t size = sizeof(status_t);
7346 status_t status = (*mEffectInterface)->command(mEffectInterface,
7347 EFFECT_CMD_DISABLE,
7348 0,
7349 NULL,
7350 &size,
7351 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007352 if (status == 0) {
7353 status = cmdStatus;
7354 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007355 if (status == 0 &&
7356 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7357 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7358 sp<ThreadBase> thread = mThread.promote();
7359 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007360 audio_stream_t *stream = thread->stream();
7361 if (stream != NULL) {
7362 stream->remove_audio_effect(stream, mEffectInterface);
7363 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007364 }
7365 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007366 return status;
7367}
7368
Eric Laurent25f43952010-07-28 05:40:18 -07007369status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
7370 uint32_t cmdSize,
7371 void *pCmdData,
7372 uint32_t *replySize,
7373 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007374{
7375 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007376// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007377
Eric Laurentec437d82011-07-26 20:54:46 -07007378 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007379 return NO_INIT;
7380 }
Eric Laurent25f43952010-07-28 05:40:18 -07007381 status_t status = (*mEffectInterface)->command(mEffectInterface,
7382 cmdCode,
7383 cmdSize,
7384 pCmdData,
7385 replySize,
7386 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007387 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07007388 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007389 for (size_t i = 1; i < mHandles.size(); i++) {
7390 sp<EffectHandle> h = mHandles[i].promote();
7391 if (h != 0) {
7392 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
7393 }
7394 }
7395 }
7396 return status;
7397}
7398
7399status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
7400{
Eric Laurentdb7c0792011-08-10 10:37:50 -07007401
Mathias Agopian65ab4712010-07-14 17:59:35 -07007402 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007403 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007404
7405 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007406 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
7407 if (enabled && status != NO_ERROR) {
7408 return status;
7409 }
7410
Mathias Agopian65ab4712010-07-14 17:59:35 -07007411 switch (mState) {
7412 // going from disabled to enabled
7413 case IDLE:
7414 mState = STARTING;
7415 break;
7416 case STOPPED:
7417 mState = RESTART;
7418 break;
7419 case STOPPING:
7420 mState = ACTIVE;
7421 break;
7422
7423 // going from enabled to disabled
7424 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007425 mState = STOPPED;
7426 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007427 case STARTING:
7428 mState = IDLE;
7429 break;
7430 case ACTIVE:
7431 mState = STOPPING;
7432 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007433 case DESTROYED:
7434 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007435 }
7436 for (size_t i = 1; i < mHandles.size(); i++) {
7437 sp<EffectHandle> h = mHandles[i].promote();
7438 if (h != 0) {
7439 h->setEnabled(enabled);
7440 }
7441 }
7442 }
7443 return NO_ERROR;
7444}
7445
Glenn Kastenc59c0042012-02-02 14:06:11 -08007446bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007447{
7448 switch (mState) {
7449 case RESTART:
7450 case STARTING:
7451 case ACTIVE:
7452 return true;
7453 case IDLE:
7454 case STOPPING:
7455 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07007456 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07007457 default:
7458 return false;
7459 }
7460}
7461
Glenn Kastenc59c0042012-02-02 14:06:11 -08007462bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07007463{
7464 switch (mState) {
7465 case RESTART:
7466 case ACTIVE:
7467 case STOPPING:
7468 case STOPPED:
7469 return true;
7470 case IDLE:
7471 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07007472 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007473 default:
7474 return false;
7475 }
7476}
7477
Mathias Agopian65ab4712010-07-14 17:59:35 -07007478status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7479{
7480 Mutex::Autolock _l(mLock);
7481 status_t status = NO_ERROR;
7482
7483 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7484 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07007485 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07007486 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7487 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007488 status_t cmdStatus;
7489 uint32_t volume[2];
7490 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07007491 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007492 volume[0] = *left;
7493 volume[1] = *right;
7494 if (controller) {
7495 pVolume = volume;
7496 }
Eric Laurent25f43952010-07-28 05:40:18 -07007497 status = (*mEffectInterface)->command(mEffectInterface,
7498 EFFECT_CMD_SET_VOLUME,
7499 size,
7500 volume,
7501 &size,
7502 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007503 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7504 *left = volume[0];
7505 *right = volume[1];
7506 }
7507 }
7508 return status;
7509}
7510
7511status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7512{
7513 Mutex::Autolock _l(mLock);
7514 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007515 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7516 // audio pre processing modules on RecordThread can receive both output and
7517 // input device indication in the same call
7518 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7519 if (dev) {
7520 status_t cmdStatus;
7521 uint32_t size = sizeof(status_t);
7522
7523 status = (*mEffectInterface)->command(mEffectInterface,
7524 EFFECT_CMD_SET_DEVICE,
7525 sizeof(uint32_t),
7526 &dev,
7527 &size,
7528 &cmdStatus);
7529 if (status == NO_ERROR) {
7530 status = cmdStatus;
7531 }
7532 }
7533 dev = device & AUDIO_DEVICE_IN_ALL;
7534 if (dev) {
7535 status_t cmdStatus;
7536 uint32_t size = sizeof(status_t);
7537
7538 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7539 EFFECT_CMD_SET_INPUT_DEVICE,
7540 sizeof(uint32_t),
7541 &dev,
7542 &size,
7543 &cmdStatus);
7544 if (status2 == NO_ERROR) {
7545 status2 = cmdStatus;
7546 }
7547 if (status == NO_ERROR) {
7548 status = status2;
7549 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007550 }
7551 }
7552 return status;
7553}
7554
Glenn Kastenf78aee72012-01-04 11:00:47 -08007555status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007556{
7557 Mutex::Autolock _l(mLock);
7558 status_t status = NO_ERROR;
7559 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007560 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007561 uint32_t size = sizeof(status_t);
7562 status = (*mEffectInterface)->command(mEffectInterface,
7563 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08007564 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07007565 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07007566 &size,
7567 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007568 if (status == NO_ERROR) {
7569 status = cmdStatus;
7570 }
7571 }
7572 return status;
7573}
7574
Eric Laurent59255e42011-07-27 19:49:51 -07007575void AudioFlinger::EffectModule::setSuspended(bool suspended)
7576{
7577 Mutex::Autolock _l(mLock);
7578 mSuspended = suspended;
7579}
Glenn Kastena3a85482012-01-04 11:01:11 -08007580
7581bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07007582{
7583 Mutex::Autolock _l(mLock);
7584 return mSuspended;
7585}
7586
Mathias Agopian65ab4712010-07-14 17:59:35 -07007587status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7588{
7589 const size_t SIZE = 256;
7590 char buffer[SIZE];
7591 String8 result;
7592
7593 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7594 result.append(buffer);
7595
7596 bool locked = tryLock(mLock);
7597 // failed to lock - AudioFlinger is probably deadlocked
7598 if (!locked) {
7599 result.append("\t\tCould not lock Fx mutex:\n");
7600 }
7601
7602 result.append("\t\tSession Status State Engine:\n");
7603 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7604 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7605 result.append(buffer);
7606
7607 result.append("\t\tDescriptor:\n");
7608 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7609 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7610 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7611 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7612 result.append(buffer);
7613 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7614 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7615 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7616 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7617 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07007618 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007619 mDescriptor.apiVersion,
7620 mDescriptor.flags);
7621 result.append(buffer);
7622 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7623 mDescriptor.name);
7624 result.append(buffer);
7625 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7626 mDescriptor.implementor);
7627 result.append(buffer);
7628
7629 result.append("\t\t- Input configuration:\n");
7630 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7631 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7632 (uint32_t)mConfig.inputCfg.buffer.raw,
7633 mConfig.inputCfg.buffer.frameCount,
7634 mConfig.inputCfg.samplingRate,
7635 mConfig.inputCfg.channels,
7636 mConfig.inputCfg.format);
7637 result.append(buffer);
7638
7639 result.append("\t\t- Output configuration:\n");
7640 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7641 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7642 (uint32_t)mConfig.outputCfg.buffer.raw,
7643 mConfig.outputCfg.buffer.frameCount,
7644 mConfig.outputCfg.samplingRate,
7645 mConfig.outputCfg.channels,
7646 mConfig.outputCfg.format);
7647 result.append(buffer);
7648
7649 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7650 result.append(buffer);
7651 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7652 for (size_t i = 0; i < mHandles.size(); ++i) {
7653 sp<EffectHandle> handle = mHandles[i].promote();
7654 if (handle != 0) {
7655 handle->dump(buffer, SIZE);
7656 result.append(buffer);
7657 }
7658 }
7659
7660 result.append("\n");
7661
7662 write(fd, result.string(), result.length());
7663
7664 if (locked) {
7665 mLock.unlock();
7666 }
7667
7668 return NO_ERROR;
7669}
7670
7671// ----------------------------------------------------------------------------
7672// EffectHandle implementation
7673// ----------------------------------------------------------------------------
7674
7675#undef LOG_TAG
7676#define LOG_TAG "AudioFlinger::EffectHandle"
7677
7678AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7679 const sp<AudioFlinger::Client>& client,
7680 const sp<IEffectClient>& effectClient,
7681 int32_t priority)
7682 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007683 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007684 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007685{
Steve Block3856b092011-10-20 11:56:00 +01007686 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007687
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007688 if (client == 0) {
7689 return;
7690 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007691 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7692 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7693 if (mCblkMemory != 0) {
7694 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7695
Glenn Kastena0d68332012-01-27 16:47:15 -08007696 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007697 new(mCblk) effect_param_cblk_t();
7698 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007699 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007700 } else {
Steve Block29357bc2012-01-06 19:20:56 +00007701 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007702 return;
7703 }
7704}
7705
7706AudioFlinger::EffectHandle::~EffectHandle()
7707{
Steve Block3856b092011-10-20 11:56:00 +01007708 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007709 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01007710 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007711}
7712
7713status_t AudioFlinger::EffectHandle::enable()
7714{
Steve Block3856b092011-10-20 11:56:00 +01007715 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007716 if (!mHasControl) return INVALID_OPERATION;
7717 if (mEffect == 0) return DEAD_OBJECT;
7718
Eric Laurentdb7c0792011-08-10 10:37:50 -07007719 if (mEnabled) {
7720 return NO_ERROR;
7721 }
7722
Eric Laurent59255e42011-07-27 19:49:51 -07007723 mEnabled = true;
7724
7725 sp<ThreadBase> thread = mEffect->thread().promote();
7726 if (thread != 0) {
7727 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7728 }
7729
7730 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7731 if (mEffect->suspended()) {
7732 return NO_ERROR;
7733 }
7734
Eric Laurentdb7c0792011-08-10 10:37:50 -07007735 status_t status = mEffect->setEnabled(true);
7736 if (status != NO_ERROR) {
7737 if (thread != 0) {
7738 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7739 }
7740 mEnabled = false;
7741 }
7742 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007743}
7744
7745status_t AudioFlinger::EffectHandle::disable()
7746{
Steve Block3856b092011-10-20 11:56:00 +01007747 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007748 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07007749 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007750
Eric Laurentdb7c0792011-08-10 10:37:50 -07007751 if (!mEnabled) {
7752 return NO_ERROR;
7753 }
Eric Laurent59255e42011-07-27 19:49:51 -07007754 mEnabled = false;
7755
7756 if (mEffect->suspended()) {
7757 return NO_ERROR;
7758 }
7759
7760 status_t status = mEffect->setEnabled(false);
7761
7762 sp<ThreadBase> thread = mEffect->thread().promote();
7763 if (thread != 0) {
7764 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7765 }
7766
7767 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007768}
7769
7770void AudioFlinger::EffectHandle::disconnect()
7771{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007772 disconnect(true);
7773}
7774
Glenn Kasten58123c32012-02-03 10:32:24 -08007775void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007776{
Glenn Kasten58123c32012-02-03 10:32:24 -08007777 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007778 if (mEffect == 0) {
7779 return;
7780 }
Glenn Kasten58123c32012-02-03 10:32:24 -08007781 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07007782
Eric Laurenta85a74a2011-10-19 11:44:54 -07007783 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007784 sp<ThreadBase> thread = mEffect->thread().promote();
7785 if (thread != 0) {
7786 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7787 }
Eric Laurent59255e42011-07-27 19:49:51 -07007788 }
7789
Mathias Agopian65ab4712010-07-14 17:59:35 -07007790 // release sp on module => module destructor can be called now
7791 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007792 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08007793 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08007794 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007795 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7796 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08007797 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007798 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07007799 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7800 mClient.clear();
7801 }
7802}
7803
Eric Laurent25f43952010-07-28 05:40:18 -07007804status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7805 uint32_t cmdSize,
7806 void *pCmdData,
7807 uint32_t *replySize,
7808 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007809{
Steve Block3856b092011-10-20 11:56:00 +01007810// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07007811// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007812
7813 // only get parameter command is permitted for applications not controlling the effect
7814 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7815 return INVALID_OPERATION;
7816 }
7817 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007818 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007819
7820 // handle commands that are not forwarded transparently to effect engine
7821 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7822 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7823 // no risk to block the whole media server process or mixer threads is we are stuck here
7824 Mutex::Autolock _l(mCblk->lock);
7825 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7826 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7827 mCblk->serverIndex = 0;
7828 mCblk->clientIndex = 0;
7829 return BAD_VALUE;
7830 }
7831 status_t status = NO_ERROR;
7832 while (mCblk->serverIndex < mCblk->clientIndex) {
7833 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007834 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007835 int *p = (int *)(mBuffer + mCblk->serverIndex);
7836 int size = *p++;
7837 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007838 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007839 break;
7840 }
7841 effect_param_t *param = (effect_param_t *)p;
7842 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007843 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007844 mCblk->serverIndex += size;
7845 continue;
7846 }
Eric Laurent25f43952010-07-28 05:40:18 -07007847 uint32_t psize = sizeof(effect_param_t) +
7848 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7849 param->vsize;
7850 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7851 psize,
7852 p,
7853 &rsize,
7854 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007855 // stop at first error encountered
7856 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007857 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007858 *(int *)pReplyData = reply;
7859 break;
7860 } else if (reply != NO_ERROR) {
7861 *(int *)pReplyData = reply;
7862 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007863 }
7864 mCblk->serverIndex += size;
7865 }
7866 mCblk->serverIndex = 0;
7867 mCblk->clientIndex = 0;
7868 return status;
7869 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007870 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007871 return enable();
7872 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007873 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007874 return disable();
7875 }
7876
7877 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7878}
7879
Eric Laurent59255e42011-07-27 19:49:51 -07007880void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007881{
Steve Block3856b092011-10-20 11:56:00 +01007882 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007883
7884 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007885 mEnabled = enabled;
7886
Mathias Agopian65ab4712010-07-14 17:59:35 -07007887 if (signal && mEffectClient != 0) {
7888 mEffectClient->controlStatusChanged(hasControl);
7889 }
7890}
7891
Eric Laurent25f43952010-07-28 05:40:18 -07007892void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7893 uint32_t cmdSize,
7894 void *pCmdData,
7895 uint32_t replySize,
7896 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007897{
7898 if (mEffectClient != 0) {
7899 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7900 }
7901}
7902
7903
7904
7905void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7906{
7907 if (mEffectClient != 0) {
7908 mEffectClient->enableStatusChanged(enabled);
7909 }
7910}
7911
7912status_t AudioFlinger::EffectHandle::onTransact(
7913 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7914{
7915 return BnEffect::onTransact(code, data, reply, flags);
7916}
7917
7918
7919void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7920{
Glenn Kastena0d68332012-01-27 16:47:15 -08007921 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007922
7923 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08007924 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007925 mPriority,
7926 mHasControl,
7927 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007928 mCblk ? mCblk->clientIndex : 0,
7929 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007930 );
7931
7932 if (locked) {
7933 mCblk->lock.unlock();
7934 }
7935}
7936
7937#undef LOG_TAG
7938#define LOG_TAG "AudioFlinger::EffectChain"
7939
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007940AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007941 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007942 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007943 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7944 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007945{
Dima Zavinfce7a472011-04-19 22:30:36 -07007946 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007947 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007948 return;
7949 }
7950 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7951 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007952}
7953
7954AudioFlinger::EffectChain::~EffectChain()
7955{
7956 if (mOwnInBuffer) {
7957 delete mInBuffer;
7958 }
7959
7960}
7961
Eric Laurent59255e42011-07-27 19:49:51 -07007962// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007963sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007964{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007965 size_t size = mEffects.size();
7966
7967 for (size_t i = 0; i < size; i++) {
7968 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007969 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007970 }
7971 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007972 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007973}
7974
Eric Laurent59255e42011-07-27 19:49:51 -07007975// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007976sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007977{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007978 size_t size = mEffects.size();
7979
7980 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007981 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7982 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007983 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007984 }
7985 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007986 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007987}
7988
Eric Laurent59255e42011-07-27 19:49:51 -07007989// getEffectFromType_l() must be called with ThreadBase::mLock held
7990sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7991 const effect_uuid_t *type)
7992{
Eric Laurent59255e42011-07-27 19:49:51 -07007993 size_t size = mEffects.size();
7994
7995 for (size_t i = 0; i < size; i++) {
7996 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007997 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007998 }
7999 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008000 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008001}
8002
Mathias Agopian65ab4712010-07-14 17:59:35 -07008003// Must be called with EffectChain::mLock locked
8004void AudioFlinger::EffectChain::process_l()
8005{
Eric Laurentdac69112010-09-28 14:09:57 -07008006 sp<ThreadBase> thread = mThread.promote();
8007 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008008 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07008009 return;
8010 }
Dima Zavinfce7a472011-04-19 22:30:36 -07008011 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
8012 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08008013 // always process effects unless no more tracks are on the session and the effect tail
8014 // has been rendered
8015 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07008016 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008017 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07008018
Eric Laurent544fe9b2011-11-11 15:42:52 -08008019 if (!tracksOnSession && mTailBufferCount == 0) {
8020 doProcess = false;
8021 }
8022
8023 if (activeTrackCnt() == 0) {
8024 // if no track is active and the effect tail has not been rendered,
8025 // the input buffer must be cleared here as the mixer process will not do it
8026 if (tracksOnSession || mTailBufferCount > 0) {
8027 size_t numSamples = thread->frameCount() * thread->channelCount();
8028 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
8029 if (mTailBufferCount > 0) {
8030 mTailBufferCount--;
8031 }
8032 }
8033 }
Eric Laurentdac69112010-09-28 14:09:57 -07008034 }
8035
Mathias Agopian65ab4712010-07-14 17:59:35 -07008036 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08008037 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07008038 for (size_t i = 0; i < size; i++) {
8039 mEffects[i]->process();
8040 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008041 }
8042 for (size_t i = 0; i < size; i++) {
8043 mEffects[i]->updateState();
8044 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008045}
8046
Eric Laurentcab11242010-07-15 12:50:15 -07008047// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07008048status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008049{
8050 effect_descriptor_t desc = effect->desc();
8051 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
8052
8053 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07008054 effect->setChain(this);
8055 sp<ThreadBase> thread = mThread.promote();
8056 if (thread == 0) {
8057 return NO_INIT;
8058 }
8059 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008060
8061 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8062 // Auxiliary effects are inserted at the beginning of mEffects vector as
8063 // they are processed first and accumulated in chain input buffer
8064 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07008065
Mathias Agopian65ab4712010-07-14 17:59:35 -07008066 // the input buffer for auxiliary effect contains mono samples in
8067 // 32 bit format. This is to avoid saturation in AudoMixer
8068 // accumulation stage. Saturation is done in EffectModule::process() before
8069 // calling the process in effect engine
8070 size_t numSamples = thread->frameCount();
8071 int32_t *buffer = new int32_t[numSamples];
8072 memset(buffer, 0, numSamples * sizeof(int32_t));
8073 effect->setInBuffer((int16_t *)buffer);
8074 // auxiliary effects output samples to chain input buffer for further processing
8075 // by insert effects
8076 effect->setOutBuffer(mInBuffer);
8077 } else {
8078 // Insert effects are inserted at the end of mEffects vector as they are processed
8079 // after track and auxiliary effects.
8080 // Insert effect order as a function of indicated preference:
8081 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
8082 // another effect is present
8083 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
8084 // last effect claiming first position
8085 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
8086 // first effect claiming last position
8087 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
8088 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
8089 // already present
8090
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008091 size_t size = mEffects.size();
8092 size_t idx_insert = size;
8093 ssize_t idx_insert_first = -1;
8094 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008095
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008096 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008097 effect_descriptor_t d = mEffects[i]->desc();
8098 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
8099 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
8100 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
8101 // check invalid effect chaining combinations
8102 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
8103 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008104 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008105 return INVALID_OPERATION;
8106 }
8107 // remember position of first insert effect and by default
8108 // select this as insert position for new effect
8109 if (idx_insert == size) {
8110 idx_insert = i;
8111 }
8112 // remember position of last insert effect claiming
8113 // first position
8114 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
8115 idx_insert_first = i;
8116 }
8117 // remember position of first insert effect claiming
8118 // last position
8119 if (iPref == EFFECT_FLAG_INSERT_LAST &&
8120 idx_insert_last == -1) {
8121 idx_insert_last = i;
8122 }
8123 }
8124 }
8125
8126 // modify idx_insert from first position if needed
8127 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
8128 if (idx_insert_last != -1) {
8129 idx_insert = idx_insert_last;
8130 } else {
8131 idx_insert = size;
8132 }
8133 } else {
8134 if (idx_insert_first != -1) {
8135 idx_insert = idx_insert_first + 1;
8136 }
8137 }
8138
8139 // always read samples from chain input buffer
8140 effect->setInBuffer(mInBuffer);
8141
8142 // if last effect in the chain, output samples to chain
8143 // output buffer, otherwise to chain input buffer
8144 if (idx_insert == size) {
8145 if (idx_insert != 0) {
8146 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
8147 mEffects[idx_insert-1]->configure();
8148 }
8149 effect->setOutBuffer(mOutBuffer);
8150 } else {
8151 effect->setOutBuffer(mInBuffer);
8152 }
8153 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008154
Steve Block3856b092011-10-20 11:56:00 +01008155 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008156 }
8157 effect->configure();
8158 return NO_ERROR;
8159}
8160
Eric Laurentcab11242010-07-15 12:50:15 -07008161// removeEffect_l() must be called with PlaybackThread::mLock held
8162size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008163{
8164 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008165 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008166 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
8167
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008168 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008169 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07008170 // calling stop here will remove pre-processing effect from the audio HAL.
8171 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
8172 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07008173 if (mEffects[i]->state() == EffectModule::ACTIVE ||
8174 mEffects[i]->state() == EffectModule::STOPPING) {
8175 mEffects[i]->stop();
8176 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008177 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
8178 delete[] effect->inBuffer();
8179 } else {
8180 if (i == size - 1 && i != 0) {
8181 mEffects[i - 1]->setOutBuffer(mOutBuffer);
8182 mEffects[i - 1]->configure();
8183 }
8184 }
8185 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01008186 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008187 break;
8188 }
8189 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008190
8191 return mEffects.size();
8192}
8193
Eric Laurentcab11242010-07-15 12:50:15 -07008194// setDevice_l() must be called with PlaybackThread::mLock held
8195void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008196{
8197 size_t size = mEffects.size();
8198 for (size_t i = 0; i < size; i++) {
8199 mEffects[i]->setDevice(device);
8200 }
8201}
8202
Eric Laurentcab11242010-07-15 12:50:15 -07008203// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08008204void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008205{
8206 size_t size = mEffects.size();
8207 for (size_t i = 0; i < size; i++) {
8208 mEffects[i]->setMode(mode);
8209 }
8210}
8211
Eric Laurentcab11242010-07-15 12:50:15 -07008212// setVolume_l() must be called with PlaybackThread::mLock held
8213bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008214{
8215 uint32_t newLeft = *left;
8216 uint32_t newRight = *right;
8217 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07008218 int ctrlIdx = -1;
8219 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008220
Eric Laurentcab11242010-07-15 12:50:15 -07008221 // first update volume controller
8222 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07008223 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07008224 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
8225 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07008226 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07008227 break;
8228 }
8229 }
8230
8231 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07008232 if (hasControl) {
8233 *left = mNewLeftVolume;
8234 *right = mNewRightVolume;
8235 }
8236 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07008237 }
8238
8239 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07008240 mLeftVolume = newLeft;
8241 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008242
8243 // second get volume update from volume controller
8244 if (ctrlIdx >= 0) {
8245 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07008246 mNewLeftVolume = newLeft;
8247 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008248 }
8249 // then indicate volume to all other effects in chain.
8250 // Pass altered volume to effects before volume controller
8251 // and requested volume to effects after controller
8252 uint32_t lVol = newLeft;
8253 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008254
Mathias Agopian65ab4712010-07-14 17:59:35 -07008255 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07008256 if ((int)i == ctrlIdx) continue;
8257 // this also works for ctrlIdx == -1 when there is no volume controller
8258 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008259 lVol = *left;
8260 rVol = *right;
8261 }
8262 mEffects[i]->setVolume(&lVol, &rVol, false);
8263 }
8264 *left = newLeft;
8265 *right = newRight;
8266
8267 return hasControl;
8268}
8269
Mathias Agopian65ab4712010-07-14 17:59:35 -07008270status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
8271{
8272 const size_t SIZE = 256;
8273 char buffer[SIZE];
8274 String8 result;
8275
8276 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
8277 result.append(buffer);
8278
8279 bool locked = tryLock(mLock);
8280 // failed to lock - AudioFlinger is probably deadlocked
8281 if (!locked) {
8282 result.append("\tCould not lock mutex:\n");
8283 }
8284
Eric Laurentcab11242010-07-15 12:50:15 -07008285 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
8286 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008287 mEffects.size(),
8288 (uint32_t)mInBuffer,
8289 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008290 mActiveTrackCnt);
8291 result.append(buffer);
8292 write(fd, result.string(), result.size());
8293
8294 for (size_t i = 0; i < mEffects.size(); ++i) {
8295 sp<EffectModule> effect = mEffects[i];
8296 if (effect != 0) {
8297 effect->dump(fd, args);
8298 }
8299 }
8300
8301 if (locked) {
8302 mLock.unlock();
8303 }
8304
8305 return NO_ERROR;
8306}
8307
Eric Laurent59255e42011-07-27 19:49:51 -07008308// must be called with ThreadBase::mLock held
8309void AudioFlinger::EffectChain::setEffectSuspended_l(
8310 const effect_uuid_t *type, bool suspend)
8311{
8312 sp<SuspendedEffectDesc> desc;
8313 // use effect type UUID timelow as key as there is no real risk of identical
8314 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008315 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008316 if (suspend) {
8317 if (index >= 0) {
8318 desc = mSuspendedEffects.valueAt(index);
8319 } else {
8320 desc = new SuspendedEffectDesc();
8321 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
8322 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01008323 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008324 }
8325 if (desc->mRefCount++ == 0) {
8326 sp<EffectModule> effect = getEffectIfEnabled(type);
8327 if (effect != 0) {
8328 desc->mEffect = effect;
8329 effect->setSuspended(true);
8330 effect->setEnabled(false);
8331 }
8332 }
8333 } else {
8334 if (index < 0) {
8335 return;
8336 }
8337 desc = mSuspendedEffects.valueAt(index);
8338 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008339 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008340 desc->mRefCount = 1;
8341 }
8342 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01008343 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008344 if (desc->mEffect != 0) {
8345 sp<EffectModule> effect = desc->mEffect.promote();
8346 if (effect != 0) {
8347 effect->setSuspended(false);
8348 sp<EffectHandle> handle = effect->controlHandle();
8349 if (handle != 0) {
8350 effect->setEnabled(handle->enabled());
8351 }
8352 }
8353 desc->mEffect.clear();
8354 }
8355 mSuspendedEffects.removeItemsAt(index);
8356 }
8357 }
8358}
8359
8360// must be called with ThreadBase::mLock held
8361void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
8362{
8363 sp<SuspendedEffectDesc> desc;
8364
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008365 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07008366 if (suspend) {
8367 if (index >= 0) {
8368 desc = mSuspendedEffects.valueAt(index);
8369 } else {
8370 desc = new SuspendedEffectDesc();
8371 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01008372 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07008373 }
8374 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08008375 Vector< sp<EffectModule> > effects;
8376 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07008377 for (size_t i = 0; i < effects.size(); i++) {
8378 setEffectSuspended_l(&effects[i]->desc().type, true);
8379 }
8380 }
8381 } else {
8382 if (index < 0) {
8383 return;
8384 }
8385 desc = mSuspendedEffects.valueAt(index);
8386 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008387 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008388 desc->mRefCount = 1;
8389 }
8390 if (--desc->mRefCount == 0) {
8391 Vector<const effect_uuid_t *> types;
8392 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
8393 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
8394 continue;
8395 }
8396 types.add(&mSuspendedEffects.valueAt(i)->mType);
8397 }
8398 for (size_t i = 0; i < types.size(); i++) {
8399 setEffectSuspended_l(types[i], false);
8400 }
Steve Block3856b092011-10-20 11:56:00 +01008401 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008402 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
8403 }
8404 }
8405}
8406
Eric Laurent6bffdb82011-09-23 08:40:41 -07008407
8408// The volume effect is used for automated tests only
8409#ifndef OPENSL_ES_H_
8410static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
8411 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
8412const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
8413#endif //OPENSL_ES_H_
8414
Eric Laurentdb7c0792011-08-10 10:37:50 -07008415bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
8416{
8417 // auxiliary effects and visualizer are never suspended on output mix
8418 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8419 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07008420 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8421 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008422 return false;
8423 }
8424 return true;
8425}
8426
Glenn Kastend0539712012-01-30 12:56:03 -08008427void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07008428{
Glenn Kastend0539712012-01-30 12:56:03 -08008429 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07008430 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08008431 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8432 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07008433 }
Eric Laurent59255e42011-07-27 19:49:51 -07008434 }
Eric Laurent59255e42011-07-27 19:49:51 -07008435}
8436
8437sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8438 const effect_uuid_t *type)
8439{
Glenn Kasten090f0192012-01-30 13:00:02 -08008440 sp<EffectModule> effect = getEffectFromType_l(type);
8441 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008442}
8443
8444void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8445 bool enabled)
8446{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008447 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008448 if (enabled) {
8449 if (index < 0) {
8450 // if the effect is not suspend check if all effects are suspended
8451 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8452 if (index < 0) {
8453 return;
8454 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07008455 if (!isEffectEligibleForSuspend(effect->desc())) {
8456 return;
8457 }
Eric Laurent59255e42011-07-27 19:49:51 -07008458 setEffectSuspended_l(&effect->desc().type, enabled);
8459 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07008460 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008461 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07008462 return;
8463 }
Eric Laurent59255e42011-07-27 19:49:51 -07008464 }
Steve Block3856b092011-10-20 11:56:00 +01008465 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008466 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008467 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8468 // if effect is requested to suspended but was not yet enabled, supend it now.
8469 if (desc->mEffect == 0) {
8470 desc->mEffect = effect;
8471 effect->setEnabled(false);
8472 effect->setSuspended(true);
8473 }
8474 } else {
8475 if (index < 0) {
8476 return;
8477 }
Steve Block3856b092011-10-20 11:56:00 +01008478 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008479 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008480 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8481 desc->mEffect.clear();
8482 effect->setSuspended(false);
8483 }
8484}
8485
Mathias Agopian65ab4712010-07-14 17:59:35 -07008486#undef LOG_TAG
8487#define LOG_TAG "AudioFlinger"
8488
8489// ----------------------------------------------------------------------------
8490
8491status_t AudioFlinger::onTransact(
8492 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8493{
8494 return BnAudioFlinger::onTransact(code, data, reply, flags);
8495}
8496
Mathias Agopian65ab4712010-07-14 17:59:35 -07008497}; // namespace android