blob: b6ac359578e9f1730d6ba8f86189effe3d663b48 [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 Grossman4ff14ba2012-02-08 16:37:41 -08003899 mTimedSilenceBuffer(NULL),
3900 mTimedSilenceBufferSize(0),
3901 mTimedAudioOutputOnTime(false),
3902 mMediaTimeTransformValid(false)
3903{
3904 LocalClock lc;
3905 mLocalTimeFreq = lc.getLocalFreq();
3906
3907 mLocalTimeToSampleTransform.a_zero = 0;
3908 mLocalTimeToSampleTransform.b_zero = 0;
3909 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3910 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3911 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3912 &mLocalTimeToSampleTransform.a_to_b_denom);
3913}
3914
3915AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3916 mClient->releaseTimedTrack();
3917 delete [] mTimedSilenceBuffer;
3918}
3919
3920status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3921 size_t size, sp<IMemory>* buffer) {
3922
3923 Mutex::Autolock _l(mTimedBufferQueueLock);
3924
3925 trimTimedBufferQueue_l();
3926
3927 // lazily initialize the shared memory heap for timed buffers
3928 if (mTimedMemoryDealer == NULL) {
3929 const int kTimedBufferHeapSize = 512 << 10;
3930
3931 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3932 "AudioFlingerTimed");
3933 if (mTimedMemoryDealer == NULL)
3934 return NO_MEMORY;
3935 }
3936
3937 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3938 if (newBuffer == NULL) {
3939 newBuffer = mTimedMemoryDealer->allocate(size);
3940 if (newBuffer == NULL)
3941 return NO_MEMORY;
3942 }
3943
3944 *buffer = newBuffer;
3945 return NO_ERROR;
3946}
3947
3948// caller must hold mTimedBufferQueueLock
3949void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
3950 int64_t mediaTimeNow;
3951 {
3952 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3953 if (!mMediaTimeTransformValid)
3954 return;
3955
3956 int64_t targetTimeNow;
3957 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
3958 ? mCCHelper.getCommonTime(&targetTimeNow)
3959 : mCCHelper.getLocalTime(&targetTimeNow);
3960
3961 if (OK != res)
3962 return;
3963
3964 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
3965 &mediaTimeNow)) {
3966 return;
3967 }
3968 }
3969
3970 size_t trimIndex;
3971 for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
3972 if (mTimedBufferQueue[trimIndex].pts() > mediaTimeNow)
3973 break;
3974 }
3975
3976 if (trimIndex) {
3977 mTimedBufferQueue.removeItemsAt(0, trimIndex);
3978 }
3979}
3980
3981status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
3982 const sp<IMemory>& buffer, int64_t pts) {
3983
3984 {
3985 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3986 if (!mMediaTimeTransformValid)
3987 return INVALID_OPERATION;
3988 }
3989
3990 Mutex::Autolock _l(mTimedBufferQueueLock);
3991
3992 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
3993
3994 return NO_ERROR;
3995}
3996
3997status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
3998 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
3999
4000 ALOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
4001 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4002 target);
4003
4004 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4005 target == TimedAudioTrack::COMMON_TIME)) {
4006 return BAD_VALUE;
4007 }
4008
4009 Mutex::Autolock lock(mMediaTimeTransformLock);
4010 mMediaTimeTransform = xform;
4011 mMediaTimeTransformTarget = target;
4012 mMediaTimeTransformValid = true;
4013
4014 return NO_ERROR;
4015}
4016
4017#define min(a, b) ((a) < (b) ? (a) : (b))
4018
4019// implementation of getNextBuffer for tracks whose buffers have timestamps
4020status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4021 AudioBufferProvider::Buffer* buffer, int64_t pts)
4022{
4023 if (pts == AudioBufferProvider::kInvalidPTS) {
4024 buffer->raw = 0;
4025 buffer->frameCount = 0;
4026 return INVALID_OPERATION;
4027 }
4028
John Grossman4ff14ba2012-02-08 16:37:41 -08004029 Mutex::Autolock _l(mTimedBufferQueueLock);
4030
4031 while (true) {
4032
4033 // if we have no timed buffers, then fail
4034 if (mTimedBufferQueue.isEmpty()) {
4035 buffer->raw = 0;
4036 buffer->frameCount = 0;
4037 return NOT_ENOUGH_DATA;
4038 }
4039
4040 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4041
4042 // calculate the PTS of the head of the timed buffer queue expressed in
4043 // local time
4044 int64_t headLocalPTS;
4045 {
4046 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4047
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004048 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08004049
4050 if (mMediaTimeTransform.a_to_b_denom == 0) {
4051 // the transform represents a pause, so yield silence
4052 timedYieldSilence(buffer->frameCount, buffer);
4053 return NO_ERROR;
4054 }
4055
4056 int64_t transformedPTS;
4057 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4058 &transformedPTS)) {
4059 // the transform failed. this shouldn't happen, but if it does
4060 // then just drop this buffer
4061 ALOGW("timedGetNextBuffer transform failed");
4062 buffer->raw = 0;
4063 buffer->frameCount = 0;
4064 mTimedBufferQueue.removeAt(0);
4065 return NO_ERROR;
4066 }
4067
4068 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
4069 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
4070 &headLocalPTS)) {
4071 buffer->raw = 0;
4072 buffer->frameCount = 0;
4073 return INVALID_OPERATION;
4074 }
4075 } else {
4076 headLocalPTS = transformedPTS;
4077 }
4078 }
4079
4080 // adjust the head buffer's PTS to reflect the portion of the head buffer
4081 // that has already been consumed
4082 int64_t effectivePTS = headLocalPTS +
4083 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4084
4085 // Calculate the delta in samples between the head of the input buffer
4086 // queue and the start of the next output buffer that will be written.
4087 // If the transformation fails because of over or underflow, it means
4088 // that the sample's position in the output stream is so far out of
4089 // whack that it should just be dropped.
4090 int64_t sampleDelta;
4091 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4092 ALOGV("*** head buffer is too far from PTS: dropped buffer");
4093 mTimedBufferQueue.removeAt(0);
4094 continue;
4095 }
4096 if (!mLocalTimeToSampleTransform.doForwardTransform(
4097 (effectivePTS - pts) << 32, &sampleDelta)) {
4098 ALOGV("*** too late during sample rate transform: dropped buffer");
4099 mTimedBufferQueue.removeAt(0);
4100 continue;
4101 }
4102
4103 ALOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
4104 __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
4105 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
4106 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
4107
4108 // if the delta between the ideal placement for the next input sample and
4109 // the current output position is within this threshold, then we will
4110 // concatenate the next input samples to the previous output
4111 const int64_t kSampleContinuityThreshold =
4112 (static_cast<int64_t>(sampleRate()) << 32) / 10;
4113
4114 // if this is the first buffer of audio that we're emitting from this track
4115 // then it should be almost exactly on time.
4116 const int64_t kSampleStartupThreshold = 1LL << 32;
4117
4118 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
4119 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
4120 // the next input is close enough to being on time, so concatenate it
4121 // with the last output
4122 timedYieldSamples(buffer);
4123
4124 ALOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4125 return NO_ERROR;
4126 } else if (sampleDelta > 0) {
4127 // the gap between the current output position and the proper start of
4128 // the next input sample is too big, so fill it with silence
4129 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4130
4131 timedYieldSilence(framesUntilNextInput, buffer);
4132 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4133 return NO_ERROR;
4134 } else {
4135 // the next input sample is late
4136 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4137 size_t onTimeSamplePosition =
4138 head.position() + lateFrames * mCblk->frameSize;
4139
4140 if (onTimeSamplePosition > head.buffer()->size()) {
4141 // all the remaining samples in the head are too late, so
4142 // drop it and move on
4143 ALOGV("*** too late: dropped buffer");
4144 mTimedBufferQueue.removeAt(0);
4145 continue;
4146 } else {
4147 // skip over the late samples
4148 head.setPosition(onTimeSamplePosition);
4149
4150 // yield the available samples
4151 timedYieldSamples(buffer);
4152
4153 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4154 return NO_ERROR;
4155 }
4156 }
4157 }
4158}
4159
4160// Yield samples from the timed buffer queue head up to the given output
4161// buffer's capacity.
4162//
4163// Caller must hold mTimedBufferQueueLock
4164void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples(
4165 AudioBufferProvider::Buffer* buffer) {
4166
4167 const TimedBuffer& head = mTimedBufferQueue[0];
4168
4169 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4170 head.position());
4171
4172 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4173 mCblk->frameSize);
4174 size_t framesRequested = buffer->frameCount;
4175 buffer->frameCount = min(framesLeftInHead, framesRequested);
4176
4177 mTimedAudioOutputOnTime = true;
4178}
4179
4180// Yield samples of silence up to the given output buffer's capacity
4181//
4182// Caller must hold mTimedBufferQueueLock
4183void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence(
4184 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4185
4186 // lazily allocate a buffer filled with silence
4187 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4188 delete [] mTimedSilenceBuffer;
4189 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4190 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4191 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4192 }
4193
4194 buffer->raw = mTimedSilenceBuffer;
4195 size_t framesRequested = buffer->frameCount;
4196 buffer->frameCount = min(numFrames, framesRequested);
4197
4198 mTimedAudioOutputOnTime = false;
4199}
4200
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004201// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004202void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4203 AudioBufferProvider::Buffer* buffer) {
4204
4205 Mutex::Autolock _l(mTimedBufferQueueLock);
4206
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004207 // If the buffer which was just released is part of the buffer at the head
4208 // of the queue, be sure to update the amt of the buffer which has been
4209 // consumed. If the buffer being returned is not part of the head of the
4210 // queue, its either because the buffer is part of the silence buffer, or
4211 // because the head of the timed queue was trimmed after the mixer called
4212 // getNextBuffer but before the mixer called releaseBuffer.
4213 if ((buffer->raw != mTimedSilenceBuffer) && mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004214 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004215
4216 void* start = head.buffer()->pointer();
Glenn Kastenf063b492012-02-17 16:24:10 -08004217 void* end = (char *) head.buffer()->pointer() + head.buffer()->size();
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004218
4219 if ((buffer->raw >= start) && (buffer->raw <= end)) {
4220 head.setPosition(head.position() +
4221 (buffer->frameCount * mCblk->frameSize));
4222 if (static_cast<size_t>(head.position()) >= head.buffer()->size()) {
4223 mTimedBufferQueue.removeAt(0);
4224 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004225 }
4226 }
4227
4228 buffer->raw = 0;
4229 buffer->frameCount = 0;
4230}
4231
4232uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4233 Mutex::Autolock _l(mTimedBufferQueueLock);
4234
4235 uint32_t frames = 0;
4236 for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4237 const TimedBuffer& tb = mTimedBufferQueue[i];
4238 frames += (tb.buffer()->size() - tb.position()) / mCblk->frameSize;
4239 }
4240
4241 return frames;
4242}
4243
4244AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4245 : mPTS(0), mPosition(0) {}
4246
4247AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4248 const sp<IMemory>& buffer, int64_t pts)
4249 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4250
Mathias Agopian65ab4712010-07-14 17:59:35 -07004251// ----------------------------------------------------------------------------
4252
4253// RecordTrack constructor must be called with AudioFlinger::mLock held
4254AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004255 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004256 const sp<Client>& client,
4257 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004258 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004259 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004260 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004261 int sessionId)
4262 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004263 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004264 mOverflow(false)
4265{
4266 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004267 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
4268 if (format == AUDIO_FORMAT_PCM_16_BIT) {
4269 mCblk->frameSize = mChannelCount * sizeof(int16_t);
4270 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
4271 mCblk->frameSize = mChannelCount * sizeof(int8_t);
4272 } else {
4273 mCblk->frameSize = sizeof(int8_t);
4274 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004275 }
4276}
4277
4278AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4279{
4280 sp<ThreadBase> thread = mThread.promote();
4281 if (thread != 0) {
4282 AudioSystem::releaseInput(thread->id());
4283 }
4284}
4285
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004286// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004287status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004288{
4289 audio_track_cblk_t* cblk = this->cblk();
4290 uint32_t framesAvail;
4291 uint32_t framesReq = buffer->frameCount;
4292
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004293 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004294 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004295 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004296 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004297 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004298 }
4299
4300 framesAvail = cblk->framesAvailable_l();
4301
Glenn Kastenf6b16782011-12-15 09:51:17 -08004302 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004303 uint32_t s = cblk->server;
4304 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4305
4306 if (framesReq > framesAvail) {
4307 framesReq = framesAvail;
4308 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004309 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004310 framesReq = bufferEnd - s;
4311 }
4312
4313 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004314 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004315
4316 buffer->frameCount = framesReq;
4317 return NO_ERROR;
4318 }
4319
4320getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004321 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004322 buffer->frameCount = 0;
4323 return NOT_ENOUGH_DATA;
4324}
4325
Eric Laurenta011e352012-03-29 15:51:43 -07004326status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid,
4327 AudioSystem::sync_event_t event,
4328 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004329{
4330 sp<ThreadBase> thread = mThread.promote();
4331 if (thread != 0) {
4332 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurenta011e352012-03-29 15:51:43 -07004333 return recordThread->start(this, tid, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004334 } else {
4335 return BAD_VALUE;
4336 }
4337}
4338
4339void AudioFlinger::RecordThread::RecordTrack::stop()
4340{
4341 sp<ThreadBase> thread = mThread.promote();
4342 if (thread != 0) {
4343 RecordThread *recordThread = (RecordThread *)thread.get();
4344 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004345 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08004346 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07004347 // read from buffer
4348 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004349 }
4350}
4351
4352void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4353{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004354 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004355 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004356 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004357 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004358 mSessionId,
4359 mFrameCount,
4360 mState,
4361 mCblk->sampleRate,
4362 mCblk->server,
4363 mCblk->user);
4364}
4365
4366
4367// ----------------------------------------------------------------------------
4368
4369AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004370 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004371 DuplicatingThread *sourceThread,
4372 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004373 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004374 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004375 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07004376 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
4377 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004378 mActive(false), mSourceThread(sourceThread)
4379{
4380
Mathias Agopian65ab4712010-07-14 17:59:35 -07004381 if (mCblk != NULL) {
4382 mCblk->flags |= CBLK_DIRECTION_OUT;
4383 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004384 mOutBuffer.frameCount = 0;
4385 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01004386 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004387 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4388 mCblk, mBuffer, mCblk->buffers,
4389 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004390 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004391 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004392 }
4393}
4394
4395AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4396{
4397 clearBufferQueue();
4398}
4399
Eric Laurenta011e352012-03-29 15:51:43 -07004400status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid,
4401 AudioSystem::sync_event_t event,
4402 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004403{
Eric Laurenta011e352012-03-29 15:51:43 -07004404 status_t status = Track::start(tid, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004405 if (status != NO_ERROR) {
4406 return status;
4407 }
4408
4409 mActive = true;
4410 mRetryCount = 127;
4411 return status;
4412}
4413
4414void AudioFlinger::PlaybackThread::OutputTrack::stop()
4415{
4416 Track::stop();
4417 clearBufferQueue();
4418 mOutBuffer.frameCount = 0;
4419 mActive = false;
4420}
4421
4422bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4423{
4424 Buffer *pInBuffer;
4425 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004426 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004427 bool outputBufferFull = false;
4428 inBuffer.frameCount = frames;
4429 inBuffer.i16 = data;
4430
4431 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4432
4433 if (!mActive && frames != 0) {
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004434 start(0);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004435 sp<ThreadBase> thread = mThread.promote();
4436 if (thread != 0) {
4437 MixerThread *mixerThread = (MixerThread *)thread.get();
4438 if (mCblk->frameCount > frames){
4439 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4440 uint32_t startFrames = (mCblk->frameCount - frames);
4441 pInBuffer = new Buffer;
4442 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4443 pInBuffer->frameCount = startFrames;
4444 pInBuffer->i16 = pInBuffer->mBuffer;
4445 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4446 mBufferQueue.add(pInBuffer);
4447 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004448 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004449 }
4450 }
4451 }
4452 }
4453
4454 while (waitTimeLeftMs) {
4455 // First write pending buffers, then new data
4456 if (mBufferQueue.size()) {
4457 pInBuffer = mBufferQueue.itemAt(0);
4458 } else {
4459 pInBuffer = &inBuffer;
4460 }
4461
4462 if (pInBuffer->frameCount == 0) {
4463 break;
4464 }
4465
4466 if (mOutBuffer.frameCount == 0) {
4467 mOutBuffer.frameCount = pInBuffer->frameCount;
4468 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08004469 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01004470 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004471 outputBufferFull = true;
4472 break;
4473 }
4474 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4475 if (waitTimeLeftMs >= waitTimeMs) {
4476 waitTimeLeftMs -= waitTimeMs;
4477 } else {
4478 waitTimeLeftMs = 0;
4479 }
4480 }
4481
4482 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4483 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4484 mCblk->stepUser(outFrames);
4485 pInBuffer->frameCount -= outFrames;
4486 pInBuffer->i16 += outFrames * channelCount;
4487 mOutBuffer.frameCount -= outFrames;
4488 mOutBuffer.i16 += outFrames * channelCount;
4489
4490 if (pInBuffer->frameCount == 0) {
4491 if (mBufferQueue.size()) {
4492 mBufferQueue.removeAt(0);
4493 delete [] pInBuffer->mBuffer;
4494 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01004495 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004496 } else {
4497 break;
4498 }
4499 }
4500 }
4501
4502 // If we could not write all frames, allocate a buffer and queue it for next time.
4503 if (inBuffer.frameCount) {
4504 sp<ThreadBase> thread = mThread.promote();
4505 if (thread != 0 && !thread->standby()) {
4506 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4507 pInBuffer = new Buffer;
4508 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4509 pInBuffer->frameCount = inBuffer.frameCount;
4510 pInBuffer->i16 = pInBuffer->mBuffer;
4511 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4512 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01004513 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004514 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004515 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004516 }
4517 }
4518 }
4519
4520 // Calling write() with a 0 length buffer, means that no more data will be written:
4521 // If no more buffers are pending, fill output track buffer to make sure it is started
4522 // by output mixer.
4523 if (frames == 0 && mBufferQueue.size() == 0) {
4524 if (mCblk->user < mCblk->frameCount) {
4525 frames = mCblk->frameCount - mCblk->user;
4526 pInBuffer = new Buffer;
4527 pInBuffer->mBuffer = new int16_t[frames * channelCount];
4528 pInBuffer->frameCount = frames;
4529 pInBuffer->i16 = pInBuffer->mBuffer;
4530 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4531 mBufferQueue.add(pInBuffer);
4532 } else if (mActive) {
4533 stop();
4534 }
4535 }
4536
4537 return outputBufferFull;
4538}
4539
4540status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4541{
4542 int active;
4543 status_t result;
4544 audio_track_cblk_t* cblk = mCblk;
4545 uint32_t framesReq = buffer->frameCount;
4546
Steve Block3856b092011-10-20 11:56:00 +01004547// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004548 buffer->frameCount = 0;
4549
4550 uint32_t framesAvail = cblk->framesAvailable();
4551
4552
4553 if (framesAvail == 0) {
4554 Mutex::Autolock _l(cblk->lock);
4555 goto start_loop_here;
4556 while (framesAvail == 0) {
4557 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004558 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004559 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004560 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004561 }
4562 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4563 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004564 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004565 }
4566 // read the server count again
4567 start_loop_here:
4568 framesAvail = cblk->framesAvailable_l();
4569 }
4570 }
4571
4572// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004573// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004574// }
4575
4576 if (framesReq > framesAvail) {
4577 framesReq = framesAvail;
4578 }
4579
4580 uint32_t u = cblk->user;
4581 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4582
Marco Nelissena1472d92012-03-30 14:36:54 -07004583 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004584 framesReq = bufferEnd - u;
4585 }
4586
4587 buffer->frameCount = framesReq;
4588 buffer->raw = (void *)cblk->buffer(u);
4589 return NO_ERROR;
4590}
4591
4592
4593void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4594{
4595 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004596
4597 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004598 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004599 delete [] pBuffer->mBuffer;
4600 delete pBuffer;
4601 }
4602 mBufferQueue.clear();
4603}
4604
4605// ----------------------------------------------------------------------------
4606
4607AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4608 : RefBase(),
4609 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08004610 // 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 -07004611 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08004612 mPid(pid),
4613 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004614{
4615 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4616}
4617
4618// Client destructor must be called with AudioFlinger::mLock held
4619AudioFlinger::Client::~Client()
4620{
4621 mAudioFlinger->removeClient_l(mPid);
4622}
4623
Glenn Kasten435dbe62012-01-30 10:15:48 -08004624sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004625{
4626 return mMemoryDealer;
4627}
4628
John Grossman4ff14ba2012-02-08 16:37:41 -08004629// Reserve one of the limited slots for a timed audio track associated
4630// with this client
4631bool AudioFlinger::Client::reserveTimedTrack()
4632{
4633 const int kMaxTimedTracksPerClient = 4;
4634
4635 Mutex::Autolock _l(mTimedTrackLock);
4636
4637 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4638 ALOGW("can not create timed track - pid %d has exceeded the limit",
4639 mPid);
4640 return false;
4641 }
4642
4643 mTimedTrackCount++;
4644 return true;
4645}
4646
4647// Release a slot for a timed audio track
4648void AudioFlinger::Client::releaseTimedTrack()
4649{
4650 Mutex::Autolock _l(mTimedTrackLock);
4651 mTimedTrackCount--;
4652}
4653
Mathias Agopian65ab4712010-07-14 17:59:35 -07004654// ----------------------------------------------------------------------------
4655
4656AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4657 const sp<IAudioFlingerClient>& client,
4658 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004659 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004660{
4661}
4662
4663AudioFlinger::NotificationClient::~NotificationClient()
4664{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004665}
4666
4667void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4668{
4669 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08004670 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004671}
4672
4673// ----------------------------------------------------------------------------
4674
4675AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4676 : BnAudioTrack(),
4677 mTrack(track)
4678{
4679}
4680
4681AudioFlinger::TrackHandle::~TrackHandle() {
4682 // just stop the track on deletion, associated resources
4683 // will be freed from the main thread once all pending buffers have
4684 // been played. Unless it's not in the active track list, in which
4685 // case we free everything now...
4686 mTrack->destroy();
4687}
4688
Glenn Kasten90716c52012-01-26 13:40:12 -08004689sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4690 return mTrack->getCblk();
4691}
4692
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004693status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4694 return mTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004695}
4696
4697void AudioFlinger::TrackHandle::stop() {
4698 mTrack->stop();
4699}
4700
4701void AudioFlinger::TrackHandle::flush() {
4702 mTrack->flush();
4703}
4704
4705void AudioFlinger::TrackHandle::mute(bool e) {
4706 mTrack->mute(e);
4707}
4708
4709void AudioFlinger::TrackHandle::pause() {
4710 mTrack->pause();
4711}
4712
Mathias Agopian65ab4712010-07-14 17:59:35 -07004713status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4714{
4715 return mTrack->attachAuxEffect(EffectId);
4716}
4717
John Grossman4ff14ba2012-02-08 16:37:41 -08004718status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4719 sp<IMemory>* buffer) {
4720 if (!mTrack->isTimedTrack())
4721 return INVALID_OPERATION;
4722
4723 PlaybackThread::TimedTrack* tt =
4724 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4725 return tt->allocateTimedBuffer(size, buffer);
4726}
4727
4728status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4729 int64_t pts) {
4730 if (!mTrack->isTimedTrack())
4731 return INVALID_OPERATION;
4732
4733 PlaybackThread::TimedTrack* tt =
4734 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4735 return tt->queueTimedBuffer(buffer, pts);
4736}
4737
4738status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4739 const LinearTransform& xform, int target) {
4740
4741 if (!mTrack->isTimedTrack())
4742 return INVALID_OPERATION;
4743
4744 PlaybackThread::TimedTrack* tt =
4745 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4746 return tt->setMediaTimeTransform(
4747 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4748}
4749
Mathias Agopian65ab4712010-07-14 17:59:35 -07004750status_t AudioFlinger::TrackHandle::onTransact(
4751 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4752{
4753 return BnAudioTrack::onTransact(code, data, reply, flags);
4754}
4755
4756// ----------------------------------------------------------------------------
4757
4758sp<IAudioRecord> AudioFlinger::openRecord(
4759 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004760 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004761 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004762 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004763 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004764 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08004765 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004766 int *sessionId,
4767 status_t *status)
4768{
4769 sp<RecordThread::RecordTrack> recordTrack;
4770 sp<RecordHandle> recordHandle;
4771 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004772 status_t lStatus;
4773 RecordThread *thread;
4774 size_t inFrameCount;
4775 int lSessionId;
4776
4777 // check calling permissions
4778 if (!recordingAllowed()) {
4779 lStatus = PERMISSION_DENIED;
4780 goto Exit;
4781 }
4782
4783 // add client to list
4784 { // scope for mLock
4785 Mutex::Autolock _l(mLock);
4786 thread = checkRecordThread_l(input);
4787 if (thread == NULL) {
4788 lStatus = BAD_VALUE;
4789 goto Exit;
4790 }
4791
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004792 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004793
4794 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004795 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004796 lSessionId = *sessionId;
4797 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004798 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004799 if (sessionId != NULL) {
4800 *sessionId = lSessionId;
4801 }
4802 }
4803 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004804 recordTrack = thread->createRecordTrack_l(client,
4805 sampleRate,
4806 format,
4807 channelMask,
4808 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004809 lSessionId,
4810 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004811 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004812 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004813 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4814 // destructor is called by the TrackBase destructor with mLock held
4815 client.clear();
4816 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004817 goto Exit;
4818 }
4819
4820 // return to handle to client
4821 recordHandle = new RecordHandle(recordTrack);
4822 lStatus = NO_ERROR;
4823
4824Exit:
4825 if (status) {
4826 *status = lStatus;
4827 }
4828 return recordHandle;
4829}
4830
4831// ----------------------------------------------------------------------------
4832
4833AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4834 : BnAudioRecord(),
4835 mRecordTrack(recordTrack)
4836{
4837}
4838
4839AudioFlinger::RecordHandle::~RecordHandle() {
4840 stop();
4841}
4842
Glenn Kasten90716c52012-01-26 13:40:12 -08004843sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4844 return mRecordTrack->getCblk();
4845}
4846
Eric Laurenta011e352012-03-29 15:51:43 -07004847status_t AudioFlinger::RecordHandle::start(pid_t tid, int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01004848 ALOGV("RecordHandle::start()");
Eric Laurenta011e352012-03-29 15:51:43 -07004849 return mRecordTrack->start(tid, (AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004850}
4851
4852void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004853 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004854 mRecordTrack->stop();
4855}
4856
Mathias Agopian65ab4712010-07-14 17:59:35 -07004857status_t AudioFlinger::RecordHandle::onTransact(
4858 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4859{
4860 return BnAudioRecord::onTransact(code, data, reply, flags);
4861}
4862
4863// ----------------------------------------------------------------------------
4864
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004865AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4866 AudioStreamIn *input,
4867 uint32_t sampleRate,
4868 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004869 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004870 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004871 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004872 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4873 // mRsmpInIndex and mInputBytes set by readInputParameters()
4874 mReqChannelCount(popcount(channels)),
4875 mReqSampleRate(sampleRate)
4876 // mBytesRead is only meaningful while active, and so is cleared in start()
4877 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004878{
Glenn Kasten480b4682012-02-28 12:30:08 -08004879 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07004880
Mathias Agopian65ab4712010-07-14 17:59:35 -07004881 readInputParameters();
4882}
4883
4884
4885AudioFlinger::RecordThread::~RecordThread()
4886{
4887 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004888 delete mResampler;
4889 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004890}
4891
4892void AudioFlinger::RecordThread::onFirstRef()
4893{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004894 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004895}
4896
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004897status_t AudioFlinger::RecordThread::readyToRun()
4898{
4899 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004900 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004901 return status;
4902}
4903
Mathias Agopian65ab4712010-07-14 17:59:35 -07004904bool AudioFlinger::RecordThread::threadLoop()
4905{
4906 AudioBufferProvider::Buffer buffer;
4907 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004908 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004909
Eric Laurent44d98482010-09-30 16:12:31 -07004910 nsecs_t lastWarning = 0;
4911
Eric Laurentfeb0db62011-07-22 09:04:31 -07004912 acquireWakeLock();
4913
Mathias Agopian65ab4712010-07-14 17:59:35 -07004914 // start recording
4915 while (!exitPending()) {
4916
4917 processConfigEvents();
4918
4919 { // scope for mLock
4920 Mutex::Autolock _l(mLock);
4921 checkForNewParameters_l();
4922 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4923 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004924 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004925 mStandby = true;
4926 }
4927
4928 if (exitPending()) break;
4929
Eric Laurentfeb0db62011-07-22 09:04:31 -07004930 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004931 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004932 // go to sleep
4933 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004934 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004935 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004936 continue;
4937 }
4938 if (mActiveTrack != 0) {
4939 if (mActiveTrack->mState == TrackBase::PAUSING) {
4940 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004941 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004942 mStandby = true;
4943 }
4944 mActiveTrack.clear();
4945 mStartStopCond.broadcast();
4946 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4947 if (mReqChannelCount != mActiveTrack->channelCount()) {
4948 mActiveTrack.clear();
4949 mStartStopCond.broadcast();
4950 } else if (mBytesRead != 0) {
4951 // record start succeeds only if first read from audio input
4952 // succeeds
4953 if (mBytesRead > 0) {
4954 mActiveTrack->mState = TrackBase::ACTIVE;
4955 } else {
4956 mActiveTrack.clear();
4957 }
4958 mStartStopCond.broadcast();
4959 }
4960 mStandby = false;
4961 }
4962 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004963 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004964 }
4965
4966 if (mActiveTrack != 0) {
4967 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4968 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004969 unlockEffectChains(effectChains);
4970 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004971 continue;
4972 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004973 for (size_t i = 0; i < effectChains.size(); i ++) {
4974 effectChains[i]->process_l();
4975 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004976
Mathias Agopian65ab4712010-07-14 17:59:35 -07004977 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004978 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004979 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004980 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004981 // no resampling
4982 while (framesOut) {
4983 size_t framesIn = mFrameCount - mRsmpInIndex;
4984 if (framesIn) {
4985 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4986 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4987 if (framesIn > framesOut)
4988 framesIn = framesOut;
4989 mRsmpInIndex += framesIn;
4990 framesOut -= framesIn;
4991 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004992 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004993 memcpy(dst, src, framesIn * mFrameSize);
4994 } else {
4995 int16_t *src16 = (int16_t *)src;
4996 int16_t *dst16 = (int16_t *)dst;
4997 if (mChannelCount == 1) {
4998 while (framesIn--) {
4999 *dst16++ = *src16;
5000 *dst16++ = *src16++;
5001 }
5002 } else {
5003 while (framesIn--) {
5004 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
5005 src16 += 2;
5006 }
5007 }
5008 }
5009 }
5010 if (framesOut && mFrameCount == mRsmpInIndex) {
5011 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005012 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005013 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005014 framesOut = 0;
5015 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07005016 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005017 mRsmpInIndex = 0;
5018 }
5019 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005020 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005021 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5022 // Force input into standby so that it tries to
5023 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005024 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005025 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005026 }
5027 mRsmpInIndex = mFrameCount;
5028 framesOut = 0;
5029 buffer.frameCount = 0;
5030 }
5031 }
5032 }
5033 } else {
5034 // resampling
5035
5036 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
5037 // alter output frame count as if we were expecting stereo samples
5038 if (mChannelCount == 1 && mReqChannelCount == 1) {
5039 framesOut >>= 1;
5040 }
5041 mResampler->resample(mRsmpOutBuffer, framesOut, this);
5042 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
5043 // are 32 bit aligned which should be always true.
5044 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005045 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005046 // the resampler always outputs stereo samples: do post stereo to mono conversion
5047 int16_t *src = (int16_t *)mRsmpOutBuffer;
5048 int16_t *dst = buffer.i16;
5049 while (framesOut--) {
5050 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
5051 src += 2;
5052 }
5053 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005054 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005055 }
5056
5057 }
Eric Laurenta011e352012-03-29 15:51:43 -07005058 if (mFramestoDrop == 0) {
5059 mActiveTrack->releaseBuffer(&buffer);
5060 } else {
5061 if (mFramestoDrop > 0) {
5062 mFramestoDrop -= buffer.frameCount;
5063 if (mFramestoDrop < 0) {
5064 mFramestoDrop = 0;
5065 }
5066 }
5067 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005068 mActiveTrack->overflow();
5069 }
5070 // client isn't retrieving buffers fast enough
5071 else {
Eric Laurent44d98482010-09-30 16:12:31 -07005072 if (!mActiveTrack->setOverflow()) {
5073 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08005074 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005075 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07005076 lastWarning = now;
5077 }
5078 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005079 // Release the processor for a while before asking for a new buffer.
5080 // This will give the application more chance to read from the buffer and
5081 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005082 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005083 }
5084 }
Eric Laurentec437d82011-07-26 20:54:46 -07005085 // enable changes in effect chain
5086 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005087 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005088 }
5089
5090 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005091 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005092 }
5093 mActiveTrack.clear();
5094
5095 mStartStopCond.broadcast();
5096
Eric Laurentfeb0db62011-07-22 09:04:31 -07005097 releaseWakeLock();
5098
Steve Block3856b092011-10-20 11:56:00 +01005099 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005100 return false;
5101}
5102
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005103
5104sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5105 const sp<AudioFlinger::Client>& client,
5106 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005107 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005108 int channelMask,
5109 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005110 int sessionId,
5111 status_t *status)
5112{
5113 sp<RecordTrack> track;
5114 status_t lStatus;
5115
5116 lStatus = initCheck();
5117 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005118 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005119 goto Exit;
5120 }
5121
5122 { // scope for mLock
5123 Mutex::Autolock _l(mLock);
5124
5125 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005126 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005127
Glenn Kasten7378ca52012-01-20 13:44:40 -08005128 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005129 lStatus = NO_MEMORY;
5130 goto Exit;
5131 }
5132
5133 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005134 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5135 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005136 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005137 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5138 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005139 }
5140 lStatus = NO_ERROR;
5141
5142Exit:
5143 if (status) {
5144 *status = lStatus;
5145 }
5146 return track;
5147}
5148
Eric Laurenta011e352012-03-29 15:51:43 -07005149status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5150 pid_t tid, AudioSystem::sync_event_t event,
5151 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005152{
Eric Laurenta011e352012-03-29 15:51:43 -07005153 ALOGV("RecordThread::start tid=%d, event %d, triggerSession %d", tid, event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005154 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005155 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07005156
5157 if (event == AudioSystem::SYNC_EVENT_NONE) {
5158 mSyncStartEvent.clear();
5159 mFramestoDrop = 0;
5160 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
5161 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
5162 triggerSession,
5163 recordTrack->sessionId(),
5164 syncStartEventCallback,
5165 this);
5166 mFramestoDrop = -1;
5167 }
5168
Mathias Agopian65ab4712010-07-14 17:59:35 -07005169 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005170 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005171 if (mActiveTrack != 0) {
5172 if (recordTrack != mActiveTrack.get()) {
5173 status = -EBUSY;
5174 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5175 mActiveTrack->mState = TrackBase::ACTIVE;
5176 }
5177 return status;
5178 }
5179
5180 recordTrack->mState = TrackBase::IDLE;
5181 mActiveTrack = recordTrack;
5182 mLock.unlock();
5183 status_t status = AudioSystem::startInput(mId);
5184 mLock.lock();
5185 if (status != NO_ERROR) {
5186 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07005187 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005188 return status;
5189 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005190 mRsmpInIndex = mFrameCount;
5191 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005192 if (mResampler != NULL) {
5193 mResampler->reset();
5194 }
5195 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005196 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005197 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005198 mWaitWorkCV.signal();
5199 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005200 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005201 mActiveTrack.clear();
5202 status = INVALID_OPERATION;
5203 goto startError;
5204 }
5205 mStartStopCond.wait(mLock);
5206 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005207 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005208 status = BAD_VALUE;
5209 goto startError;
5210 }
Steve Block3856b092011-10-20 11:56:00 +01005211 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005212 return status;
5213 }
5214startError:
5215 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07005216 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005217 return status;
5218}
5219
Eric Laurenta011e352012-03-29 15:51:43 -07005220void AudioFlinger::RecordThread::clearSyncStartEvent()
5221{
5222 if (mSyncStartEvent != 0) {
5223 mSyncStartEvent->cancel();
5224 }
5225 mSyncStartEvent.clear();
5226}
5227
5228void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5229{
5230 sp<SyncEvent> strongEvent = event.promote();
5231
5232 if (strongEvent != 0) {
5233 RecordThread *me = (RecordThread *)strongEvent->cookie();
5234 me->handleSyncStartEvent(strongEvent);
5235 }
5236}
5237
5238void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
5239{
5240 ALOGV("handleSyncStartEvent() mActiveTrack %p session %d event->listenerSession() %d",
5241 mActiveTrack.get(),
5242 mActiveTrack.get() ? mActiveTrack->sessionId() : 0,
5243 event->listenerSession());
5244
5245 if (mActiveTrack != 0 &&
5246 event == mSyncStartEvent) {
5247 // TODO: use actual buffer filling status instead of 2 buffers when info is available
5248 // from audio HAL
5249 mFramestoDrop = mFrameCount * 2;
5250 mSyncStartEvent.clear();
5251 }
5252}
5253
Mathias Agopian65ab4712010-07-14 17:59:35 -07005254void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005255 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005256 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005257 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005258 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005259 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5260 mActiveTrack->mState = TrackBase::PAUSING;
5261 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005262 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005263 return;
5264 }
5265 mStartStopCond.wait(mLock);
5266 // if we have been restarted, recordTrack == mActiveTrack.get() here
5267 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5268 mLock.unlock();
5269 AudioSystem::stopInput(mId);
5270 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005271 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005272 }
5273 }
5274 }
5275}
5276
Eric Laurenta011e352012-03-29 15:51:43 -07005277bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
5278{
5279 return false;
5280}
5281
5282status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
5283{
5284 if (!isValidSyncEvent(event)) {
5285 return BAD_VALUE;
5286 }
5287
5288 Mutex::Autolock _l(mLock);
5289
5290 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
5291 mTrack->setSyncEvent(event);
5292 return NO_ERROR;
5293 }
5294 return NAME_NOT_FOUND;
5295}
5296
Mathias Agopian65ab4712010-07-14 17:59:35 -07005297status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5298{
5299 const size_t SIZE = 256;
5300 char buffer[SIZE];
5301 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005302
5303 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5304 result.append(buffer);
5305
5306 if (mActiveTrack != 0) {
5307 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005308 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005309 mActiveTrack->dump(buffer, SIZE);
5310 result.append(buffer);
5311
5312 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5313 result.append(buffer);
5314 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5315 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005316 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005317 result.append(buffer);
5318 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5319 result.append(buffer);
5320 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5321 result.append(buffer);
5322
5323
5324 } else {
5325 result.append("No record client\n");
5326 }
5327 write(fd, result.string(), result.size());
5328
5329 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005330 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005331
5332 return NO_ERROR;
5333}
5334
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005335// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005336status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005337{
5338 size_t framesReq = buffer->frameCount;
5339 size_t framesReady = mFrameCount - mRsmpInIndex;
5340 int channelCount;
5341
5342 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005343 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005344 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005345 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005346 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5347 // Force input into standby so that it tries to
5348 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005349 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005350 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005351 }
Glenn Kastene0feee32011-12-13 11:53:26 -08005352 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005353 buffer->frameCount = 0;
5354 return NOT_ENOUGH_DATA;
5355 }
5356 mRsmpInIndex = 0;
5357 framesReady = mFrameCount;
5358 }
5359
5360 if (framesReq > framesReady) {
5361 framesReq = framesReady;
5362 }
5363
5364 if (mChannelCount == 1 && mReqChannelCount == 2) {
5365 channelCount = 1;
5366 } else {
5367 channelCount = 2;
5368 }
5369 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5370 buffer->frameCount = framesReq;
5371 return NO_ERROR;
5372}
5373
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005374// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07005375void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5376{
5377 mRsmpInIndex += buffer->frameCount;
5378 buffer->frameCount = 0;
5379}
5380
5381bool AudioFlinger::RecordThread::checkForNewParameters_l()
5382{
5383 bool reconfig = false;
5384
5385 while (!mNewParameters.isEmpty()) {
5386 status_t status = NO_ERROR;
5387 String8 keyValuePair = mNewParameters[0];
5388 AudioParameter param = AudioParameter(keyValuePair);
5389 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08005390 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005391 int reqSamplingRate = mReqSampleRate;
5392 int reqChannelCount = mReqChannelCount;
5393
5394 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5395 reqSamplingRate = value;
5396 reconfig = true;
5397 }
5398 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08005399 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005400 reconfig = true;
5401 }
5402 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005403 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005404 reconfig = true;
5405 }
5406 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5407 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08005408 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005409 // if frame count is changed after track creation
5410 if (mActiveTrack != 0) {
5411 status = INVALID_OPERATION;
5412 } else {
5413 reconfig = true;
5414 }
5415 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005416 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5417 // forward device change to effects that have requested to be
5418 // aware of attached audio device.
5419 for (size_t i = 0; i < mEffectChains.size(); i++) {
5420 mEffectChains[i]->setDevice_l(value);
5421 }
5422 // store input device and output device but do not forward output device to audio HAL.
5423 // Note that status is ignored by the caller for output device
5424 // (see AudioFlinger::setParameters()
5425 if (value & AUDIO_DEVICE_OUT_ALL) {
5426 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5427 status = BAD_VALUE;
5428 } else {
5429 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07005430 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5431 if (mTrack != NULL) {
5432 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005433 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005434 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5435 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5436 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005437 }
5438 mDevice |= (uint32_t)value;
5439 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005440 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005441 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005442 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005443 mInput->stream->common.standby(&mInput->stream->common);
5444 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5445 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005446 }
5447 if (reconfig) {
5448 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005449 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005450 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005451 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08005452 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
5453 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005454 status = NO_ERROR;
5455 }
5456 if (status == NO_ERROR) {
5457 readInputParameters();
5458 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5459 }
5460 }
5461 }
5462
5463 mNewParameters.removeAt(0);
5464
5465 mParamStatus = status;
5466 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07005467 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5468 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08005469 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005470 }
5471 return reconfig;
5472}
5473
5474String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5475{
Dima Zavinfce7a472011-04-19 22:30:36 -07005476 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005477 String8 out_s8 = String8();
5478
5479 Mutex::Autolock _l(mLock);
5480 if (initCheck() != NO_ERROR) {
5481 return out_s8;
5482 }
Dima Zavinfce7a472011-04-19 22:30:36 -07005483
Dima Zavin799a70e2011-04-18 16:57:27 -07005484 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07005485 out_s8 = String8(s);
5486 free(s);
5487 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005488}
5489
5490void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5491 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08005492 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005493
5494 switch (event) {
5495 case AudioSystem::INPUT_OPENED:
5496 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005497 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005498 desc.samplingRate = mSampleRate;
5499 desc.format = mFormat;
5500 desc.frameCount = mFrameCount;
5501 desc.latency = 0;
5502 param2 = &desc;
5503 break;
5504
5505 case AudioSystem::INPUT_CLOSED:
5506 default:
5507 break;
5508 }
5509 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5510}
5511
5512void AudioFlinger::RecordThread::readInputParameters()
5513{
Glenn Kastene9dd0172012-01-27 18:08:45 -08005514 delete mRsmpInBuffer;
5515 // mRsmpInBuffer is always assigned a new[] below
5516 delete mRsmpOutBuffer;
5517 mRsmpOutBuffer = NULL;
5518 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08005519 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005520
Dima Zavin799a70e2011-04-18 16:57:27 -07005521 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005522 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5523 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07005524 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08005525 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07005526 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005527 mFrameCount = mInputBytes / mFrameSize;
5528 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5529
Glenn Kasten53d76db2012-03-08 12:32:47 -08005530 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005531 {
5532 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005533 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5534 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005535 if (mChannelCount == 1 && mReqChannelCount == 2) {
5536 channelCount = 1;
5537 } else {
5538 channelCount = 2;
5539 }
5540 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5541 mResampler->setSampleRate(mSampleRate);
5542 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5543 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5544
5545 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5546 if (mChannelCount == 1 && mReqChannelCount == 1) {
5547 mFrameCount >>= 1;
5548 }
5549
5550 }
5551 mRsmpInIndex = mFrameCount;
5552}
5553
5554unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5555{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005556 Mutex::Autolock _l(mLock);
5557 if (initCheck() != NO_ERROR) {
5558 return 0;
5559 }
5560
Dima Zavin799a70e2011-04-18 16:57:27 -07005561 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005562}
5563
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005564uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5565{
5566 Mutex::Autolock _l(mLock);
5567 uint32_t result = 0;
5568 if (getEffectChain_l(sessionId) != 0) {
5569 result = EFFECT_SESSION;
5570 }
5571
5572 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5573 result |= TRACK_SESSION;
5574 }
5575
5576 return result;
5577}
5578
Eric Laurent59bd0da2011-08-01 09:52:20 -07005579AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5580{
5581 Mutex::Autolock _l(mLock);
5582 return mTrack;
5583}
5584
Glenn Kastenaed850d2012-01-26 09:46:34 -08005585AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005586{
5587 Mutex::Autolock _l(mLock);
5588 return mInput;
5589}
5590
5591AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5592{
5593 Mutex::Autolock _l(mLock);
5594 AudioStreamIn *input = mInput;
5595 mInput = NULL;
5596 return input;
5597}
5598
5599// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08005600audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005601{
5602 if (mInput == NULL) {
5603 return NULL;
5604 }
5605 return &mInput->stream->common;
5606}
5607
5608
Mathias Agopian65ab4712010-07-14 17:59:35 -07005609// ----------------------------------------------------------------------------
5610
Eric Laurenta4c5a552012-03-29 10:12:40 -07005611audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
5612{
5613 if (!settingsAllowed()) {
5614 return 0;
5615 }
5616 Mutex::Autolock _l(mLock);
5617 return loadHwModule_l(name);
5618}
5619
5620// loadHwModule_l() must be called with AudioFlinger::mLock held
5621audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
5622{
5623 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
5624 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
5625 ALOGW("loadHwModule() module %s already loaded", name);
5626 return mAudioHwDevs.keyAt(i);
5627 }
5628 }
5629
5630 const hw_module_t *mod;
5631 audio_hw_device_t *dev;
5632
5633 int rc = load_audio_interface(name, &mod, &dev);
5634 if (rc) {
5635 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
5636 return 0;
5637 }
5638
5639 mHardwareStatus = AUDIO_HW_INIT;
5640 rc = dev->init_check(dev);
5641 mHardwareStatus = AUDIO_HW_IDLE;
5642 if (rc) {
5643 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
5644 return 0;
5645 }
5646
5647 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
5648 (NULL != dev->set_master_volume)) {
5649 AutoMutex lock(mHardwareLock);
5650 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
5651 dev->set_master_volume(dev, mMasterVolume);
5652 mHardwareStatus = AUDIO_HW_IDLE;
5653 }
5654
5655 audio_module_handle_t handle = nextUniqueId();
5656 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
5657
5658 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
5659 name, mod->name, mod->id, handle);
5660
5661 return handle;
5662
5663}
5664
5665audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
5666 audio_devices_t *pDevices,
5667 uint32_t *pSamplingRate,
5668 audio_format_t *pFormat,
5669 audio_channel_mask_t *pChannelMask,
5670 uint32_t *pLatencyMs,
5671 audio_policy_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005672{
5673 status_t status;
5674 PlaybackThread *thread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005675 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005676 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Eric Laurenta4c5a552012-03-29 10:12:40 -07005677 audio_channel_mask_t channelMask = pChannelMask ? *pChannelMask : 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005678 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07005679 audio_stream_out_t *outStream;
5680 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005681
Eric Laurenta4c5a552012-03-29 10:12:40 -07005682 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
5683 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07005684 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurenta4c5a552012-03-29 10:12:40 -07005685 samplingRate,
5686 format,
5687 channelMask,
5688 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005689
5690 if (pDevices == NULL || *pDevices == 0) {
5691 return 0;
5692 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005693
Mathias Agopian65ab4712010-07-14 17:59:35 -07005694 Mutex::Autolock _l(mLock);
5695
Eric Laurenta4c5a552012-03-29 10:12:40 -07005696 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07005697 if (outHwDev == NULL)
5698 return 0;
5699
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005700 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Glenn Kasten58f30212012-01-12 12:27:51 -08005701 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Eric Laurenta4c5a552012-03-29 10:12:40 -07005702 &channelMask, &samplingRate, &outStream);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005703 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01005704 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005705 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005706 samplingRate,
5707 format,
Eric Laurenta4c5a552012-03-29 10:12:40 -07005708 channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005709 status);
5710
Dima Zavin799a70e2011-04-18 16:57:27 -07005711 if (outStream != NULL) {
5712 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005713 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07005714
Dima Zavinfce7a472011-04-19 22:30:36 -07005715 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5716 (format != AUDIO_FORMAT_PCM_16_BIT) ||
Eric Laurenta4c5a552012-03-29 10:12:40 -07005717 (channelMask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005718 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005719 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005720 } else {
5721 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005722 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005723 }
5724 mPlaybackThreads.add(id, thread);
5725
Glenn Kastena0d68332012-01-27 16:47:15 -08005726 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5727 if (pFormat != NULL) *pFormat = format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07005728 if (pChannelMask != NULL) *pChannelMask = channelMask;
Glenn Kastena0d68332012-01-27 16:47:15 -08005729 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005730
5731 // notify client processes of the new output creation
5732 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07005733
5734 // the first primary output opened designates the primary hw device
5735 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_POLICY_OUTPUT_FLAG_PRIMARY)) {
5736 ALOGI("Using module %d has the primary audio interface", module);
5737 mPrimaryHardwareDev = outHwDev;
5738
5739 AutoMutex lock(mHardwareLock);
5740 mHardwareStatus = AUDIO_HW_SET_MODE;
5741 outHwDev->set_mode(outHwDev, mMode);
5742
5743 // Determine the level of master volume support the primary audio HAL has,
5744 // and set the initial master volume at the same time.
5745 float initialVolume = 1.0;
5746 mMasterVolumeSupportLvl = MVS_NONE;
5747
5748 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
5749 if ((NULL != outHwDev->get_master_volume) &&
5750 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
5751 mMasterVolumeSupportLvl = MVS_FULL;
5752 } else {
5753 mMasterVolumeSupportLvl = MVS_SETONLY;
5754 initialVolume = 1.0;
5755 }
5756
5757 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
5758 if ((NULL == outHwDev->set_master_volume) ||
5759 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
5760 mMasterVolumeSupportLvl = MVS_NONE;
5761 }
5762 // now that we have a primary device, initialize master volume on other devices
5763 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
5764 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
5765
5766 if ((dev != mPrimaryHardwareDev) &&
5767 (NULL != dev->set_master_volume)) {
5768 dev->set_master_volume(dev, initialVolume);
5769 }
5770 }
5771 mHardwareStatus = AUDIO_HW_IDLE;
5772 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
5773 ? initialVolume
5774 : 1.0;
5775 mMasterVolume = initialVolume;
5776 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005777 return id;
5778 }
5779
5780 return 0;
5781}
5782
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005783audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
5784 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005785{
5786 Mutex::Autolock _l(mLock);
5787 MixerThread *thread1 = checkMixerThread_l(output1);
5788 MixerThread *thread2 = checkMixerThread_l(output2);
5789
5790 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005791 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005792 return 0;
5793 }
5794
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005795 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005796 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5797 thread->addOutputTrack(thread2);
5798 mPlaybackThreads.add(id, thread);
5799 // notify client processes of the new output creation
5800 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5801 return id;
5802}
5803
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005804status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005805{
5806 // keep strong reference on the playback thread so that
5807 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005808 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005809 {
5810 Mutex::Autolock _l(mLock);
5811 thread = checkPlaybackThread_l(output);
5812 if (thread == NULL) {
5813 return BAD_VALUE;
5814 }
5815
Steve Block3856b092011-10-20 11:56:00 +01005816 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005817
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005818 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005819 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005820 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005821 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5822 dupThread->removeOutputTrack((MixerThread *)thread.get());
5823 }
5824 }
5825 }
Glenn Kastena1117922012-01-26 10:53:32 -08005826 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005827 mPlaybackThreads.removeItem(output);
5828 }
5829 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005830 // The thread entity (active unit of execution) is no longer running here,
5831 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005832
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005833 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005834 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005835 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005836 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005837 out->hwDev->close_output_stream(out->hwDev, out->stream);
5838 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005839 }
5840 return NO_ERROR;
5841}
5842
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005843status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005844{
5845 Mutex::Autolock _l(mLock);
5846 PlaybackThread *thread = checkPlaybackThread_l(output);
5847
5848 if (thread == NULL) {
5849 return BAD_VALUE;
5850 }
5851
Steve Block3856b092011-10-20 11:56:00 +01005852 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005853 thread->suspend();
5854
5855 return NO_ERROR;
5856}
5857
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005858status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005859{
5860 Mutex::Autolock _l(mLock);
5861 PlaybackThread *thread = checkPlaybackThread_l(output);
5862
5863 if (thread == NULL) {
5864 return BAD_VALUE;
5865 }
5866
Steve Block3856b092011-10-20 11:56:00 +01005867 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005868
5869 thread->restore();
5870
5871 return NO_ERROR;
5872}
5873
Eric Laurenta4c5a552012-03-29 10:12:40 -07005874audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
5875 audio_devices_t *pDevices,
5876 uint32_t *pSamplingRate,
5877 audio_format_t *pFormat,
5878 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005879{
5880 status_t status;
5881 RecordThread *thread = NULL;
5882 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005883 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Eric Laurenta4c5a552012-03-29 10:12:40 -07005884 audio_channel_mask_t channelMask = pChannelMask ? *pChannelMask : 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005885 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005886 audio_format_t reqFormat = format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07005887 audio_channel_mask_t reqChannels = channelMask;
Dima Zavin799a70e2011-04-18 16:57:27 -07005888 audio_stream_in_t *inStream;
5889 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005890
5891 if (pDevices == NULL || *pDevices == 0) {
5892 return 0;
5893 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005894
Mathias Agopian65ab4712010-07-14 17:59:35 -07005895 Mutex::Autolock _l(mLock);
5896
Eric Laurenta4c5a552012-03-29 10:12:40 -07005897 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07005898 if (inHwDev == NULL)
5899 return 0;
5900
Glenn Kasten58f30212012-01-12 12:27:51 -08005901 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Eric Laurenta4c5a552012-03-29 10:12:40 -07005902 &channelMask, &samplingRate,
5903 (audio_in_acoustics_t)0,
Dima Zavin799a70e2011-04-18 16:57:27 -07005904 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07005905 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005906 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005907 samplingRate,
5908 format,
Eric Laurenta4c5a552012-03-29 10:12:40 -07005909 channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005910 status);
5911
5912 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5913 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5914 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005915 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005916 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005917 (samplingRate <= 2 * reqSamplingRate) &&
Eric Laurenta4c5a552012-03-29 10:12:40 -07005918 (popcount(channelMask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01005919 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005920 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Eric Laurenta4c5a552012-03-29 10:12:40 -07005921 &channelMask, &samplingRate,
5922 (audio_in_acoustics_t)0,
Dima Zavin799a70e2011-04-18 16:57:27 -07005923 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005924 }
5925
Dima Zavin799a70e2011-04-18 16:57:27 -07005926 if (inStream != NULL) {
5927 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5928
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005929 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005930 // Start record thread
5931 // RecorThread require both input and output device indication to forward to audio
5932 // pre processing modules
5933 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5934 thread = new RecordThread(this,
5935 input,
5936 reqSamplingRate,
5937 reqChannels,
5938 id,
5939 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005940 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005941 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005942 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5943 if (pFormat != NULL) *pFormat = format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07005944 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005945
Dima Zavin799a70e2011-04-18 16:57:27 -07005946 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005947
5948 // notify client processes of the new input creation
5949 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5950 return id;
5951 }
5952
5953 return 0;
5954}
5955
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005956status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005957{
5958 // keep strong reference on the record thread so that
5959 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005960 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005961 {
5962 Mutex::Autolock _l(mLock);
5963 thread = checkRecordThread_l(input);
5964 if (thread == NULL) {
5965 return BAD_VALUE;
5966 }
5967
Steve Block3856b092011-10-20 11:56:00 +01005968 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08005969 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005970 mRecordThreads.removeItem(input);
5971 }
5972 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005973 // The thread entity (active unit of execution) is no longer running here,
5974 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005975
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005976 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005977 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005978 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005979 in->hwDev->close_input_stream(in->hwDev, in->stream);
5980 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005981
5982 return NO_ERROR;
5983}
5984
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005985status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005986{
5987 Mutex::Autolock _l(mLock);
5988 MixerThread *dstThread = checkMixerThread_l(output);
5989 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005990 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005991 return BAD_VALUE;
5992 }
5993
Steve Block3856b092011-10-20 11:56:00 +01005994 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005995 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5996
5997 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5998 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08005999 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006000 MixerThread *srcThread = (MixerThread *)thread;
6001 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006002 }
Eric Laurentde070132010-07-13 04:45:46 -07006003 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006004
6005 return NO_ERROR;
6006}
6007
6008
6009int AudioFlinger::newAudioSessionId()
6010{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006011 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006012}
6013
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006014void AudioFlinger::acquireAudioSessionId(int audioSession)
6015{
6016 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006017 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006018 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006019 size_t num = mAudioSessionRefs.size();
6020 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006021 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006022 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6023 ref->mCnt++;
6024 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006025 return;
6026 }
6027 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006028 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
6029 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006030}
6031
6032void AudioFlinger::releaseAudioSessionId(int audioSession)
6033{
6034 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006035 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006036 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006037 size_t num = mAudioSessionRefs.size();
6038 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006039 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006040 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6041 ref->mCnt--;
6042 ALOGV(" decremented refcount to %d", ref->mCnt);
6043 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006044 mAudioSessionRefs.removeAt(i);
6045 delete ref;
6046 purgeStaleEffects_l();
6047 }
6048 return;
6049 }
6050 }
Steve Block5ff1dd52012-01-05 23:22:43 +00006051 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006052}
6053
6054void AudioFlinger::purgeStaleEffects_l() {
6055
Steve Block3856b092011-10-20 11:56:00 +01006056 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006057
6058 Vector< sp<EffectChain> > chains;
6059
6060 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6061 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
6062 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6063 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07006064 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
6065 chains.push(ec);
6066 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006067 }
6068 }
6069 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6070 sp<RecordThread> t = mRecordThreads.valueAt(i);
6071 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6072 sp<EffectChain> ec = t->mEffectChains[j];
6073 chains.push(ec);
6074 }
6075 }
6076
6077 for (size_t i = 0; i < chains.size(); i++) {
6078 sp<EffectChain> ec = chains[i];
6079 int sessionid = ec->sessionId();
6080 sp<ThreadBase> t = ec->mThread.promote();
6081 if (t == 0) {
6082 continue;
6083 }
6084 size_t numsessionrefs = mAudioSessionRefs.size();
6085 bool found = false;
6086 for (size_t k = 0; k < numsessionrefs; k++) {
6087 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006088 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01006089 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006090 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006091 found = true;
6092 break;
6093 }
6094 }
6095 if (!found) {
6096 // remove all effects from the chain
6097 while (ec->mEffects.size()) {
6098 sp<EffectModule> effect = ec->mEffects[0];
6099 effect->unPin();
6100 Mutex::Autolock _l (t->mLock);
6101 t->removeEffect_l(effect);
6102 for (size_t j = 0; j < effect->mHandles.size(); j++) {
6103 sp<EffectHandle> handle = effect->mHandles[j].promote();
6104 if (handle != 0) {
6105 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07006106 if (handle->mHasControl && handle->mEnabled) {
6107 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
6108 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006109 }
6110 }
6111 AudioSystem::unregisterEffect(effect->id());
6112 }
6113 }
6114 }
6115 return;
6116}
6117
Mathias Agopian65ab4712010-07-14 17:59:35 -07006118// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006119AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006120{
Glenn Kastena1117922012-01-26 10:53:32 -08006121 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006122}
6123
6124// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006125AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006126{
6127 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08006128 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006129}
6130
6131// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006132AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006133{
Glenn Kastena1117922012-01-26 10:53:32 -08006134 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006135}
6136
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006137uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07006138{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006139 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006140}
6141
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006142AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006143{
6144 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6145 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006146 AudioStreamOut *output = thread->getOutput();
6147 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006148 return thread;
6149 }
6150 }
6151 return NULL;
6152}
6153
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006154uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006155{
6156 PlaybackThread *thread = primaryPlaybackThread_l();
6157
6158 if (thread == NULL) {
6159 return 0;
6160 }
6161
6162 return thread->device();
6163}
6164
Eric Laurenta011e352012-03-29 15:51:43 -07006165sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
6166 int triggerSession,
6167 int listenerSession,
6168 sync_event_callback_t callBack,
6169 void *cookie)
6170{
6171 Mutex::Autolock _l(mLock);
6172
6173 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
6174 status_t playStatus = NAME_NOT_FOUND;
6175 status_t recStatus = NAME_NOT_FOUND;
6176 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6177 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
6178 if (playStatus == NO_ERROR) {
6179 return event;
6180 }
6181 }
6182 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6183 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
6184 if (recStatus == NO_ERROR) {
6185 return event;
6186 }
6187 }
6188 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
6189 mPendingSyncEvents.add(event);
6190 } else {
6191 ALOGV("createSyncEvent() invalid event %d", event->type());
6192 event.clear();
6193 }
6194 return event;
6195}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006196
Mathias Agopian65ab4712010-07-14 17:59:35 -07006197// ----------------------------------------------------------------------------
6198// Effect management
6199// ----------------------------------------------------------------------------
6200
6201
Glenn Kastenf587ba52012-01-26 16:25:10 -08006202status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006203{
6204 Mutex::Autolock _l(mLock);
6205 return EffectQueryNumberEffects(numEffects);
6206}
6207
Glenn Kastenf587ba52012-01-26 16:25:10 -08006208status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006209{
6210 Mutex::Autolock _l(mLock);
6211 return EffectQueryEffect(index, descriptor);
6212}
6213
Glenn Kasten5e92a782012-01-30 07:40:52 -08006214status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08006215 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006216{
6217 Mutex::Autolock _l(mLock);
6218 return EffectGetDescriptor(pUuid, descriptor);
6219}
6220
6221
Mathias Agopian65ab4712010-07-14 17:59:35 -07006222sp<IEffect> AudioFlinger::createEffect(pid_t pid,
6223 effect_descriptor_t *pDesc,
6224 const sp<IEffectClient>& effectClient,
6225 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006226 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006227 int sessionId,
6228 status_t *status,
6229 int *id,
6230 int *enabled)
6231{
6232 status_t lStatus = NO_ERROR;
6233 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006234 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006235
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006236 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006237 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006238
6239 if (pDesc == NULL) {
6240 lStatus = BAD_VALUE;
6241 goto Exit;
6242 }
6243
Eric Laurent84e9a102010-09-23 16:10:16 -07006244 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006245 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006246 lStatus = PERMISSION_DENIED;
6247 goto Exit;
6248 }
6249
Dima Zavinfce7a472011-04-19 22:30:36 -07006250 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07006251 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08006252 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006253 lStatus = PERMISSION_DENIED;
6254 goto Exit;
6255 }
6256
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006257 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006258 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006259 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07006260 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07006261 lStatus = BAD_VALUE;
6262 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07006263 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006264 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006265 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07006266 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006267 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07006268 }
6269 }
6270
Mathias Agopian65ab4712010-07-14 17:59:35 -07006271 {
6272 Mutex::Autolock _l(mLock);
6273
Mathias Agopian65ab4712010-07-14 17:59:35 -07006274
6275 if (!EffectIsNullUuid(&pDesc->uuid)) {
6276 // if uuid is specified, request effect descriptor
6277 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
6278 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006279 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006280 goto Exit;
6281 }
6282 } else {
6283 // if uuid is not specified, look for an available implementation
6284 // of the required type in effect factory
6285 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006286 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006287 lStatus = BAD_VALUE;
6288 goto Exit;
6289 }
6290 uint32_t numEffects = 0;
6291 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006292 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07006293 bool found = false;
6294
6295 lStatus = EffectQueryNumberEffects(&numEffects);
6296 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006297 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006298 goto Exit;
6299 }
6300 for (uint32_t i = 0; i < numEffects; i++) {
6301 lStatus = EffectQueryEffect(i, &desc);
6302 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006303 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006304 continue;
6305 }
6306 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
6307 // If matching type found save effect descriptor. If the session is
6308 // 0 and the effect is not auxiliary, continue enumeration in case
6309 // an auxiliary version of this effect type is available
6310 found = true;
6311 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07006312 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006313 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6314 break;
6315 }
6316 }
6317 }
6318 if (!found) {
6319 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00006320 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006321 goto Exit;
6322 }
6323 // For same effect type, chose auxiliary version over insert version if
6324 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07006325 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006326 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
6327 memcpy(&desc, &d, sizeof(effect_descriptor_t));
6328 }
6329 }
6330
6331 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07006332 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006333 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6334 lStatus = INVALID_OPERATION;
6335 goto Exit;
6336 }
6337
Eric Laurent59255e42011-07-27 19:49:51 -07006338 // check recording permission for visualizer
6339 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
6340 !recordingAllowed()) {
6341 lStatus = PERMISSION_DENIED;
6342 goto Exit;
6343 }
6344
Mathias Agopian65ab4712010-07-14 17:59:35 -07006345 // return effect descriptor
6346 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
6347
6348 // If output is not specified try to find a matching audio session ID in one of the
6349 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07006350 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
6351 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006352 // Note: io is never 0 when creating an effect on an input
6353 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006354 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07006355 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6356 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006357 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07006358 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07006359 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006360 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006361 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006362 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6363 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6364 io = mRecordThreads.keyAt(i);
6365 break;
6366 }
6367 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006368 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006369 // If no output thread contains the requested session ID, default to
6370 // first output. The effect chain will be moved to the correct output
6371 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006372 if (io == 0 && mPlaybackThreads.size()) {
6373 io = mPlaybackThreads.keyAt(0);
6374 }
Steve Block3856b092011-10-20 11:56:00 +01006375 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006376 }
6377 ThreadBase *thread = checkRecordThread_l(io);
6378 if (thread == NULL) {
6379 thread = checkPlaybackThread_l(io);
6380 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00006381 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006382 lStatus = BAD_VALUE;
6383 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07006384 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006385 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006386
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006387 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006388
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006389 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07006390 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6391 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006392 if (handle != 0 && id != NULL) {
6393 *id = handle->id();
6394 }
6395 }
6396
6397Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006398 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006399 *status = lStatus;
6400 }
6401 return handle;
6402}
6403
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006404status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
6405 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07006406{
Steve Block3856b092011-10-20 11:56:00 +01006407 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07006408 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006409 Mutex::Autolock _l(mLock);
6410 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006411 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006412 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006413 }
Eric Laurentde070132010-07-13 04:45:46 -07006414 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6415 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006416 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006417 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006418 }
Eric Laurentde070132010-07-13 04:45:46 -07006419 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6420 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006421 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006422 return BAD_VALUE;
6423 }
6424
6425 Mutex::Autolock _dl(dstThread->mLock);
6426 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07006427 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07006428
Mathias Agopian65ab4712010-07-14 17:59:35 -07006429 return NO_ERROR;
6430}
6431
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006432// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07006433status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07006434 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07006435 AudioFlinger::PlaybackThread *dstThread,
6436 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07006437{
Steve Block3856b092011-10-20 11:56:00 +01006438 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006439 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07006440
Eric Laurent59255e42011-07-27 19:49:51 -07006441 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006442 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006443 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006444 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07006445 return INVALID_OPERATION;
6446 }
6447
Eric Laurent39e94f82010-07-28 01:32:47 -07006448 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07006449 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07006450 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07006451 // removed.
6452 srcThread->removeEffectChain_l(chain);
6453
6454 // transfer all effects one by one so that new effect chain is created on new thread with
6455 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006456 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07006457 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006458 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07006459 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6460 while (effect != 0) {
6461 srcThread->removeEffect_l(effect);
6462 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07006463 // removeEffect_l() has stopped the effect if it was active so it must be restarted
6464 if (effect->state() == EffectModule::ACTIVE ||
6465 effect->state() == EffectModule::STOPPING) {
6466 effect->start();
6467 }
Eric Laurent39e94f82010-07-28 01:32:47 -07006468 // if the move request is not received from audio policy manager, the effect must be
6469 // re-registered with the new strategy and output
6470 if (dstChain == 0) {
6471 dstChain = effect->chain().promote();
6472 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006473 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07006474 srcThread->addEffect_l(effect);
6475 return NO_INIT;
6476 }
6477 strategy = dstChain->strategy();
6478 }
6479 if (reRegister) {
6480 AudioSystem::unregisterEffect(effect->id());
6481 AudioSystem::registerEffect(&effect->desc(),
6482 dstOutput,
6483 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07006484 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07006485 effect->id());
6486 }
Eric Laurentde070132010-07-13 04:45:46 -07006487 effect = chain->getEffectFromId_l(0);
6488 }
6489
6490 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006491}
6492
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006493
Mathias Agopian65ab4712010-07-14 17:59:35 -07006494// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006495sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07006496 const sp<AudioFlinger::Client>& client,
6497 const sp<IEffectClient>& effectClient,
6498 int32_t priority,
6499 int sessionId,
6500 effect_descriptor_t *desc,
6501 int *enabled,
6502 status_t *status
6503 )
6504{
6505 sp<EffectModule> effect;
6506 sp<EffectHandle> handle;
6507 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006508 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07006509 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006510 bool effectCreated = false;
6511 bool effectRegistered = false;
6512
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006513 lStatus = initCheck();
6514 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006515 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006516 goto Exit;
6517 }
6518
6519 // Do not allow effects with session ID 0 on direct output or duplicating threads
6520 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07006521 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006522 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07006523 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006524 lStatus = BAD_VALUE;
6525 goto Exit;
6526 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006527 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08006528 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006529 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006530 desc->name, desc->flags, mType);
6531 lStatus = BAD_VALUE;
6532 goto Exit;
6533 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006534
Steve Block3856b092011-10-20 11:56:00 +01006535 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006536
6537 { // scope for mLock
6538 Mutex::Autolock _l(mLock);
6539
6540 // check for existing effect chain with the requested audio session
6541 chain = getEffectChain_l(sessionId);
6542 if (chain == 0) {
6543 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006544 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006545 chain = new EffectChain(this, sessionId);
6546 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07006547 chain->setStrategy(getStrategyForSession_l(sessionId));
6548 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006549 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07006550 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006551 }
6552
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08006553 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006554
6555 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006556 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006557 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07006558 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006559 if (lStatus != NO_ERROR) {
6560 goto Exit;
6561 }
6562 effectRegistered = true;
6563 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07006564 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006565 lStatus = effect->status();
6566 if (lStatus != NO_ERROR) {
6567 goto Exit;
6568 }
Eric Laurentcab11242010-07-15 12:50:15 -07006569 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006570 if (lStatus != NO_ERROR) {
6571 goto Exit;
6572 }
6573 effectCreated = true;
6574
6575 effect->setDevice(mDevice);
6576 effect->setMode(mAudioFlinger->getMode());
6577 }
6578 // create effect handle and connect it to effect module
6579 handle = new EffectHandle(effect, client, effectClient, priority);
6580 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08006581 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006582 *enabled = (int)effect->isEnabled();
6583 }
6584 }
6585
6586Exit:
6587 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07006588 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006589 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07006590 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006591 }
6592 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07006593 AudioSystem::unregisterEffect(effect->id());
6594 }
6595 if (chainCreated) {
6596 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006597 }
6598 handle.clear();
6599 }
6600
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006601 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006602 *status = lStatus;
6603 }
6604 return handle;
6605}
6606
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006607sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6608{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006609 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08006610 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006611}
6612
Eric Laurentde070132010-07-13 04:45:46 -07006613// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6614// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006615status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07006616{
6617 // check for existing effect chain with the requested audio session
6618 int sessionId = effect->sessionId();
6619 sp<EffectChain> chain = getEffectChain_l(sessionId);
6620 bool chainCreated = false;
6621
6622 if (chain == 0) {
6623 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006624 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006625 chain = new EffectChain(this, sessionId);
6626 addEffectChain_l(chain);
6627 chain->setStrategy(getStrategyForSession_l(sessionId));
6628 chainCreated = true;
6629 }
Steve Block3856b092011-10-20 11:56:00 +01006630 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006631
6632 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006633 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07006634 this, effect->desc().name, chain.get());
6635 return BAD_VALUE;
6636 }
6637
6638 status_t status = chain->addEffect_l(effect);
6639 if (status != NO_ERROR) {
6640 if (chainCreated) {
6641 removeEffectChain_l(chain);
6642 }
6643 return status;
6644 }
6645
6646 effect->setDevice(mDevice);
6647 effect->setMode(mAudioFlinger->getMode());
6648 return NO_ERROR;
6649}
6650
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006651void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07006652
Steve Block3856b092011-10-20 11:56:00 +01006653 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006654 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07006655 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6656 detachAuxEffect_l(effect->id());
6657 }
6658
6659 sp<EffectChain> chain = effect->chain().promote();
6660 if (chain != 0) {
6661 // remove effect chain if removing last effect
6662 if (chain->removeEffect_l(effect) == 0) {
6663 removeEffectChain_l(chain);
6664 }
6665 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00006666 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006667 }
6668}
6669
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006670void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006671 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006672{
6673 effectChains = mEffectChains;
6674 for (size_t i = 0; i < mEffectChains.size(); i++) {
6675 mEffectChains[i]->lock();
6676 }
6677}
6678
6679void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006680 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006681{
6682 for (size_t i = 0; i < effectChains.size(); i++) {
6683 effectChains[i]->unlock();
6684 }
6685}
6686
6687sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6688{
6689 Mutex::Autolock _l(mLock);
6690 return getEffectChain_l(sessionId);
6691}
6692
6693sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6694{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006695 size_t size = mEffectChains.size();
6696 for (size_t i = 0; i < size; i++) {
6697 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08006698 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006699 }
6700 }
Glenn Kasten090f0192012-01-30 13:00:02 -08006701 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006702}
6703
Glenn Kastenf78aee72012-01-04 11:00:47 -08006704void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006705{
6706 Mutex::Autolock _l(mLock);
6707 size_t size = mEffectChains.size();
6708 for (size_t i = 0; i < size; i++) {
6709 mEffectChains[i]->setMode_l(mode);
6710 }
6711}
6712
6713void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006714 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08006715 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07006716
Mathias Agopian65ab4712010-07-14 17:59:35 -07006717 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006718 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006719 // delete the effect module if removing last handle on it
6720 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006721 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006722 removeEffect_l(effect);
6723 AudioSystem::unregisterEffect(effect->id());
6724 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006725 }
6726}
6727
6728status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6729{
6730 int session = chain->sessionId();
6731 int16_t *buffer = mMixBuffer;
6732 bool ownsBuffer = false;
6733
Steve Block3856b092011-10-20 11:56:00 +01006734 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006735 if (session > 0) {
6736 // Only one effect chain can be present in direct output thread and it uses
6737 // the mix buffer as input
6738 if (mType != DIRECT) {
6739 size_t numSamples = mFrameCount * mChannelCount;
6740 buffer = new int16_t[numSamples];
6741 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01006742 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006743 ownsBuffer = true;
6744 }
6745
6746 // Attach all tracks with same session ID to this chain.
6747 for (size_t i = 0; i < mTracks.size(); ++i) {
6748 sp<Track> track = mTracks[i];
6749 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006750 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006751 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006752 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006753 }
6754 }
6755
6756 // indicate all active tracks in the chain
6757 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6758 sp<Track> track = mActiveTracks[i].promote();
6759 if (track == 0) continue;
6760 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006761 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07006762 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006763 }
6764 }
6765 }
6766
6767 chain->setInBuffer(buffer, ownsBuffer);
6768 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006769 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006770 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006771 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6772 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006773 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006774 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6775 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006776 // Effect chain for other sessions are inserted at beginning of effect
6777 // chains list to be processed before output mix effects. Relative order between other
6778 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006779 size_t size = mEffectChains.size();
6780 size_t i = 0;
6781 for (i = 0; i < size; i++) {
6782 if (mEffectChains[i]->sessionId() < session) break;
6783 }
6784 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006785 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006786
6787 return NO_ERROR;
6788}
6789
6790size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6791{
6792 int session = chain->sessionId();
6793
Steve Block3856b092011-10-20 11:56:00 +01006794 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006795
6796 for (size_t i = 0; i < mEffectChains.size(); i++) {
6797 if (chain == mEffectChains[i]) {
6798 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006799 // detach all active tracks from the chain
6800 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6801 sp<Track> track = mActiveTracks[i].promote();
6802 if (track == 0) continue;
6803 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006804 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006805 chain.get(), session);
6806 chain->decActiveTrackCnt();
6807 }
6808 }
6809
Mathias Agopian65ab4712010-07-14 17:59:35 -07006810 // detach all tracks with same session ID from this chain
6811 for (size_t i = 0; i < mTracks.size(); ++i) {
6812 sp<Track> track = mTracks[i];
6813 if (session == track->sessionId()) {
6814 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006815 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006816 }
6817 }
Eric Laurentde070132010-07-13 04:45:46 -07006818 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006819 }
6820 }
6821 return mEffectChains.size();
6822}
6823
Eric Laurentde070132010-07-13 04:45:46 -07006824status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6825 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006826{
6827 Mutex::Autolock _l(mLock);
6828 return attachAuxEffect_l(track, EffectId);
6829}
6830
Eric Laurentde070132010-07-13 04:45:46 -07006831status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6832 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006833{
6834 status_t status = NO_ERROR;
6835
6836 if (EffectId == 0) {
6837 track->setAuxBuffer(0, NULL);
6838 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006839 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6840 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006841 if (effect != 0) {
6842 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6843 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6844 } else {
6845 status = INVALID_OPERATION;
6846 }
6847 } else {
6848 status = BAD_VALUE;
6849 }
6850 }
6851 return status;
6852}
6853
6854void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6855{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006856 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006857 sp<Track> track = mTracks[i];
6858 if (track->auxEffectId() == effectId) {
6859 attachAuxEffect_l(track, 0);
6860 }
6861 }
6862}
6863
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006864status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6865{
6866 // only one chain per input thread
6867 if (mEffectChains.size() != 0) {
6868 return INVALID_OPERATION;
6869 }
Steve Block3856b092011-10-20 11:56:00 +01006870 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006871
6872 chain->setInBuffer(NULL);
6873 chain->setOutBuffer(NULL);
6874
Eric Laurent59255e42011-07-27 19:49:51 -07006875 checkSuspendOnAddEffectChain_l(chain);
6876
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006877 mEffectChains.add(chain);
6878
6879 return NO_ERROR;
6880}
6881
6882size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6883{
Steve Block3856b092011-10-20 11:56:00 +01006884 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006885 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006886 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6887 chain.get(), mEffectChains.size(), this);
6888 if (mEffectChains.size() == 1) {
6889 mEffectChains.removeAt(0);
6890 }
6891 return 0;
6892}
6893
Mathias Agopian65ab4712010-07-14 17:59:35 -07006894// ----------------------------------------------------------------------------
6895// EffectModule implementation
6896// ----------------------------------------------------------------------------
6897
6898#undef LOG_TAG
6899#define LOG_TAG "AudioFlinger::EffectModule"
6900
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006901AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006902 const wp<AudioFlinger::EffectChain>& chain,
6903 effect_descriptor_t *desc,
6904 int id,
6905 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006906 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006907 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006908{
Steve Block3856b092011-10-20 11:56:00 +01006909 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006910 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006911 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006912 return;
6913 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006914
6915 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6916
6917 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006918 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006919
6920 if (mStatus != NO_ERROR) {
6921 return;
6922 }
6923 lStatus = init();
6924 if (lStatus < 0) {
6925 mStatus = lStatus;
6926 goto Error;
6927 }
6928
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006929 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6930 mPinned = true;
6931 }
Steve Block3856b092011-10-20 11:56:00 +01006932 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006933 return;
6934Error:
6935 EffectRelease(mEffectInterface);
6936 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006937 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006938}
6939
6940AudioFlinger::EffectModule::~EffectModule()
6941{
Steve Block3856b092011-10-20 11:56:00 +01006942 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006943 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006944 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6945 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6946 sp<ThreadBase> thread = mThread.promote();
6947 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006948 audio_stream_t *stream = thread->stream();
6949 if (stream != NULL) {
6950 stream->remove_audio_effect(stream, mEffectInterface);
6951 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006952 }
6953 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006954 // release effect engine
6955 EffectRelease(mEffectInterface);
6956 }
6957}
6958
Glenn Kasten435dbe62012-01-30 10:15:48 -08006959status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006960{
6961 status_t status;
6962
6963 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006964 int priority = handle->priority();
6965 size_t size = mHandles.size();
6966 sp<EffectHandle> h;
6967 size_t i;
6968 for (i = 0; i < size; i++) {
6969 h = mHandles[i].promote();
6970 if (h == 0) continue;
6971 if (h->priority() <= priority) break;
6972 }
6973 // if inserted in first place, move effect control from previous owner to this handle
6974 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006975 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006976 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006977 enabled = h->enabled();
6978 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006979 }
Eric Laurent59255e42011-07-27 19:49:51 -07006980 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006981 status = NO_ERROR;
6982 } else {
6983 status = ALREADY_EXISTS;
6984 }
Steve Block3856b092011-10-20 11:56:00 +01006985 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006986 mHandles.insertAt(handle, i);
6987 return status;
6988}
6989
6990size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6991{
6992 Mutex::Autolock _l(mLock);
6993 size_t size = mHandles.size();
6994 size_t i;
6995 for (i = 0; i < size; i++) {
6996 if (mHandles[i] == handle) break;
6997 }
6998 if (i == size) {
6999 return size;
7000 }
Steve Block3856b092011-10-20 11:56:00 +01007001 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07007002
7003 bool enabled = false;
7004 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08007005 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01007006 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07007007 enabled = hdl->enabled();
7008 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007009 mHandles.removeAt(i);
7010 size = mHandles.size();
7011 // if removed from first place, move effect control from this handle to next in line
7012 if (i == 0 && size != 0) {
7013 sp<EffectHandle> h = mHandles[0].promote();
7014 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007015 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007016 }
7017 }
7018
Eric Laurentec437d82011-07-26 20:54:46 -07007019 // Prevent calls to process() and other functions on effect interface from now on.
7020 // The effect engine will be released by the destructor when the last strong reference on
7021 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007022 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07007023 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07007024 }
7025
Mathias Agopian65ab4712010-07-14 17:59:35 -07007026 return size;
7027}
7028
Eric Laurent59255e42011-07-27 19:49:51 -07007029sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
7030{
7031 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08007032 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007033}
7034
Glenn Kasten58123c32012-02-03 10:32:24 -08007035void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007036{
Glenn Kasten90bebef2012-01-27 15:24:38 -08007037 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007038 // keep a strong reference on this EffectModule to avoid calling the
7039 // destructor before we exit
7040 sp<EffectModule> keep(this);
7041 {
7042 sp<ThreadBase> thread = mThread.promote();
7043 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007044 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007045 }
7046 }
7047}
7048
7049void AudioFlinger::EffectModule::updateState() {
7050 Mutex::Autolock _l(mLock);
7051
7052 switch (mState) {
7053 case RESTART:
7054 reset_l();
7055 // FALL THROUGH
7056
7057 case STARTING:
7058 // clear auxiliary effect input buffer for next accumulation
7059 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7060 memset(mConfig.inputCfg.buffer.raw,
7061 0,
7062 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
7063 }
7064 start_l();
7065 mState = ACTIVE;
7066 break;
7067 case STOPPING:
7068 stop_l();
7069 mDisableWaitCnt = mMaxDisableWaitCnt;
7070 mState = STOPPED;
7071 break;
7072 case STOPPED:
7073 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
7074 // turn off sequence.
7075 if (--mDisableWaitCnt == 0) {
7076 reset_l();
7077 mState = IDLE;
7078 }
7079 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007080 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07007081 break;
7082 }
7083}
7084
7085void AudioFlinger::EffectModule::process()
7086{
7087 Mutex::Autolock _l(mLock);
7088
Eric Laurentec437d82011-07-26 20:54:46 -07007089 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007090 mConfig.inputCfg.buffer.raw == NULL ||
7091 mConfig.outputCfg.buffer.raw == NULL) {
7092 return;
7093 }
7094
Eric Laurent8f45bd72010-08-31 13:50:07 -07007095 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007096 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
7097 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08007098 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007099 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07007100 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007101 }
7102
7103 // do the actual processing in the effect engine
7104 int ret = (*mEffectInterface)->process(mEffectInterface,
7105 &mConfig.inputCfg.buffer,
7106 &mConfig.outputCfg.buffer);
7107
7108 // force transition to IDLE state when engine is ready
7109 if (mState == STOPPED && ret == -ENODATA) {
7110 mDisableWaitCnt = 1;
7111 }
7112
7113 // clear auxiliary effect input buffer for next accumulation
7114 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08007115 memset(mConfig.inputCfg.buffer.raw, 0,
7116 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007117 }
7118 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08007119 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7120 // If an insert effect is idle and input buffer is different from output buffer,
7121 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07007122 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07007123 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08007124 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
7125 int16_t *in = mConfig.inputCfg.buffer.s16;
7126 int16_t *out = mConfig.outputCfg.buffer.s16;
7127 for (size_t i = 0; i < frameCnt; i++) {
7128 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007129 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007130 }
7131 }
7132}
7133
7134void AudioFlinger::EffectModule::reset_l()
7135{
7136 if (mEffectInterface == NULL) {
7137 return;
7138 }
7139 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
7140}
7141
7142status_t AudioFlinger::EffectModule::configure()
7143{
7144 uint32_t channels;
7145 if (mEffectInterface == NULL) {
7146 return NO_INIT;
7147 }
7148
7149 sp<ThreadBase> thread = mThread.promote();
7150 if (thread == 0) {
7151 return DEAD_OBJECT;
7152 }
7153
7154 // TODO: handle configuration of effects replacing track process
7155 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007156 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007157 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07007158 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007159 }
7160
7161 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007162 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007163 } else {
7164 mConfig.inputCfg.channels = channels;
7165 }
7166 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07007167 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
7168 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007169 mConfig.inputCfg.samplingRate = thread->sampleRate();
7170 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
7171 mConfig.inputCfg.bufferProvider.cookie = NULL;
7172 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
7173 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
7174 mConfig.outputCfg.bufferProvider.cookie = NULL;
7175 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
7176 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
7177 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
7178 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07007179 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07007180 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07007181 // - in other sessions:
7182 // last effect in the chain accumulates in output buffer: input buffer != output buffer
7183 // other effect: overwrites output buffer: input buffer == output buffer
7184 // Auxiliary effect:
7185 // accumulates in output buffer: input buffer != output buffer
7186 // Therefore: accumulate <=> input buffer != output buffer
7187 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7188 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
7189 } else {
7190 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
7191 }
7192 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
7193 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
7194 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
7195 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
7196
Steve Block3856b092011-10-20 11:56:00 +01007197 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07007198 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
7199
Mathias Agopian65ab4712010-07-14 17:59:35 -07007200 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007201 uint32_t size = sizeof(int);
7202 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08007203 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07007204 sizeof(effect_config_t),
7205 &mConfig,
7206 &size,
7207 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007208 if (status == 0) {
7209 status = cmdStatus;
7210 }
7211
7212 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
7213 (1000 * mConfig.outputCfg.buffer.frameCount);
7214
7215 return status;
7216}
7217
7218status_t AudioFlinger::EffectModule::init()
7219{
7220 Mutex::Autolock _l(mLock);
7221 if (mEffectInterface == NULL) {
7222 return NO_INIT;
7223 }
7224 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007225 uint32_t size = sizeof(status_t);
7226 status_t status = (*mEffectInterface)->command(mEffectInterface,
7227 EFFECT_CMD_INIT,
7228 0,
7229 NULL,
7230 &size,
7231 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007232 if (status == 0) {
7233 status = cmdStatus;
7234 }
7235 return status;
7236}
7237
Eric Laurentec35a142011-10-05 17:42:25 -07007238status_t AudioFlinger::EffectModule::start()
7239{
7240 Mutex::Autolock _l(mLock);
7241 return start_l();
7242}
7243
Mathias Agopian65ab4712010-07-14 17:59:35 -07007244status_t AudioFlinger::EffectModule::start_l()
7245{
7246 if (mEffectInterface == NULL) {
7247 return NO_INIT;
7248 }
7249 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007250 uint32_t size = sizeof(status_t);
7251 status_t status = (*mEffectInterface)->command(mEffectInterface,
7252 EFFECT_CMD_ENABLE,
7253 0,
7254 NULL,
7255 &size,
7256 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007257 if (status == 0) {
7258 status = cmdStatus;
7259 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007260 if (status == 0 &&
7261 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7262 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7263 sp<ThreadBase> thread = mThread.promote();
7264 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007265 audio_stream_t *stream = thread->stream();
7266 if (stream != NULL) {
7267 stream->add_audio_effect(stream, mEffectInterface);
7268 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007269 }
7270 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007271 return status;
7272}
7273
Eric Laurentec437d82011-07-26 20:54:46 -07007274status_t AudioFlinger::EffectModule::stop()
7275{
7276 Mutex::Autolock _l(mLock);
7277 return stop_l();
7278}
7279
Mathias Agopian65ab4712010-07-14 17:59:35 -07007280status_t AudioFlinger::EffectModule::stop_l()
7281{
7282 if (mEffectInterface == NULL) {
7283 return NO_INIT;
7284 }
7285 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007286 uint32_t size = sizeof(status_t);
7287 status_t status = (*mEffectInterface)->command(mEffectInterface,
7288 EFFECT_CMD_DISABLE,
7289 0,
7290 NULL,
7291 &size,
7292 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007293 if (status == 0) {
7294 status = cmdStatus;
7295 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007296 if (status == 0 &&
7297 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7298 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7299 sp<ThreadBase> thread = mThread.promote();
7300 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007301 audio_stream_t *stream = thread->stream();
7302 if (stream != NULL) {
7303 stream->remove_audio_effect(stream, mEffectInterface);
7304 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007305 }
7306 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007307 return status;
7308}
7309
Eric Laurent25f43952010-07-28 05:40:18 -07007310status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
7311 uint32_t cmdSize,
7312 void *pCmdData,
7313 uint32_t *replySize,
7314 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007315{
7316 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007317// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007318
Eric Laurentec437d82011-07-26 20:54:46 -07007319 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007320 return NO_INIT;
7321 }
Eric Laurent25f43952010-07-28 05:40:18 -07007322 status_t status = (*mEffectInterface)->command(mEffectInterface,
7323 cmdCode,
7324 cmdSize,
7325 pCmdData,
7326 replySize,
7327 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007328 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07007329 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007330 for (size_t i = 1; i < mHandles.size(); i++) {
7331 sp<EffectHandle> h = mHandles[i].promote();
7332 if (h != 0) {
7333 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
7334 }
7335 }
7336 }
7337 return status;
7338}
7339
7340status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
7341{
Eric Laurentdb7c0792011-08-10 10:37:50 -07007342
Mathias Agopian65ab4712010-07-14 17:59:35 -07007343 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007344 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007345
7346 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007347 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
7348 if (enabled && status != NO_ERROR) {
7349 return status;
7350 }
7351
Mathias Agopian65ab4712010-07-14 17:59:35 -07007352 switch (mState) {
7353 // going from disabled to enabled
7354 case IDLE:
7355 mState = STARTING;
7356 break;
7357 case STOPPED:
7358 mState = RESTART;
7359 break;
7360 case STOPPING:
7361 mState = ACTIVE;
7362 break;
7363
7364 // going from enabled to disabled
7365 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007366 mState = STOPPED;
7367 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007368 case STARTING:
7369 mState = IDLE;
7370 break;
7371 case ACTIVE:
7372 mState = STOPPING;
7373 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007374 case DESTROYED:
7375 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007376 }
7377 for (size_t i = 1; i < mHandles.size(); i++) {
7378 sp<EffectHandle> h = mHandles[i].promote();
7379 if (h != 0) {
7380 h->setEnabled(enabled);
7381 }
7382 }
7383 }
7384 return NO_ERROR;
7385}
7386
Glenn Kastenc59c0042012-02-02 14:06:11 -08007387bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007388{
7389 switch (mState) {
7390 case RESTART:
7391 case STARTING:
7392 case ACTIVE:
7393 return true;
7394 case IDLE:
7395 case STOPPING:
7396 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07007397 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07007398 default:
7399 return false;
7400 }
7401}
7402
Glenn Kastenc59c0042012-02-02 14:06:11 -08007403bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07007404{
7405 switch (mState) {
7406 case RESTART:
7407 case ACTIVE:
7408 case STOPPING:
7409 case STOPPED:
7410 return true;
7411 case IDLE:
7412 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07007413 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007414 default:
7415 return false;
7416 }
7417}
7418
Mathias Agopian65ab4712010-07-14 17:59:35 -07007419status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7420{
7421 Mutex::Autolock _l(mLock);
7422 status_t status = NO_ERROR;
7423
7424 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7425 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07007426 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07007427 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7428 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007429 status_t cmdStatus;
7430 uint32_t volume[2];
7431 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07007432 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007433 volume[0] = *left;
7434 volume[1] = *right;
7435 if (controller) {
7436 pVolume = volume;
7437 }
Eric Laurent25f43952010-07-28 05:40:18 -07007438 status = (*mEffectInterface)->command(mEffectInterface,
7439 EFFECT_CMD_SET_VOLUME,
7440 size,
7441 volume,
7442 &size,
7443 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007444 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7445 *left = volume[0];
7446 *right = volume[1];
7447 }
7448 }
7449 return status;
7450}
7451
7452status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7453{
7454 Mutex::Autolock _l(mLock);
7455 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007456 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7457 // audio pre processing modules on RecordThread can receive both output and
7458 // input device indication in the same call
7459 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7460 if (dev) {
7461 status_t cmdStatus;
7462 uint32_t size = sizeof(status_t);
7463
7464 status = (*mEffectInterface)->command(mEffectInterface,
7465 EFFECT_CMD_SET_DEVICE,
7466 sizeof(uint32_t),
7467 &dev,
7468 &size,
7469 &cmdStatus);
7470 if (status == NO_ERROR) {
7471 status = cmdStatus;
7472 }
7473 }
7474 dev = device & AUDIO_DEVICE_IN_ALL;
7475 if (dev) {
7476 status_t cmdStatus;
7477 uint32_t size = sizeof(status_t);
7478
7479 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7480 EFFECT_CMD_SET_INPUT_DEVICE,
7481 sizeof(uint32_t),
7482 &dev,
7483 &size,
7484 &cmdStatus);
7485 if (status2 == NO_ERROR) {
7486 status2 = cmdStatus;
7487 }
7488 if (status == NO_ERROR) {
7489 status = status2;
7490 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007491 }
7492 }
7493 return status;
7494}
7495
Glenn Kastenf78aee72012-01-04 11:00:47 -08007496status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007497{
7498 Mutex::Autolock _l(mLock);
7499 status_t status = NO_ERROR;
7500 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007501 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007502 uint32_t size = sizeof(status_t);
7503 status = (*mEffectInterface)->command(mEffectInterface,
7504 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08007505 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07007506 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07007507 &size,
7508 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007509 if (status == NO_ERROR) {
7510 status = cmdStatus;
7511 }
7512 }
7513 return status;
7514}
7515
Eric Laurent59255e42011-07-27 19:49:51 -07007516void AudioFlinger::EffectModule::setSuspended(bool suspended)
7517{
7518 Mutex::Autolock _l(mLock);
7519 mSuspended = suspended;
7520}
Glenn Kastena3a85482012-01-04 11:01:11 -08007521
7522bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07007523{
7524 Mutex::Autolock _l(mLock);
7525 return mSuspended;
7526}
7527
Mathias Agopian65ab4712010-07-14 17:59:35 -07007528status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7529{
7530 const size_t SIZE = 256;
7531 char buffer[SIZE];
7532 String8 result;
7533
7534 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7535 result.append(buffer);
7536
7537 bool locked = tryLock(mLock);
7538 // failed to lock - AudioFlinger is probably deadlocked
7539 if (!locked) {
7540 result.append("\t\tCould not lock Fx mutex:\n");
7541 }
7542
7543 result.append("\t\tSession Status State Engine:\n");
7544 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7545 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7546 result.append(buffer);
7547
7548 result.append("\t\tDescriptor:\n");
7549 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7550 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7551 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7552 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7553 result.append(buffer);
7554 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7555 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7556 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7557 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7558 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07007559 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007560 mDescriptor.apiVersion,
7561 mDescriptor.flags);
7562 result.append(buffer);
7563 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7564 mDescriptor.name);
7565 result.append(buffer);
7566 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7567 mDescriptor.implementor);
7568 result.append(buffer);
7569
7570 result.append("\t\t- Input configuration:\n");
7571 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7572 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7573 (uint32_t)mConfig.inputCfg.buffer.raw,
7574 mConfig.inputCfg.buffer.frameCount,
7575 mConfig.inputCfg.samplingRate,
7576 mConfig.inputCfg.channels,
7577 mConfig.inputCfg.format);
7578 result.append(buffer);
7579
7580 result.append("\t\t- Output configuration:\n");
7581 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7582 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7583 (uint32_t)mConfig.outputCfg.buffer.raw,
7584 mConfig.outputCfg.buffer.frameCount,
7585 mConfig.outputCfg.samplingRate,
7586 mConfig.outputCfg.channels,
7587 mConfig.outputCfg.format);
7588 result.append(buffer);
7589
7590 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7591 result.append(buffer);
7592 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7593 for (size_t i = 0; i < mHandles.size(); ++i) {
7594 sp<EffectHandle> handle = mHandles[i].promote();
7595 if (handle != 0) {
7596 handle->dump(buffer, SIZE);
7597 result.append(buffer);
7598 }
7599 }
7600
7601 result.append("\n");
7602
7603 write(fd, result.string(), result.length());
7604
7605 if (locked) {
7606 mLock.unlock();
7607 }
7608
7609 return NO_ERROR;
7610}
7611
7612// ----------------------------------------------------------------------------
7613// EffectHandle implementation
7614// ----------------------------------------------------------------------------
7615
7616#undef LOG_TAG
7617#define LOG_TAG "AudioFlinger::EffectHandle"
7618
7619AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7620 const sp<AudioFlinger::Client>& client,
7621 const sp<IEffectClient>& effectClient,
7622 int32_t priority)
7623 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007624 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007625 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007626{
Steve Block3856b092011-10-20 11:56:00 +01007627 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007628
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007629 if (client == 0) {
7630 return;
7631 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007632 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7633 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7634 if (mCblkMemory != 0) {
7635 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7636
Glenn Kastena0d68332012-01-27 16:47:15 -08007637 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007638 new(mCblk) effect_param_cblk_t();
7639 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007640 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007641 } else {
Steve Block29357bc2012-01-06 19:20:56 +00007642 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007643 return;
7644 }
7645}
7646
7647AudioFlinger::EffectHandle::~EffectHandle()
7648{
Steve Block3856b092011-10-20 11:56:00 +01007649 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007650 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01007651 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007652}
7653
7654status_t AudioFlinger::EffectHandle::enable()
7655{
Steve Block3856b092011-10-20 11:56:00 +01007656 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007657 if (!mHasControl) return INVALID_OPERATION;
7658 if (mEffect == 0) return DEAD_OBJECT;
7659
Eric Laurentdb7c0792011-08-10 10:37:50 -07007660 if (mEnabled) {
7661 return NO_ERROR;
7662 }
7663
Eric Laurent59255e42011-07-27 19:49:51 -07007664 mEnabled = true;
7665
7666 sp<ThreadBase> thread = mEffect->thread().promote();
7667 if (thread != 0) {
7668 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7669 }
7670
7671 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7672 if (mEffect->suspended()) {
7673 return NO_ERROR;
7674 }
7675
Eric Laurentdb7c0792011-08-10 10:37:50 -07007676 status_t status = mEffect->setEnabled(true);
7677 if (status != NO_ERROR) {
7678 if (thread != 0) {
7679 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7680 }
7681 mEnabled = false;
7682 }
7683 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007684}
7685
7686status_t AudioFlinger::EffectHandle::disable()
7687{
Steve Block3856b092011-10-20 11:56:00 +01007688 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007689 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07007690 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007691
Eric Laurentdb7c0792011-08-10 10:37:50 -07007692 if (!mEnabled) {
7693 return NO_ERROR;
7694 }
Eric Laurent59255e42011-07-27 19:49:51 -07007695 mEnabled = false;
7696
7697 if (mEffect->suspended()) {
7698 return NO_ERROR;
7699 }
7700
7701 status_t status = mEffect->setEnabled(false);
7702
7703 sp<ThreadBase> thread = mEffect->thread().promote();
7704 if (thread != 0) {
7705 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7706 }
7707
7708 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007709}
7710
7711void AudioFlinger::EffectHandle::disconnect()
7712{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007713 disconnect(true);
7714}
7715
Glenn Kasten58123c32012-02-03 10:32:24 -08007716void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007717{
Glenn Kasten58123c32012-02-03 10:32:24 -08007718 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007719 if (mEffect == 0) {
7720 return;
7721 }
Glenn Kasten58123c32012-02-03 10:32:24 -08007722 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07007723
Eric Laurenta85a74a2011-10-19 11:44:54 -07007724 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007725 sp<ThreadBase> thread = mEffect->thread().promote();
7726 if (thread != 0) {
7727 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7728 }
Eric Laurent59255e42011-07-27 19:49:51 -07007729 }
7730
Mathias Agopian65ab4712010-07-14 17:59:35 -07007731 // release sp on module => module destructor can be called now
7732 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007733 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08007734 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08007735 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007736 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7737 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08007738 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007739 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07007740 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7741 mClient.clear();
7742 }
7743}
7744
Eric Laurent25f43952010-07-28 05:40:18 -07007745status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7746 uint32_t cmdSize,
7747 void *pCmdData,
7748 uint32_t *replySize,
7749 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007750{
Steve Block3856b092011-10-20 11:56:00 +01007751// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07007752// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007753
7754 // only get parameter command is permitted for applications not controlling the effect
7755 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7756 return INVALID_OPERATION;
7757 }
7758 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007759 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007760
7761 // handle commands that are not forwarded transparently to effect engine
7762 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7763 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7764 // no risk to block the whole media server process or mixer threads is we are stuck here
7765 Mutex::Autolock _l(mCblk->lock);
7766 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7767 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7768 mCblk->serverIndex = 0;
7769 mCblk->clientIndex = 0;
7770 return BAD_VALUE;
7771 }
7772 status_t status = NO_ERROR;
7773 while (mCblk->serverIndex < mCblk->clientIndex) {
7774 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007775 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007776 int *p = (int *)(mBuffer + mCblk->serverIndex);
7777 int size = *p++;
7778 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007779 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007780 break;
7781 }
7782 effect_param_t *param = (effect_param_t *)p;
7783 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007784 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007785 mCblk->serverIndex += size;
7786 continue;
7787 }
Eric Laurent25f43952010-07-28 05:40:18 -07007788 uint32_t psize = sizeof(effect_param_t) +
7789 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7790 param->vsize;
7791 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7792 psize,
7793 p,
7794 &rsize,
7795 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007796 // stop at first error encountered
7797 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007798 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007799 *(int *)pReplyData = reply;
7800 break;
7801 } else if (reply != NO_ERROR) {
7802 *(int *)pReplyData = reply;
7803 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007804 }
7805 mCblk->serverIndex += size;
7806 }
7807 mCblk->serverIndex = 0;
7808 mCblk->clientIndex = 0;
7809 return status;
7810 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007811 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007812 return enable();
7813 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007814 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007815 return disable();
7816 }
7817
7818 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7819}
7820
Eric Laurent59255e42011-07-27 19:49:51 -07007821void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007822{
Steve Block3856b092011-10-20 11:56:00 +01007823 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007824
7825 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007826 mEnabled = enabled;
7827
Mathias Agopian65ab4712010-07-14 17:59:35 -07007828 if (signal && mEffectClient != 0) {
7829 mEffectClient->controlStatusChanged(hasControl);
7830 }
7831}
7832
Eric Laurent25f43952010-07-28 05:40:18 -07007833void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7834 uint32_t cmdSize,
7835 void *pCmdData,
7836 uint32_t replySize,
7837 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007838{
7839 if (mEffectClient != 0) {
7840 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7841 }
7842}
7843
7844
7845
7846void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7847{
7848 if (mEffectClient != 0) {
7849 mEffectClient->enableStatusChanged(enabled);
7850 }
7851}
7852
7853status_t AudioFlinger::EffectHandle::onTransact(
7854 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7855{
7856 return BnEffect::onTransact(code, data, reply, flags);
7857}
7858
7859
7860void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7861{
Glenn Kastena0d68332012-01-27 16:47:15 -08007862 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007863
7864 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08007865 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007866 mPriority,
7867 mHasControl,
7868 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007869 mCblk ? mCblk->clientIndex : 0,
7870 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007871 );
7872
7873 if (locked) {
7874 mCblk->lock.unlock();
7875 }
7876}
7877
7878#undef LOG_TAG
7879#define LOG_TAG "AudioFlinger::EffectChain"
7880
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007881AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007882 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007883 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007884 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7885 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007886{
Dima Zavinfce7a472011-04-19 22:30:36 -07007887 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007888 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007889 return;
7890 }
7891 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7892 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007893}
7894
7895AudioFlinger::EffectChain::~EffectChain()
7896{
7897 if (mOwnInBuffer) {
7898 delete mInBuffer;
7899 }
7900
7901}
7902
Eric Laurent59255e42011-07-27 19:49:51 -07007903// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007904sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007905{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007906 size_t size = mEffects.size();
7907
7908 for (size_t i = 0; i < size; i++) {
7909 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007910 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007911 }
7912 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007913 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007914}
7915
Eric Laurent59255e42011-07-27 19:49:51 -07007916// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007917sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007918{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007919 size_t size = mEffects.size();
7920
7921 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007922 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7923 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007924 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007925 }
7926 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007927 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007928}
7929
Eric Laurent59255e42011-07-27 19:49:51 -07007930// getEffectFromType_l() must be called with ThreadBase::mLock held
7931sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7932 const effect_uuid_t *type)
7933{
Eric Laurent59255e42011-07-27 19:49:51 -07007934 size_t size = mEffects.size();
7935
7936 for (size_t i = 0; i < size; i++) {
7937 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007938 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007939 }
7940 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007941 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007942}
7943
Mathias Agopian65ab4712010-07-14 17:59:35 -07007944// Must be called with EffectChain::mLock locked
7945void AudioFlinger::EffectChain::process_l()
7946{
Eric Laurentdac69112010-09-28 14:09:57 -07007947 sp<ThreadBase> thread = mThread.promote();
7948 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007949 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007950 return;
7951 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007952 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7953 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007954 // always process effects unless no more tracks are on the session and the effect tail
7955 // has been rendered
7956 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007957 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007958 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007959
Eric Laurent544fe9b2011-11-11 15:42:52 -08007960 if (!tracksOnSession && mTailBufferCount == 0) {
7961 doProcess = false;
7962 }
7963
7964 if (activeTrackCnt() == 0) {
7965 // if no track is active and the effect tail has not been rendered,
7966 // the input buffer must be cleared here as the mixer process will not do it
7967 if (tracksOnSession || mTailBufferCount > 0) {
7968 size_t numSamples = thread->frameCount() * thread->channelCount();
7969 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7970 if (mTailBufferCount > 0) {
7971 mTailBufferCount--;
7972 }
7973 }
7974 }
Eric Laurentdac69112010-09-28 14:09:57 -07007975 }
7976
Mathias Agopian65ab4712010-07-14 17:59:35 -07007977 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007978 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007979 for (size_t i = 0; i < size; i++) {
7980 mEffects[i]->process();
7981 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007982 }
7983 for (size_t i = 0; i < size; i++) {
7984 mEffects[i]->updateState();
7985 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007986}
7987
Eric Laurentcab11242010-07-15 12:50:15 -07007988// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007989status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007990{
7991 effect_descriptor_t desc = effect->desc();
7992 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7993
7994 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007995 effect->setChain(this);
7996 sp<ThreadBase> thread = mThread.promote();
7997 if (thread == 0) {
7998 return NO_INIT;
7999 }
8000 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008001
8002 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8003 // Auxiliary effects are inserted at the beginning of mEffects vector as
8004 // they are processed first and accumulated in chain input buffer
8005 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07008006
Mathias Agopian65ab4712010-07-14 17:59:35 -07008007 // the input buffer for auxiliary effect contains mono samples in
8008 // 32 bit format. This is to avoid saturation in AudoMixer
8009 // accumulation stage. Saturation is done in EffectModule::process() before
8010 // calling the process in effect engine
8011 size_t numSamples = thread->frameCount();
8012 int32_t *buffer = new int32_t[numSamples];
8013 memset(buffer, 0, numSamples * sizeof(int32_t));
8014 effect->setInBuffer((int16_t *)buffer);
8015 // auxiliary effects output samples to chain input buffer for further processing
8016 // by insert effects
8017 effect->setOutBuffer(mInBuffer);
8018 } else {
8019 // Insert effects are inserted at the end of mEffects vector as they are processed
8020 // after track and auxiliary effects.
8021 // Insert effect order as a function of indicated preference:
8022 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
8023 // another effect is present
8024 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
8025 // last effect claiming first position
8026 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
8027 // first effect claiming last position
8028 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
8029 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
8030 // already present
8031
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008032 size_t size = mEffects.size();
8033 size_t idx_insert = size;
8034 ssize_t idx_insert_first = -1;
8035 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008036
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008037 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008038 effect_descriptor_t d = mEffects[i]->desc();
8039 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
8040 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
8041 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
8042 // check invalid effect chaining combinations
8043 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
8044 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008045 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008046 return INVALID_OPERATION;
8047 }
8048 // remember position of first insert effect and by default
8049 // select this as insert position for new effect
8050 if (idx_insert == size) {
8051 idx_insert = i;
8052 }
8053 // remember position of last insert effect claiming
8054 // first position
8055 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
8056 idx_insert_first = i;
8057 }
8058 // remember position of first insert effect claiming
8059 // last position
8060 if (iPref == EFFECT_FLAG_INSERT_LAST &&
8061 idx_insert_last == -1) {
8062 idx_insert_last = i;
8063 }
8064 }
8065 }
8066
8067 // modify idx_insert from first position if needed
8068 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
8069 if (idx_insert_last != -1) {
8070 idx_insert = idx_insert_last;
8071 } else {
8072 idx_insert = size;
8073 }
8074 } else {
8075 if (idx_insert_first != -1) {
8076 idx_insert = idx_insert_first + 1;
8077 }
8078 }
8079
8080 // always read samples from chain input buffer
8081 effect->setInBuffer(mInBuffer);
8082
8083 // if last effect in the chain, output samples to chain
8084 // output buffer, otherwise to chain input buffer
8085 if (idx_insert == size) {
8086 if (idx_insert != 0) {
8087 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
8088 mEffects[idx_insert-1]->configure();
8089 }
8090 effect->setOutBuffer(mOutBuffer);
8091 } else {
8092 effect->setOutBuffer(mInBuffer);
8093 }
8094 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008095
Steve Block3856b092011-10-20 11:56:00 +01008096 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008097 }
8098 effect->configure();
8099 return NO_ERROR;
8100}
8101
Eric Laurentcab11242010-07-15 12:50:15 -07008102// removeEffect_l() must be called with PlaybackThread::mLock held
8103size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008104{
8105 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008106 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008107 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
8108
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008109 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008110 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07008111 // calling stop here will remove pre-processing effect from the audio HAL.
8112 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
8113 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07008114 if (mEffects[i]->state() == EffectModule::ACTIVE ||
8115 mEffects[i]->state() == EffectModule::STOPPING) {
8116 mEffects[i]->stop();
8117 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008118 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
8119 delete[] effect->inBuffer();
8120 } else {
8121 if (i == size - 1 && i != 0) {
8122 mEffects[i - 1]->setOutBuffer(mOutBuffer);
8123 mEffects[i - 1]->configure();
8124 }
8125 }
8126 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01008127 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008128 break;
8129 }
8130 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008131
8132 return mEffects.size();
8133}
8134
Eric Laurentcab11242010-07-15 12:50:15 -07008135// setDevice_l() must be called with PlaybackThread::mLock held
8136void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008137{
8138 size_t size = mEffects.size();
8139 for (size_t i = 0; i < size; i++) {
8140 mEffects[i]->setDevice(device);
8141 }
8142}
8143
Eric Laurentcab11242010-07-15 12:50:15 -07008144// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08008145void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008146{
8147 size_t size = mEffects.size();
8148 for (size_t i = 0; i < size; i++) {
8149 mEffects[i]->setMode(mode);
8150 }
8151}
8152
Eric Laurentcab11242010-07-15 12:50:15 -07008153// setVolume_l() must be called with PlaybackThread::mLock held
8154bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008155{
8156 uint32_t newLeft = *left;
8157 uint32_t newRight = *right;
8158 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07008159 int ctrlIdx = -1;
8160 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008161
Eric Laurentcab11242010-07-15 12:50:15 -07008162 // first update volume controller
8163 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07008164 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07008165 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
8166 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07008167 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07008168 break;
8169 }
8170 }
8171
8172 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07008173 if (hasControl) {
8174 *left = mNewLeftVolume;
8175 *right = mNewRightVolume;
8176 }
8177 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07008178 }
8179
8180 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07008181 mLeftVolume = newLeft;
8182 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008183
8184 // second get volume update from volume controller
8185 if (ctrlIdx >= 0) {
8186 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07008187 mNewLeftVolume = newLeft;
8188 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008189 }
8190 // then indicate volume to all other effects in chain.
8191 // Pass altered volume to effects before volume controller
8192 // and requested volume to effects after controller
8193 uint32_t lVol = newLeft;
8194 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008195
Mathias Agopian65ab4712010-07-14 17:59:35 -07008196 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07008197 if ((int)i == ctrlIdx) continue;
8198 // this also works for ctrlIdx == -1 when there is no volume controller
8199 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008200 lVol = *left;
8201 rVol = *right;
8202 }
8203 mEffects[i]->setVolume(&lVol, &rVol, false);
8204 }
8205 *left = newLeft;
8206 *right = newRight;
8207
8208 return hasControl;
8209}
8210
Mathias Agopian65ab4712010-07-14 17:59:35 -07008211status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
8212{
8213 const size_t SIZE = 256;
8214 char buffer[SIZE];
8215 String8 result;
8216
8217 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
8218 result.append(buffer);
8219
8220 bool locked = tryLock(mLock);
8221 // failed to lock - AudioFlinger is probably deadlocked
8222 if (!locked) {
8223 result.append("\tCould not lock mutex:\n");
8224 }
8225
Eric Laurentcab11242010-07-15 12:50:15 -07008226 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
8227 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008228 mEffects.size(),
8229 (uint32_t)mInBuffer,
8230 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008231 mActiveTrackCnt);
8232 result.append(buffer);
8233 write(fd, result.string(), result.size());
8234
8235 for (size_t i = 0; i < mEffects.size(); ++i) {
8236 sp<EffectModule> effect = mEffects[i];
8237 if (effect != 0) {
8238 effect->dump(fd, args);
8239 }
8240 }
8241
8242 if (locked) {
8243 mLock.unlock();
8244 }
8245
8246 return NO_ERROR;
8247}
8248
Eric Laurent59255e42011-07-27 19:49:51 -07008249// must be called with ThreadBase::mLock held
8250void AudioFlinger::EffectChain::setEffectSuspended_l(
8251 const effect_uuid_t *type, bool suspend)
8252{
8253 sp<SuspendedEffectDesc> desc;
8254 // use effect type UUID timelow as key as there is no real risk of identical
8255 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008256 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008257 if (suspend) {
8258 if (index >= 0) {
8259 desc = mSuspendedEffects.valueAt(index);
8260 } else {
8261 desc = new SuspendedEffectDesc();
8262 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
8263 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01008264 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008265 }
8266 if (desc->mRefCount++ == 0) {
8267 sp<EffectModule> effect = getEffectIfEnabled(type);
8268 if (effect != 0) {
8269 desc->mEffect = effect;
8270 effect->setSuspended(true);
8271 effect->setEnabled(false);
8272 }
8273 }
8274 } else {
8275 if (index < 0) {
8276 return;
8277 }
8278 desc = mSuspendedEffects.valueAt(index);
8279 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008280 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008281 desc->mRefCount = 1;
8282 }
8283 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01008284 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008285 if (desc->mEffect != 0) {
8286 sp<EffectModule> effect = desc->mEffect.promote();
8287 if (effect != 0) {
8288 effect->setSuspended(false);
8289 sp<EffectHandle> handle = effect->controlHandle();
8290 if (handle != 0) {
8291 effect->setEnabled(handle->enabled());
8292 }
8293 }
8294 desc->mEffect.clear();
8295 }
8296 mSuspendedEffects.removeItemsAt(index);
8297 }
8298 }
8299}
8300
8301// must be called with ThreadBase::mLock held
8302void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
8303{
8304 sp<SuspendedEffectDesc> desc;
8305
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008306 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07008307 if (suspend) {
8308 if (index >= 0) {
8309 desc = mSuspendedEffects.valueAt(index);
8310 } else {
8311 desc = new SuspendedEffectDesc();
8312 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01008313 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07008314 }
8315 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08008316 Vector< sp<EffectModule> > effects;
8317 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07008318 for (size_t i = 0; i < effects.size(); i++) {
8319 setEffectSuspended_l(&effects[i]->desc().type, true);
8320 }
8321 }
8322 } else {
8323 if (index < 0) {
8324 return;
8325 }
8326 desc = mSuspendedEffects.valueAt(index);
8327 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008328 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008329 desc->mRefCount = 1;
8330 }
8331 if (--desc->mRefCount == 0) {
8332 Vector<const effect_uuid_t *> types;
8333 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
8334 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
8335 continue;
8336 }
8337 types.add(&mSuspendedEffects.valueAt(i)->mType);
8338 }
8339 for (size_t i = 0; i < types.size(); i++) {
8340 setEffectSuspended_l(types[i], false);
8341 }
Steve Block3856b092011-10-20 11:56:00 +01008342 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008343 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
8344 }
8345 }
8346}
8347
Eric Laurent6bffdb82011-09-23 08:40:41 -07008348
8349// The volume effect is used for automated tests only
8350#ifndef OPENSL_ES_H_
8351static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
8352 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
8353const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
8354#endif //OPENSL_ES_H_
8355
Eric Laurentdb7c0792011-08-10 10:37:50 -07008356bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
8357{
8358 // auxiliary effects and visualizer are never suspended on output mix
8359 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8360 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07008361 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8362 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008363 return false;
8364 }
8365 return true;
8366}
8367
Glenn Kastend0539712012-01-30 12:56:03 -08008368void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07008369{
Glenn Kastend0539712012-01-30 12:56:03 -08008370 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07008371 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08008372 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8373 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07008374 }
Eric Laurent59255e42011-07-27 19:49:51 -07008375 }
Eric Laurent59255e42011-07-27 19:49:51 -07008376}
8377
8378sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8379 const effect_uuid_t *type)
8380{
Glenn Kasten090f0192012-01-30 13:00:02 -08008381 sp<EffectModule> effect = getEffectFromType_l(type);
8382 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008383}
8384
8385void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8386 bool enabled)
8387{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008388 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008389 if (enabled) {
8390 if (index < 0) {
8391 // if the effect is not suspend check if all effects are suspended
8392 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8393 if (index < 0) {
8394 return;
8395 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07008396 if (!isEffectEligibleForSuspend(effect->desc())) {
8397 return;
8398 }
Eric Laurent59255e42011-07-27 19:49:51 -07008399 setEffectSuspended_l(&effect->desc().type, enabled);
8400 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07008401 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008402 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07008403 return;
8404 }
Eric Laurent59255e42011-07-27 19:49:51 -07008405 }
Steve Block3856b092011-10-20 11:56:00 +01008406 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008407 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008408 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8409 // if effect is requested to suspended but was not yet enabled, supend it now.
8410 if (desc->mEffect == 0) {
8411 desc->mEffect = effect;
8412 effect->setEnabled(false);
8413 effect->setSuspended(true);
8414 }
8415 } else {
8416 if (index < 0) {
8417 return;
8418 }
Steve Block3856b092011-10-20 11:56:00 +01008419 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008420 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008421 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8422 desc->mEffect.clear();
8423 effect->setSuspended(false);
8424 }
8425}
8426
Mathias Agopian65ab4712010-07-14 17:59:35 -07008427#undef LOG_TAG
8428#define LOG_TAG "AudioFlinger"
8429
8430// ----------------------------------------------------------------------------
8431
8432status_t AudioFlinger::onTransact(
8433 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8434{
8435 return BnAudioFlinger::onTransact(code, data, reply, flags);
8436}
8437
Mathias Agopian65ab4712010-07-14 17:59:35 -07008438}; // namespace android