blob: 9e6a6dfec0005f4a149f7a538fca26228a594d63 [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
2642int AudioFlinger::MixerThread::getTrackName_l()
2643{
2644 return mAudioMixer->getTrackName();
2645}
2646
2647// deleteTrackName_l() must be called with ThreadBase::mLock held
2648void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2649{
Steve Block3856b092011-10-20 11:56:00 +01002650 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002651 mAudioMixer->deleteTrackName(name);
2652}
2653
2654// checkForNewParameters_l() must be called with ThreadBase::mLock held
2655bool AudioFlinger::MixerThread::checkForNewParameters_l()
2656{
2657 bool reconfig = false;
2658
2659 while (!mNewParameters.isEmpty()) {
2660 status_t status = NO_ERROR;
2661 String8 keyValuePair = mNewParameters[0];
2662 AudioParameter param = AudioParameter(keyValuePair);
2663 int value;
2664
2665 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2666 reconfig = true;
2667 }
2668 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002669 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002670 status = BAD_VALUE;
2671 } else {
2672 reconfig = true;
2673 }
2674 }
2675 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002676 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002677 status = BAD_VALUE;
2678 } else {
2679 reconfig = true;
2680 }
2681 }
2682 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2683 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002684 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002685 // if frame count is changed after track creation
2686 if (!mTracks.isEmpty()) {
2687 status = INVALID_OPERATION;
2688 } else {
2689 reconfig = true;
2690 }
2691 }
2692 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07002693#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08002694 // when changing the audio output device, call addBatteryData to notify
2695 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002696 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002697 uint32_t params = 0;
2698 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002699 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002700 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2701 }
2702
2703 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002704 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002705 // check if any other device (except speaker) is on
2706 if (value & deviceWithoutSpeaker ) {
2707 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2708 }
2709
2710 if (params != 0) {
2711 addBatteryData(params);
2712 }
2713 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07002714#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08002715
Mathias Agopian65ab4712010-07-14 17:59:35 -07002716 // forward device change to effects that have requested to be
2717 // aware of attached audio device.
2718 mDevice = (uint32_t)value;
2719 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002720 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002721 }
2722 }
2723
2724 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002725 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002726 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002727 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002728 mOutput->stream->common.standby(&mOutput->stream->common);
2729 mStandby = true;
2730 mBytesWritten = 0;
2731 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 }
2734 if (status == NO_ERROR && reconfig) {
2735 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002736 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2737 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002738 readOutputParameters();
2739 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2740 for (size_t i = 0; i < mTracks.size() ; i++) {
2741 int name = getTrackName_l();
2742 if (name < 0) break;
2743 mTracks[i]->mName = name;
2744 // limit track sample rate to 2 x new output sample rate
2745 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2746 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2747 }
2748 }
2749 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2750 }
2751 }
2752
2753 mNewParameters.removeAt(0);
2754
2755 mParamStatus = status;
2756 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002757 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2758 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002759 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002760 }
2761 return reconfig;
2762}
2763
2764status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2765{
2766 const size_t SIZE = 256;
2767 char buffer[SIZE];
2768 String8 result;
2769
2770 PlaybackThread::dumpInternals(fd, args);
2771
2772 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2773 result.append(buffer);
2774 write(fd, result.string(), result.size());
2775 return NO_ERROR;
2776}
2777
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002778uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002779{
Eric Laurent60e18242010-07-29 06:50:24 -07002780 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002781}
2782
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002783uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002784{
2785 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2786}
2787
Glenn Kasten66fcab92012-02-24 14:59:21 -08002788void AudioFlinger::MixerThread::cacheParameters_l()
2789{
2790 PlaybackThread::cacheParameters_l();
2791
2792 // FIXME: Relaxed timing because of a certain device that can't meet latency
2793 // Should be reduced to 2x after the vendor fixes the driver issue
2794 // increase threshold again due to low power audio mode. The way this warning
2795 // threshold is calculated and its usefulness should be reconsidered anyway.
2796 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
2797}
2798
Mathias Agopian65ab4712010-07-14 17:59:35 -07002799// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002800AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2801 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002802 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002803 // mLeftVolFloat, mRightVolFloat
2804 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002805{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002806}
2807
2808AudioFlinger::DirectOutputThread::~DirectOutputThread()
2809{
2810}
2811
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002812AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
2813 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08002814)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002815{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002816 sp<Track> trackToRemove;
2817
Glenn Kastenfec279f2012-03-08 07:47:15 -08002818 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002819
Glenn Kasten952eeb22012-03-06 11:30:57 -08002820 // find out which tracks need to be processed
2821 if (mActiveTracks.size() != 0) {
2822 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08002823 // The track died recently
2824 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002825
Glenn Kasten952eeb22012-03-06 11:30:57 -08002826 Track* const track = t.get();
2827 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002828
Glenn Kasten952eeb22012-03-06 11:30:57 -08002829 // The first time a track is added we wait
2830 // for all its buffers to be filled before processing it
2831 if (cblk->framesReady() && track->isReady() &&
2832 !track->isPaused() && !track->isTerminated())
2833 {
2834 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002835
Glenn Kasten952eeb22012-03-06 11:30:57 -08002836 if (track->mFillingUpStatus == Track::FS_FILLED) {
2837 track->mFillingUpStatus = Track::FS_ACTIVE;
2838 mLeftVolFloat = mRightVolFloat = 0;
2839 mLeftVolShort = mRightVolShort = 0;
2840 if (track->mState == TrackBase::RESUMING) {
2841 track->mState = TrackBase::ACTIVE;
2842 rampVolume = true;
2843 }
2844 } else if (cblk->server != 0) {
2845 // If the track is stopped before the first frame was mixed,
2846 // do not apply ramp
2847 rampVolume = true;
2848 }
2849 // compute volume for this track
2850 float left, right;
2851 if (track->isMuted() || mMasterMute || track->isPausing() ||
2852 mStreamTypes[track->streamType()].mute) {
2853 left = right = 0;
2854 if (track->isPausing()) {
2855 track->setPaused();
2856 }
2857 } else {
2858 float typeVolume = mStreamTypes[track->streamType()].volume;
2859 float v = mMasterVolume * typeVolume;
2860 uint32_t vlr = cblk->getVolumeLR();
2861 float v_clamped = v * (vlr & 0xFFFF);
2862 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2863 left = v_clamped/MAX_GAIN;
2864 v_clamped = v * (vlr >> 16);
2865 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2866 right = v_clamped/MAX_GAIN;
2867 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002868
Glenn Kasten952eeb22012-03-06 11:30:57 -08002869 if (left != mLeftVolFloat || right != mRightVolFloat) {
2870 mLeftVolFloat = left;
2871 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002872
Glenn Kasten952eeb22012-03-06 11:30:57 -08002873 // If audio HAL implements volume control,
2874 // force software volume to nominal value
2875 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
2876 left = 1.0f;
2877 right = 1.0f;
2878 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002879
Glenn Kasten952eeb22012-03-06 11:30:57 -08002880 // Convert volumes from float to 8.24
2881 uint32_t vl = (uint32_t)(left * (1 << 24));
2882 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002883
Glenn Kasten952eeb22012-03-06 11:30:57 -08002884 // Delegate volume control to effect in track effect chain if needed
2885 // only one effect chain can be present on DirectOutputThread, so if
2886 // there is one, the track is connected to it
2887 if (!mEffectChains.isEmpty()) {
2888 // Do not ramp volume if volume is controlled by effect
2889 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002890 rampVolume = false;
2891 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002892 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002893
Glenn Kasten952eeb22012-03-06 11:30:57 -08002894 // Convert volumes from 8.24 to 4.12 format
2895 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2896 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2897 leftVol = (uint16_t)v_clamped;
2898 v_clamped = (vr + (1 << 11)) >> 12;
2899 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2900 rightVol = (uint16_t)v_clamped;
2901 } else {
2902 leftVol = mLeftVolShort;
2903 rightVol = mRightVolShort;
2904 rampVolume = false;
2905 }
2906
2907 // reset retry count
2908 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002909 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002910 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002911 } else {
2912 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2913 if (track->isStopped()) {
2914 track->reset();
2915 }
2916 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2917 // We have consumed all the buffers of this track.
2918 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07002919 // TODO: implement behavior for compressed audio
2920 size_t audioHALFrames =
2921 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2922 size_t framesWritten =
2923 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2924 if (track->presentationComplete(framesWritten, audioHALFrames)) {
2925 trackToRemove = track;
2926 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002927 } else {
2928 // No buffers for this track. Give it a few chances to
2929 // fill a buffer, then remove it from active list.
2930 if (--(track->mRetryCount) <= 0) {
2931 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2932 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002933 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002934 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002935 }
2936 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002937 }
2938 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002939
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002940 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08002941 // remove all the tracks that need to be...
2942 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002943 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002944 mActiveTracks.remove(trackToRemove);
2945 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002946 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08002947 trackToRemove->sessionId());
2948 mEffectChains[0]->decActiveTrackCnt();
2949 }
2950 if (trackToRemove->isTerminated()) {
2951 removeTrack_l(trackToRemove);
2952 }
2953 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002954
Glenn Kastenfec279f2012-03-08 07:47:15 -08002955 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002956}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002957
Glenn Kasten000f0e32012-03-01 17:10:56 -08002958void AudioFlinger::DirectOutputThread::threadLoop_mix()
2959{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002960 AudioBufferProvider::Buffer buffer;
2961 size_t frameCount = mFrameCount;
2962 int8_t *curBuf = (int8_t *)mMixBuffer;
2963 // output audio to hardware
2964 while (frameCount) {
2965 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002966 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002967 if (CC_UNLIKELY(buffer.raw == NULL)) {
2968 memset(curBuf, 0, frameCount * mFrameSize);
2969 break;
2970 }
2971 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2972 frameCount -= buffer.frameCount;
2973 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002974 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002975 }
2976 sleepTime = 0;
2977 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002978 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08002979
2980 // apply volume
2981
2982 // Do not apply volume on compressed audio
2983 if (!audio_is_linear_pcm(mFormat)) {
2984 return;
2985 }
2986
2987 // convert to signed 16 bit before volume calculation
2988 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
2989 size_t count = mFrameCount * mChannelCount;
2990 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2991 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002992 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08002993 *dst-- = (int16_t)(*src--^0x80) << 8;
2994 }
2995 }
2996
2997 frameCount = mFrameCount;
2998 int16_t *out = mMixBuffer;
2999 if (rampVolume) {
3000 if (mChannelCount == 1) {
3001 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3002 int32_t vlInc = d / (int32_t)frameCount;
3003 int32_t vl = ((int32_t)mLeftVolShort << 16);
3004 do {
3005 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3006 out++;
3007 vl += vlInc;
3008 } while (--frameCount);
3009
3010 } else {
3011 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3012 int32_t vlInc = d / (int32_t)frameCount;
3013 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
3014 int32_t vrInc = d / (int32_t)frameCount;
3015 int32_t vl = ((int32_t)mLeftVolShort << 16);
3016 int32_t vr = ((int32_t)mRightVolShort << 16);
3017 do {
3018 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3019 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3020 out += 2;
3021 vl += vlInc;
3022 vr += vrInc;
3023 } while (--frameCount);
3024 }
3025 } else {
3026 if (mChannelCount == 1) {
3027 do {
3028 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3029 out++;
3030 } while (--frameCount);
3031 } else {
3032 do {
3033 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3034 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3035 out += 2;
3036 } while (--frameCount);
3037 }
3038 }
3039
3040 // convert back to unsigned 8 bit after volume calculation
3041 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3042 size_t count = mFrameCount * mChannelCount;
3043 int16_t *src = mMixBuffer;
3044 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003045 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003046 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3047 }
3048 }
3049
3050 mLeftVolShort = leftVol;
3051 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003052}
3053
3054void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3055{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003056 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003057 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003058 sleepTime = activeSleepTime;
3059 } else {
3060 sleepTime = idleSleepTime;
3061 }
3062 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3063 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
3064 sleepTime = 0;
3065 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003066}
3067
3068// getTrackName_l() must be called with ThreadBase::mLock held
3069int AudioFlinger::DirectOutputThread::getTrackName_l()
3070{
3071 return 0;
3072}
3073
3074// deleteTrackName_l() must be called with ThreadBase::mLock held
3075void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3076{
3077}
3078
3079// checkForNewParameters_l() must be called with ThreadBase::mLock held
3080bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3081{
3082 bool reconfig = false;
3083
3084 while (!mNewParameters.isEmpty()) {
3085 status_t status = NO_ERROR;
3086 String8 keyValuePair = mNewParameters[0];
3087 AudioParameter param = AudioParameter(keyValuePair);
3088 int value;
3089
3090 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3091 // do not accept frame count changes if tracks are open as the track buffer
3092 // size depends on frame count and correct behavior would not be garantied
3093 // if frame count is changed after track creation
3094 if (!mTracks.isEmpty()) {
3095 status = INVALID_OPERATION;
3096 } else {
3097 reconfig = true;
3098 }
3099 }
3100 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003101 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003102 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003103 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003104 mOutput->stream->common.standby(&mOutput->stream->common);
3105 mStandby = true;
3106 mBytesWritten = 0;
3107 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 }
3110 if (status == NO_ERROR && reconfig) {
3111 readOutputParameters();
3112 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3113 }
3114 }
3115
3116 mNewParameters.removeAt(0);
3117
3118 mParamStatus = status;
3119 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003120 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3121 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003122 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003123 }
3124 return reconfig;
3125}
3126
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003127uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003128{
3129 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003130 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003131 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003132 } else {
3133 time = 10000;
3134 }
3135 return time;
3136}
3137
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003138uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003139{
3140 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003141 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003142 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003143 } else {
3144 time = 10000;
3145 }
3146 return time;
3147}
3148
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003149uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003150{
3151 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003152 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003153 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3154 } else {
3155 time = 10000;
3156 }
3157 return time;
3158}
3159
Glenn Kasten66fcab92012-02-24 14:59:21 -08003160void AudioFlinger::DirectOutputThread::cacheParameters_l()
3161{
3162 PlaybackThread::cacheParameters_l();
3163
3164 // use shorter standby delay as on normal output to release
3165 // hardware resources as soon as possible
3166 standbyDelay = microseconds(activeSleepTime*2);
3167}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003168
Mathias Agopian65ab4712010-07-14 17:59:35 -07003169// ----------------------------------------------------------------------------
3170
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003171AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003172 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003173 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3174 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003175{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003176 addOutputTrack(mainThread);
3177}
3178
3179AudioFlinger::DuplicatingThread::~DuplicatingThread()
3180{
3181 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3182 mOutputTracks[i]->destroy();
3183 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184}
3185
Glenn Kasten000f0e32012-03-01 17:10:56 -08003186void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003187{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003188 // mix buffers...
3189 if (outputsReady(outputTracks)) {
3190 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3191 } else {
3192 memset(mMixBuffer, 0, mixBufferSize);
3193 }
3194 sleepTime = 0;
3195 writeFrames = mFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003196}
3197
3198void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3199{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003200 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003201 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003202 sleepTime = activeSleepTime;
3203 } else {
3204 sleepTime = idleSleepTime;
3205 }
3206 } else if (mBytesWritten != 0) {
3207 // flush remaining overflow buffers in output tracks
3208 for (size_t i = 0; i < outputTracks.size(); i++) {
3209 if (outputTracks[i]->isActive()) {
3210 sleepTime = 0;
3211 writeFrames = 0;
3212 memset(mMixBuffer, 0, mixBufferSize);
3213 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003214 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003215 }
3216 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003217}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003218
Glenn Kasten000f0e32012-03-01 17:10:56 -08003219void AudioFlinger::DuplicatingThread::threadLoop_write()
3220{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003221 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003222 for (size_t i = 0; i < outputTracks.size(); i++) {
3223 outputTracks[i]->write(mMixBuffer, writeFrames);
3224 }
3225 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003226}
Glenn Kasten688a6402012-02-29 07:57:06 -08003227
Glenn Kasten000f0e32012-03-01 17:10:56 -08003228void AudioFlinger::DuplicatingThread::threadLoop_standby()
3229{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003230 // DuplicatingThread implements standby by stopping all tracks
3231 for (size_t i = 0; i < outputTracks.size(); i++) {
3232 outputTracks[i]->stop();
3233 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003234}
3235
Glenn Kastenfa26a852012-03-06 11:28:04 -08003236void AudioFlinger::DuplicatingThread::saveOutputTracks()
3237{
3238 outputTracks = mOutputTracks;
3239}
3240
3241void AudioFlinger::DuplicatingThread::clearOutputTracks()
3242{
3243 outputTracks.clear();
3244}
3245
Mathias Agopian65ab4712010-07-14 17:59:35 -07003246void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3247{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003248 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003249 // FIXME explain this formula
Mathias Agopian65ab4712010-07-14 17:59:35 -07003250 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003251 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003252 this,
3253 mSampleRate,
3254 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003255 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003256 frameCount);
3257 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003258 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003259 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003260 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003261 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003262 }
3263}
3264
3265void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3266{
3267 Mutex::Autolock _l(mLock);
3268 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003269 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003270 mOutputTracks[i]->destroy();
3271 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003272 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003273 return;
3274 }
3275 }
Steve Block3856b092011-10-20 11:56:00 +01003276 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003277}
3278
Glenn Kasten438b0362012-03-06 11:24:48 -08003279// caller must hold mLock
3280void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003281{
3282 mWaitTimeMs = UINT_MAX;
3283 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3284 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003285 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003286 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3287 if (waitTimeMs < mWaitTimeMs) {
3288 mWaitTimeMs = waitTimeMs;
3289 }
3290 }
3291 }
3292}
3293
3294
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003295bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003296{
3297 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003298 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003299 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003300 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003301 return false;
3302 }
3303 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3304 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003305 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003306 return false;
3307 }
3308 }
3309 return true;
3310}
3311
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003312uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003313{
3314 return (mWaitTimeMs * 1000) / 2;
3315}
3316
Glenn Kasten66fcab92012-02-24 14:59:21 -08003317void AudioFlinger::DuplicatingThread::cacheParameters_l()
3318{
3319 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3320 updateWaitTime_l();
3321
3322 MixerThread::cacheParameters_l();
3323}
3324
Mathias Agopian65ab4712010-07-14 17:59:35 -07003325// ----------------------------------------------------------------------------
3326
3327// TrackBase constructor must be called with AudioFlinger::mLock held
3328AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003329 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003330 const sp<Client>& client,
3331 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003332 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003333 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003334 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003335 const sp<IMemory>& sharedBuffer,
3336 int sessionId)
3337 : RefBase(),
3338 mThread(thread),
3339 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003340 mCblk(NULL),
3341 // mBuffer
3342 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003343 mFrameCount(0),
3344 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003345 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003346 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003347 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003348 // mChannelCount
3349 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003350{
Steve Block3856b092011-10-20 11:56:00 +01003351 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003352
Steve Blockb8a80522011-12-20 16:23:08 +00003353 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003354 size_t size = sizeof(audio_track_cblk_t);
3355 uint8_t channelCount = popcount(channelMask);
3356 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3357 if (sharedBuffer == 0) {
3358 size += bufferSize;
3359 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003360
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003361 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003362 mCblkMemory = client->heap()->allocate(size);
3363 if (mCblkMemory != 0) {
3364 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003365 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003366 new(mCblk) audio_track_cblk_t();
3367 // clear all buffers
3368 mCblk->frameCount = frameCount;
3369 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003370// uncomment the following lines to quickly test 32-bit wraparound
3371// mCblk->user = 0xffff0000;
3372// mCblk->server = 0xffff0000;
3373// mCblk->userBase = 0xffff0000;
3374// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003375 mChannelCount = channelCount;
3376 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003377 if (sharedBuffer == 0) {
3378 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3379 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3380 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003381 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003382 mCblk->flags = CBLK_UNDERRUN_ON;
3383 } else {
3384 mBuffer = sharedBuffer->pointer();
3385 }
3386 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3387 }
3388 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003389 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003390 client->heap()->dump("AudioTrack");
3391 return;
3392 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003393 } else {
3394 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07003395 // construct the shared structure in-place.
3396 new(mCblk) audio_track_cblk_t();
3397 // clear all buffers
3398 mCblk->frameCount = frameCount;
3399 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003400// uncomment the following lines to quickly test 32-bit wraparound
3401// mCblk->user = 0xffff0000;
3402// mCblk->server = 0xffff0000;
3403// mCblk->userBase = 0xffff0000;
3404// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003405 mChannelCount = channelCount;
3406 mChannelMask = channelMask;
3407 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3408 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3409 // Force underrun condition to avoid false underrun callback until first data is
3410 // written to buffer (other flags are cleared)
3411 mCblk->flags = CBLK_UNDERRUN_ON;
3412 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003413 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003414}
3415
3416AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3417{
Glenn Kastena0d68332012-01-27 16:47:15 -08003418 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003419 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003420 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003421 } else {
3422 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003423 }
3424 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003425 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003426 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003427 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003428 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003429 // If the client's reference count drops to zero, the associated destructor
3430 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3431 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003432 mClient.clear();
3433 }
3434}
3435
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003436// AudioBufferProvider interface
3437// getNextBuffer() = 0;
3438// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07003439void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3440{
Glenn Kastene0feee32011-12-13 11:53:26 -08003441 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003442 mFrameCount = buffer->frameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003443 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003444 buffer->frameCount = 0;
3445}
3446
3447bool AudioFlinger::ThreadBase::TrackBase::step() {
3448 bool result;
3449 audio_track_cblk_t* cblk = this->cblk();
3450
3451 result = cblk->stepServer(mFrameCount);
3452 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003453 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003454 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003455 }
3456 return result;
3457}
3458
3459void AudioFlinger::ThreadBase::TrackBase::reset() {
3460 audio_track_cblk_t* cblk = this->cblk();
3461
3462 cblk->user = 0;
3463 cblk->server = 0;
3464 cblk->userBase = 0;
3465 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003466 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01003467 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003468}
3469
Mathias Agopian65ab4712010-07-14 17:59:35 -07003470int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3471 return (int)mCblk->sampleRate;
3472}
3473
Mathias Agopian65ab4712010-07-14 17:59:35 -07003474void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3475 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003476 size_t frameSize = cblk->frameSize;
3477 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3478 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003479
3480 // Check validity of returned pointer in case the track control block would have been corrupted.
3481 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003482 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003483 ALOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Marco Nelissena1472d92012-03-30 14:36:54 -07003484 server %u, serverBase %u, user %u, userBase %u",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003485 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003486 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003487 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003488 }
3489
3490 return bufferStart;
3491}
3492
Eric Laurenta011e352012-03-29 15:51:43 -07003493status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
3494{
3495 mSyncEvents.add(event);
3496 return NO_ERROR;
3497}
3498
Mathias Agopian65ab4712010-07-14 17:59:35 -07003499// ----------------------------------------------------------------------------
3500
3501// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3502AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003503 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003504 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003505 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003506 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003507 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003508 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003509 int frameCount,
3510 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07003511 int sessionId,
3512 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003513 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07003514 mMute(false),
3515 // mFillingUpStatus ?
3516 // mRetryCount initialized later when needed
3517 mSharedBuffer(sharedBuffer),
3518 mStreamType(streamType),
3519 mName(-1), // see note below
3520 mMainBuffer(thread->mixBuffer()),
3521 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07003522 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07003523 mPresentationCompleteFrames(0),
3524 mFlags(flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003525{
3526 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003527 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3528 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003529 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kastenf9959012012-03-19 11:14:37 -07003530 // to avoid leaking a track name, do not allocate one unless there is an mCblk
3531 mName = thread->getTrackName_l();
3532 if (mName < 0) {
3533 ALOGE("no more track names available");
3534 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003535 }
Glenn Kastenf9959012012-03-19 11:14:37 -07003536 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003537}
3538
3539AudioFlinger::PlaybackThread::Track::~Track()
3540{
Steve Block3856b092011-10-20 11:56:00 +01003541 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003542 sp<ThreadBase> thread = mThread.promote();
3543 if (thread != 0) {
3544 Mutex::Autolock _l(thread->mLock);
3545 mState = TERMINATED;
3546 }
3547}
3548
3549void AudioFlinger::PlaybackThread::Track::destroy()
3550{
3551 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3552 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08003553 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003554 // we must acquire a strong reference on this Track before locking mLock
3555 // here so that the destructor is called only when exiting this function.
3556 // On the other hand, as long as Track::destroy() is only called by
3557 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3558 // this Track with its member mTrack.
3559 sp<Track> keep(this);
3560 { // scope for mLock
3561 sp<ThreadBase> thread = mThread.promote();
3562 if (thread != 0) {
3563 if (!isOutputTrack()) {
3564 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08003565 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003566
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003567#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003568 // to track the speaker usage
3569 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003570#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003571 }
3572 AudioSystem::releaseOutput(thread->id());
3573 }
3574 Mutex::Autolock _l(thread->mLock);
3575 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3576 playbackThread->destroyTrack_l(this);
3577 }
3578 }
3579}
3580
3581void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3582{
Glenn Kasten83d86532012-01-17 14:39:34 -08003583 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003584 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 -07003585 mName - AudioMixer::TRACK0,
Glenn Kasten44deb052012-02-05 18:09:08 -08003586 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003587 mStreamType,
3588 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003589 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003590 mSessionId,
3591 mFrameCount,
3592 mState,
3593 mMute,
3594 mFillingUpStatus,
3595 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003596 vlr & 0xFFFF,
3597 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003598 mCblk->server,
3599 mCblk->user,
3600 (int)mMainBuffer,
3601 (int)mAuxBuffer);
3602}
3603
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003604// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08003605status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003606 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003607{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003608 audio_track_cblk_t* cblk = this->cblk();
3609 uint32_t framesReady;
3610 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003611
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003612 // Check if last stepServer failed, try to step now
3613 if (mStepServerFailed) {
3614 if (!step()) goto getNextBuffer_exit;
3615 ALOGV("stepServer recovered");
3616 mStepServerFailed = false;
3617 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003618
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003619 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003620
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003621 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003622 uint32_t s = cblk->server;
3623 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3624
3625 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3626 if (framesReq > framesReady) {
3627 framesReq = framesReady;
3628 }
Marco Nelissena1472d92012-03-30 14:36:54 -07003629 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003630 framesReq = bufferEnd - s;
3631 }
3632
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003633 buffer->raw = getBuffer(s, framesReq);
3634 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003635
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003636 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003637 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003638 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003639
3640getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003641 buffer->raw = NULL;
3642 buffer->frameCount = 0;
3643 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3644 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003645}
3646
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003647uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08003648 return mCblk->framesReady();
3649}
3650
Mathias Agopian65ab4712010-07-14 17:59:35 -07003651bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003652 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003653
John Grossman4ff14ba2012-02-08 16:37:41 -08003654 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003655 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3656 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003657 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003658 return true;
3659 }
3660 return false;
3661}
3662
Eric Laurenta011e352012-03-29 15:51:43 -07003663status_t AudioFlinger::PlaybackThread::Track::start(pid_t tid,
3664 AudioSystem::sync_event_t event,
3665 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003666{
3667 status_t status = NO_ERROR;
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003668 ALOGV("start(%d), calling pid %d session %d tid %d",
3669 mName, IPCThreadState::self()->getCallingPid(), mSessionId, tid);
Glenn Kasten73d22752012-03-19 13:38:30 -07003670 // check for use case 2 with missing callback
3671 if (isFastTrack() && (mSharedBuffer == 0) && (tid == 0)) {
3672 ALOGW("AUDIO_POLICY_OUTPUT_FLAG_FAST denied");
3673 mFlags &= ~IAudioFlinger::TRACK_FAST;
3674 // FIXME the track must be invalidated and moved to another thread or
3675 // attached directly to the normal mixer now
3676 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003677 sp<ThreadBase> thread = mThread.promote();
3678 if (thread != 0) {
3679 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003680 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003681 // here the track could be either new, or restarted
3682 // in both cases "unstop" the track
3683 if (mState == PAUSED) {
3684 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003685 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003686 } else {
3687 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003688 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003689 }
3690
3691 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3692 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003693 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003694 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003695
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003696#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003697 // to track the speaker usage
3698 if (status == NO_ERROR) {
3699 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3700 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003701#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003702 }
3703 if (status == NO_ERROR) {
3704 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3705 playbackThread->addTrack_l(this);
3706 } else {
3707 mState = state;
3708 }
3709 } else {
3710 status = BAD_VALUE;
3711 }
3712 return status;
3713}
3714
3715void AudioFlinger::PlaybackThread::Track::stop()
3716{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003717 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003718 sp<ThreadBase> thread = mThread.promote();
3719 if (thread != 0) {
3720 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003721 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003722 if (mState > STOPPED) {
3723 mState = STOPPED;
3724 // If the track is not active (PAUSED and buffers full), flush buffers
3725 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3726 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3727 reset();
3728 }
Steve Block3856b092011-10-20 11:56:00 +01003729 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003730 }
3731 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3732 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003733 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003734 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003735
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003736#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003737 // to track the speaker usage
3738 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003739#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003740 }
3741 }
3742}
3743
3744void AudioFlinger::PlaybackThread::Track::pause()
3745{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003746 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003747 sp<ThreadBase> thread = mThread.promote();
3748 if (thread != 0) {
3749 Mutex::Autolock _l(thread->mLock);
3750 if (mState == ACTIVE || mState == RESUMING) {
3751 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003752 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003753 if (!isOutputTrack()) {
3754 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003755 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003756 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003757
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003758#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003759 // to track the speaker usage
3760 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003761#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003762 }
3763 }
3764 }
3765}
3766
3767void AudioFlinger::PlaybackThread::Track::flush()
3768{
Steve Block3856b092011-10-20 11:56:00 +01003769 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003770 sp<ThreadBase> thread = mThread.promote();
3771 if (thread != 0) {
3772 Mutex::Autolock _l(thread->mLock);
3773 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3774 return;
3775 }
3776 // No point remaining in PAUSED state after a flush => go to
3777 // STOPPED state
3778 mState = STOPPED;
3779
Eric Laurent38ccae22011-03-28 18:37:07 -07003780 // do not reset the track if it is still in the process of being stopped or paused.
3781 // this will be done by prepareTracks_l() when the track is stopped.
3782 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3783 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3784 reset();
3785 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003786 }
3787}
3788
3789void AudioFlinger::PlaybackThread::Track::reset()
3790{
3791 // Do not reset twice to avoid discarding data written just after a flush and before
3792 // the audioflinger thread detects the track is stopped.
3793 if (!mResetDone) {
3794 TrackBase::reset();
3795 // Force underrun condition to avoid false underrun callback until first data is
3796 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003797 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3798 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003799 mFillingUpStatus = FS_FILLING;
3800 mResetDone = true;
Eric Laurenta011e352012-03-29 15:51:43 -07003801 mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003802 }
3803}
3804
3805void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3806{
3807 mMute = muted;
3808}
3809
Mathias Agopian65ab4712010-07-14 17:59:35 -07003810status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3811{
3812 status_t status = DEAD_OBJECT;
3813 sp<ThreadBase> thread = mThread.promote();
3814 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003815 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3816 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003817 }
3818 return status;
3819}
3820
3821void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3822{
3823 mAuxEffectId = EffectId;
3824 mAuxBuffer = buffer;
3825}
3826
Eric Laurenta011e352012-03-29 15:51:43 -07003827bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
3828 size_t audioHalFrames)
3829{
3830 // a track is considered presented when the total number of frames written to audio HAL
3831 // corresponds to the number of frames written when presentationComplete() is called for the
3832 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
3833 if (mPresentationCompleteFrames == 0) {
3834 mPresentationCompleteFrames = framesWritten + audioHalFrames;
3835 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
3836 mPresentationCompleteFrames, audioHalFrames);
3837 }
3838 if (framesWritten >= mPresentationCompleteFrames) {
3839 ALOGV("presentationComplete() session %d complete: framesWritten %d",
3840 mSessionId, framesWritten);
3841 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
3842 mPresentationCompleteFrames = 0;
3843 return true;
3844 }
3845 return false;
3846}
3847
3848void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
3849{
3850 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
3851 if (mSyncEvents[i]->type() == type) {
3852 mSyncEvents[i]->trigger();
3853 mSyncEvents.removeAt(i);
3854 i--;
3855 }
3856 }
3857}
3858
3859
John Grossman4ff14ba2012-02-08 16:37:41 -08003860// timed audio tracks
3861
3862sp<AudioFlinger::PlaybackThread::TimedTrack>
3863AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003864 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003865 const sp<Client>& client,
3866 audio_stream_type_t streamType,
3867 uint32_t sampleRate,
3868 audio_format_t format,
3869 uint32_t channelMask,
3870 int frameCount,
3871 const sp<IMemory>& sharedBuffer,
3872 int sessionId) {
3873 if (!client->reserveTimedTrack())
3874 return NULL;
3875
Glenn Kastena0356762012-03-19 10:38:51 -07003876 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08003877 thread, client, streamType, sampleRate, format, channelMask, frameCount,
3878 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08003879}
3880
3881AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003882 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003883 const sp<Client>& client,
3884 audio_stream_type_t streamType,
3885 uint32_t sampleRate,
3886 audio_format_t format,
3887 uint32_t channelMask,
3888 int frameCount,
3889 const sp<IMemory>& sharedBuffer,
3890 int sessionId)
3891 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07003892 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman4ff14ba2012-02-08 16:37:41 -08003893 mTimedSilenceBuffer(NULL),
3894 mTimedSilenceBufferSize(0),
3895 mTimedAudioOutputOnTime(false),
3896 mMediaTimeTransformValid(false)
3897{
3898 LocalClock lc;
3899 mLocalTimeFreq = lc.getLocalFreq();
3900
3901 mLocalTimeToSampleTransform.a_zero = 0;
3902 mLocalTimeToSampleTransform.b_zero = 0;
3903 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3904 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3905 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3906 &mLocalTimeToSampleTransform.a_to_b_denom);
3907}
3908
3909AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3910 mClient->releaseTimedTrack();
3911 delete [] mTimedSilenceBuffer;
3912}
3913
3914status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3915 size_t size, sp<IMemory>* buffer) {
3916
3917 Mutex::Autolock _l(mTimedBufferQueueLock);
3918
3919 trimTimedBufferQueue_l();
3920
3921 // lazily initialize the shared memory heap for timed buffers
3922 if (mTimedMemoryDealer == NULL) {
3923 const int kTimedBufferHeapSize = 512 << 10;
3924
3925 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3926 "AudioFlingerTimed");
3927 if (mTimedMemoryDealer == NULL)
3928 return NO_MEMORY;
3929 }
3930
3931 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3932 if (newBuffer == NULL) {
3933 newBuffer = mTimedMemoryDealer->allocate(size);
3934 if (newBuffer == NULL)
3935 return NO_MEMORY;
3936 }
3937
3938 *buffer = newBuffer;
3939 return NO_ERROR;
3940}
3941
3942// caller must hold mTimedBufferQueueLock
3943void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
3944 int64_t mediaTimeNow;
3945 {
3946 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3947 if (!mMediaTimeTransformValid)
3948 return;
3949
3950 int64_t targetTimeNow;
3951 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
3952 ? mCCHelper.getCommonTime(&targetTimeNow)
3953 : mCCHelper.getLocalTime(&targetTimeNow);
3954
3955 if (OK != res)
3956 return;
3957
3958 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
3959 &mediaTimeNow)) {
3960 return;
3961 }
3962 }
3963
3964 size_t trimIndex;
3965 for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
3966 if (mTimedBufferQueue[trimIndex].pts() > mediaTimeNow)
3967 break;
3968 }
3969
3970 if (trimIndex) {
3971 mTimedBufferQueue.removeItemsAt(0, trimIndex);
3972 }
3973}
3974
3975status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
3976 const sp<IMemory>& buffer, int64_t pts) {
3977
3978 {
3979 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3980 if (!mMediaTimeTransformValid)
3981 return INVALID_OPERATION;
3982 }
3983
3984 Mutex::Autolock _l(mTimedBufferQueueLock);
3985
3986 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
3987
3988 return NO_ERROR;
3989}
3990
3991status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
3992 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
3993
3994 ALOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
3995 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
3996 target);
3997
3998 if (!(target == TimedAudioTrack::LOCAL_TIME ||
3999 target == TimedAudioTrack::COMMON_TIME)) {
4000 return BAD_VALUE;
4001 }
4002
4003 Mutex::Autolock lock(mMediaTimeTransformLock);
4004 mMediaTimeTransform = xform;
4005 mMediaTimeTransformTarget = target;
4006 mMediaTimeTransformValid = true;
4007
4008 return NO_ERROR;
4009}
4010
4011#define min(a, b) ((a) < (b) ? (a) : (b))
4012
4013// implementation of getNextBuffer for tracks whose buffers have timestamps
4014status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4015 AudioBufferProvider::Buffer* buffer, int64_t pts)
4016{
4017 if (pts == AudioBufferProvider::kInvalidPTS) {
4018 buffer->raw = 0;
4019 buffer->frameCount = 0;
4020 return INVALID_OPERATION;
4021 }
4022
John Grossman4ff14ba2012-02-08 16:37:41 -08004023 Mutex::Autolock _l(mTimedBufferQueueLock);
4024
4025 while (true) {
4026
4027 // if we have no timed buffers, then fail
4028 if (mTimedBufferQueue.isEmpty()) {
4029 buffer->raw = 0;
4030 buffer->frameCount = 0;
4031 return NOT_ENOUGH_DATA;
4032 }
4033
4034 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4035
4036 // calculate the PTS of the head of the timed buffer queue expressed in
4037 // local time
4038 int64_t headLocalPTS;
4039 {
4040 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4041
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004042 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08004043
4044 if (mMediaTimeTransform.a_to_b_denom == 0) {
4045 // the transform represents a pause, so yield silence
4046 timedYieldSilence(buffer->frameCount, buffer);
4047 return NO_ERROR;
4048 }
4049
4050 int64_t transformedPTS;
4051 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4052 &transformedPTS)) {
4053 // the transform failed. this shouldn't happen, but if it does
4054 // then just drop this buffer
4055 ALOGW("timedGetNextBuffer transform failed");
4056 buffer->raw = 0;
4057 buffer->frameCount = 0;
4058 mTimedBufferQueue.removeAt(0);
4059 return NO_ERROR;
4060 }
4061
4062 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
4063 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
4064 &headLocalPTS)) {
4065 buffer->raw = 0;
4066 buffer->frameCount = 0;
4067 return INVALID_OPERATION;
4068 }
4069 } else {
4070 headLocalPTS = transformedPTS;
4071 }
4072 }
4073
4074 // adjust the head buffer's PTS to reflect the portion of the head buffer
4075 // that has already been consumed
4076 int64_t effectivePTS = headLocalPTS +
4077 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4078
4079 // Calculate the delta in samples between the head of the input buffer
4080 // queue and the start of the next output buffer that will be written.
4081 // If the transformation fails because of over or underflow, it means
4082 // that the sample's position in the output stream is so far out of
4083 // whack that it should just be dropped.
4084 int64_t sampleDelta;
4085 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4086 ALOGV("*** head buffer is too far from PTS: dropped buffer");
4087 mTimedBufferQueue.removeAt(0);
4088 continue;
4089 }
4090 if (!mLocalTimeToSampleTransform.doForwardTransform(
4091 (effectivePTS - pts) << 32, &sampleDelta)) {
4092 ALOGV("*** too late during sample rate transform: dropped buffer");
4093 mTimedBufferQueue.removeAt(0);
4094 continue;
4095 }
4096
4097 ALOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
4098 __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
4099 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
4100 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
4101
4102 // if the delta between the ideal placement for the next input sample and
4103 // the current output position is within this threshold, then we will
4104 // concatenate the next input samples to the previous output
4105 const int64_t kSampleContinuityThreshold =
4106 (static_cast<int64_t>(sampleRate()) << 32) / 10;
4107
4108 // if this is the first buffer of audio that we're emitting from this track
4109 // then it should be almost exactly on time.
4110 const int64_t kSampleStartupThreshold = 1LL << 32;
4111
4112 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
4113 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
4114 // the next input is close enough to being on time, so concatenate it
4115 // with the last output
4116 timedYieldSamples(buffer);
4117
4118 ALOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4119 return NO_ERROR;
4120 } else if (sampleDelta > 0) {
4121 // the gap between the current output position and the proper start of
4122 // the next input sample is too big, so fill it with silence
4123 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4124
4125 timedYieldSilence(framesUntilNextInput, buffer);
4126 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4127 return NO_ERROR;
4128 } else {
4129 // the next input sample is late
4130 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4131 size_t onTimeSamplePosition =
4132 head.position() + lateFrames * mCblk->frameSize;
4133
4134 if (onTimeSamplePosition > head.buffer()->size()) {
4135 // all the remaining samples in the head are too late, so
4136 // drop it and move on
4137 ALOGV("*** too late: dropped buffer");
4138 mTimedBufferQueue.removeAt(0);
4139 continue;
4140 } else {
4141 // skip over the late samples
4142 head.setPosition(onTimeSamplePosition);
4143
4144 // yield the available samples
4145 timedYieldSamples(buffer);
4146
4147 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4148 return NO_ERROR;
4149 }
4150 }
4151 }
4152}
4153
4154// Yield samples from the timed buffer queue head up to the given output
4155// buffer's capacity.
4156//
4157// Caller must hold mTimedBufferQueueLock
4158void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples(
4159 AudioBufferProvider::Buffer* buffer) {
4160
4161 const TimedBuffer& head = mTimedBufferQueue[0];
4162
4163 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4164 head.position());
4165
4166 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4167 mCblk->frameSize);
4168 size_t framesRequested = buffer->frameCount;
4169 buffer->frameCount = min(framesLeftInHead, framesRequested);
4170
4171 mTimedAudioOutputOnTime = true;
4172}
4173
4174// Yield samples of silence up to the given output buffer's capacity
4175//
4176// Caller must hold mTimedBufferQueueLock
4177void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence(
4178 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4179
4180 // lazily allocate a buffer filled with silence
4181 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4182 delete [] mTimedSilenceBuffer;
4183 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4184 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4185 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4186 }
4187
4188 buffer->raw = mTimedSilenceBuffer;
4189 size_t framesRequested = buffer->frameCount;
4190 buffer->frameCount = min(numFrames, framesRequested);
4191
4192 mTimedAudioOutputOnTime = false;
4193}
4194
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004195// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004196void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4197 AudioBufferProvider::Buffer* buffer) {
4198
4199 Mutex::Autolock _l(mTimedBufferQueueLock);
4200
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004201 // If the buffer which was just released is part of the buffer at the head
4202 // of the queue, be sure to update the amt of the buffer which has been
4203 // consumed. If the buffer being returned is not part of the head of the
4204 // queue, its either because the buffer is part of the silence buffer, or
4205 // because the head of the timed queue was trimmed after the mixer called
4206 // getNextBuffer but before the mixer called releaseBuffer.
4207 if ((buffer->raw != mTimedSilenceBuffer) && mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004208 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004209
4210 void* start = head.buffer()->pointer();
Glenn Kastenf063b492012-02-17 16:24:10 -08004211 void* end = (char *) head.buffer()->pointer() + head.buffer()->size();
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004212
4213 if ((buffer->raw >= start) && (buffer->raw <= end)) {
4214 head.setPosition(head.position() +
4215 (buffer->frameCount * mCblk->frameSize));
4216 if (static_cast<size_t>(head.position()) >= head.buffer()->size()) {
4217 mTimedBufferQueue.removeAt(0);
4218 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004219 }
4220 }
4221
4222 buffer->raw = 0;
4223 buffer->frameCount = 0;
4224}
4225
4226uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4227 Mutex::Autolock _l(mTimedBufferQueueLock);
4228
4229 uint32_t frames = 0;
4230 for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4231 const TimedBuffer& tb = mTimedBufferQueue[i];
4232 frames += (tb.buffer()->size() - tb.position()) / mCblk->frameSize;
4233 }
4234
4235 return frames;
4236}
4237
4238AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4239 : mPTS(0), mPosition(0) {}
4240
4241AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4242 const sp<IMemory>& buffer, int64_t pts)
4243 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4244
Mathias Agopian65ab4712010-07-14 17:59:35 -07004245// ----------------------------------------------------------------------------
4246
4247// RecordTrack constructor must be called with AudioFlinger::mLock held
4248AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004249 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004250 const sp<Client>& client,
4251 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004252 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004253 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004254 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004255 int sessionId)
4256 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004257 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004258 mOverflow(false)
4259{
4260 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004261 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
4262 if (format == AUDIO_FORMAT_PCM_16_BIT) {
4263 mCblk->frameSize = mChannelCount * sizeof(int16_t);
4264 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
4265 mCblk->frameSize = mChannelCount * sizeof(int8_t);
4266 } else {
4267 mCblk->frameSize = sizeof(int8_t);
4268 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004269 }
4270}
4271
4272AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4273{
4274 sp<ThreadBase> thread = mThread.promote();
4275 if (thread != 0) {
4276 AudioSystem::releaseInput(thread->id());
4277 }
4278}
4279
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004280// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004281status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004282{
4283 audio_track_cblk_t* cblk = this->cblk();
4284 uint32_t framesAvail;
4285 uint32_t framesReq = buffer->frameCount;
4286
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004287 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004288 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004289 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004290 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004291 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004292 }
4293
4294 framesAvail = cblk->framesAvailable_l();
4295
Glenn Kastenf6b16782011-12-15 09:51:17 -08004296 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004297 uint32_t s = cblk->server;
4298 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4299
4300 if (framesReq > framesAvail) {
4301 framesReq = framesAvail;
4302 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004303 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004304 framesReq = bufferEnd - s;
4305 }
4306
4307 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004308 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004309
4310 buffer->frameCount = framesReq;
4311 return NO_ERROR;
4312 }
4313
4314getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004315 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004316 buffer->frameCount = 0;
4317 return NOT_ENOUGH_DATA;
4318}
4319
Eric Laurenta011e352012-03-29 15:51:43 -07004320status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid,
4321 AudioSystem::sync_event_t event,
4322 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004323{
4324 sp<ThreadBase> thread = mThread.promote();
4325 if (thread != 0) {
4326 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurenta011e352012-03-29 15:51:43 -07004327 return recordThread->start(this, tid, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004328 } else {
4329 return BAD_VALUE;
4330 }
4331}
4332
4333void AudioFlinger::RecordThread::RecordTrack::stop()
4334{
4335 sp<ThreadBase> thread = mThread.promote();
4336 if (thread != 0) {
4337 RecordThread *recordThread = (RecordThread *)thread.get();
4338 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004339 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08004340 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07004341 // read from buffer
4342 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004343 }
4344}
4345
4346void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4347{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004348 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004349 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004350 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004351 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004352 mSessionId,
4353 mFrameCount,
4354 mState,
4355 mCblk->sampleRate,
4356 mCblk->server,
4357 mCblk->user);
4358}
4359
4360
4361// ----------------------------------------------------------------------------
4362
4363AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004364 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004365 DuplicatingThread *sourceThread,
4366 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004367 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004368 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004369 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07004370 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
4371 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004372 mActive(false), mSourceThread(sourceThread)
4373{
4374
Mathias Agopian65ab4712010-07-14 17:59:35 -07004375 if (mCblk != NULL) {
4376 mCblk->flags |= CBLK_DIRECTION_OUT;
4377 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004378 mOutBuffer.frameCount = 0;
4379 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01004380 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004381 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4382 mCblk, mBuffer, mCblk->buffers,
4383 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004384 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004385 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004386 }
4387}
4388
4389AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4390{
4391 clearBufferQueue();
4392}
4393
Eric Laurenta011e352012-03-29 15:51:43 -07004394status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid,
4395 AudioSystem::sync_event_t event,
4396 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004397{
Eric Laurenta011e352012-03-29 15:51:43 -07004398 status_t status = Track::start(tid, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004399 if (status != NO_ERROR) {
4400 return status;
4401 }
4402
4403 mActive = true;
4404 mRetryCount = 127;
4405 return status;
4406}
4407
4408void AudioFlinger::PlaybackThread::OutputTrack::stop()
4409{
4410 Track::stop();
4411 clearBufferQueue();
4412 mOutBuffer.frameCount = 0;
4413 mActive = false;
4414}
4415
4416bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4417{
4418 Buffer *pInBuffer;
4419 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004420 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004421 bool outputBufferFull = false;
4422 inBuffer.frameCount = frames;
4423 inBuffer.i16 = data;
4424
4425 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4426
4427 if (!mActive && frames != 0) {
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004428 start(0);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004429 sp<ThreadBase> thread = mThread.promote();
4430 if (thread != 0) {
4431 MixerThread *mixerThread = (MixerThread *)thread.get();
4432 if (mCblk->frameCount > frames){
4433 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4434 uint32_t startFrames = (mCblk->frameCount - frames);
4435 pInBuffer = new Buffer;
4436 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4437 pInBuffer->frameCount = startFrames;
4438 pInBuffer->i16 = pInBuffer->mBuffer;
4439 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4440 mBufferQueue.add(pInBuffer);
4441 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004442 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004443 }
4444 }
4445 }
4446 }
4447
4448 while (waitTimeLeftMs) {
4449 // First write pending buffers, then new data
4450 if (mBufferQueue.size()) {
4451 pInBuffer = mBufferQueue.itemAt(0);
4452 } else {
4453 pInBuffer = &inBuffer;
4454 }
4455
4456 if (pInBuffer->frameCount == 0) {
4457 break;
4458 }
4459
4460 if (mOutBuffer.frameCount == 0) {
4461 mOutBuffer.frameCount = pInBuffer->frameCount;
4462 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08004463 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01004464 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004465 outputBufferFull = true;
4466 break;
4467 }
4468 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4469 if (waitTimeLeftMs >= waitTimeMs) {
4470 waitTimeLeftMs -= waitTimeMs;
4471 } else {
4472 waitTimeLeftMs = 0;
4473 }
4474 }
4475
4476 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4477 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4478 mCblk->stepUser(outFrames);
4479 pInBuffer->frameCount -= outFrames;
4480 pInBuffer->i16 += outFrames * channelCount;
4481 mOutBuffer.frameCount -= outFrames;
4482 mOutBuffer.i16 += outFrames * channelCount;
4483
4484 if (pInBuffer->frameCount == 0) {
4485 if (mBufferQueue.size()) {
4486 mBufferQueue.removeAt(0);
4487 delete [] pInBuffer->mBuffer;
4488 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01004489 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004490 } else {
4491 break;
4492 }
4493 }
4494 }
4495
4496 // If we could not write all frames, allocate a buffer and queue it for next time.
4497 if (inBuffer.frameCount) {
4498 sp<ThreadBase> thread = mThread.promote();
4499 if (thread != 0 && !thread->standby()) {
4500 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4501 pInBuffer = new Buffer;
4502 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4503 pInBuffer->frameCount = inBuffer.frameCount;
4504 pInBuffer->i16 = pInBuffer->mBuffer;
4505 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4506 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01004507 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004508 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004509 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004510 }
4511 }
4512 }
4513
4514 // Calling write() with a 0 length buffer, means that no more data will be written:
4515 // If no more buffers are pending, fill output track buffer to make sure it is started
4516 // by output mixer.
4517 if (frames == 0 && mBufferQueue.size() == 0) {
4518 if (mCblk->user < mCblk->frameCount) {
4519 frames = mCblk->frameCount - mCblk->user;
4520 pInBuffer = new Buffer;
4521 pInBuffer->mBuffer = new int16_t[frames * channelCount];
4522 pInBuffer->frameCount = frames;
4523 pInBuffer->i16 = pInBuffer->mBuffer;
4524 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4525 mBufferQueue.add(pInBuffer);
4526 } else if (mActive) {
4527 stop();
4528 }
4529 }
4530
4531 return outputBufferFull;
4532}
4533
4534status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4535{
4536 int active;
4537 status_t result;
4538 audio_track_cblk_t* cblk = mCblk;
4539 uint32_t framesReq = buffer->frameCount;
4540
Steve Block3856b092011-10-20 11:56:00 +01004541// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004542 buffer->frameCount = 0;
4543
4544 uint32_t framesAvail = cblk->framesAvailable();
4545
4546
4547 if (framesAvail == 0) {
4548 Mutex::Autolock _l(cblk->lock);
4549 goto start_loop_here;
4550 while (framesAvail == 0) {
4551 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004552 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004553 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004554 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004555 }
4556 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4557 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004558 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004559 }
4560 // read the server count again
4561 start_loop_here:
4562 framesAvail = cblk->framesAvailable_l();
4563 }
4564 }
4565
4566// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004567// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004568// }
4569
4570 if (framesReq > framesAvail) {
4571 framesReq = framesAvail;
4572 }
4573
4574 uint32_t u = cblk->user;
4575 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4576
Marco Nelissena1472d92012-03-30 14:36:54 -07004577 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004578 framesReq = bufferEnd - u;
4579 }
4580
4581 buffer->frameCount = framesReq;
4582 buffer->raw = (void *)cblk->buffer(u);
4583 return NO_ERROR;
4584}
4585
4586
4587void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4588{
4589 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004590
4591 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004592 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004593 delete [] pBuffer->mBuffer;
4594 delete pBuffer;
4595 }
4596 mBufferQueue.clear();
4597}
4598
4599// ----------------------------------------------------------------------------
4600
4601AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4602 : RefBase(),
4603 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08004604 // 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 -07004605 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08004606 mPid(pid),
4607 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004608{
4609 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4610}
4611
4612// Client destructor must be called with AudioFlinger::mLock held
4613AudioFlinger::Client::~Client()
4614{
4615 mAudioFlinger->removeClient_l(mPid);
4616}
4617
Glenn Kasten435dbe62012-01-30 10:15:48 -08004618sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004619{
4620 return mMemoryDealer;
4621}
4622
John Grossman4ff14ba2012-02-08 16:37:41 -08004623// Reserve one of the limited slots for a timed audio track associated
4624// with this client
4625bool AudioFlinger::Client::reserveTimedTrack()
4626{
4627 const int kMaxTimedTracksPerClient = 4;
4628
4629 Mutex::Autolock _l(mTimedTrackLock);
4630
4631 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4632 ALOGW("can not create timed track - pid %d has exceeded the limit",
4633 mPid);
4634 return false;
4635 }
4636
4637 mTimedTrackCount++;
4638 return true;
4639}
4640
4641// Release a slot for a timed audio track
4642void AudioFlinger::Client::releaseTimedTrack()
4643{
4644 Mutex::Autolock _l(mTimedTrackLock);
4645 mTimedTrackCount--;
4646}
4647
Mathias Agopian65ab4712010-07-14 17:59:35 -07004648// ----------------------------------------------------------------------------
4649
4650AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4651 const sp<IAudioFlingerClient>& client,
4652 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004653 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004654{
4655}
4656
4657AudioFlinger::NotificationClient::~NotificationClient()
4658{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004659}
4660
4661void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4662{
4663 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08004664 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004665}
4666
4667// ----------------------------------------------------------------------------
4668
4669AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4670 : BnAudioTrack(),
4671 mTrack(track)
4672{
4673}
4674
4675AudioFlinger::TrackHandle::~TrackHandle() {
4676 // just stop the track on deletion, associated resources
4677 // will be freed from the main thread once all pending buffers have
4678 // been played. Unless it's not in the active track list, in which
4679 // case we free everything now...
4680 mTrack->destroy();
4681}
4682
Glenn Kasten90716c52012-01-26 13:40:12 -08004683sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4684 return mTrack->getCblk();
4685}
4686
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004687status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4688 return mTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004689}
4690
4691void AudioFlinger::TrackHandle::stop() {
4692 mTrack->stop();
4693}
4694
4695void AudioFlinger::TrackHandle::flush() {
4696 mTrack->flush();
4697}
4698
4699void AudioFlinger::TrackHandle::mute(bool e) {
4700 mTrack->mute(e);
4701}
4702
4703void AudioFlinger::TrackHandle::pause() {
4704 mTrack->pause();
4705}
4706
Mathias Agopian65ab4712010-07-14 17:59:35 -07004707status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4708{
4709 return mTrack->attachAuxEffect(EffectId);
4710}
4711
John Grossman4ff14ba2012-02-08 16:37:41 -08004712status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4713 sp<IMemory>* buffer) {
4714 if (!mTrack->isTimedTrack())
4715 return INVALID_OPERATION;
4716
4717 PlaybackThread::TimedTrack* tt =
4718 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4719 return tt->allocateTimedBuffer(size, buffer);
4720}
4721
4722status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4723 int64_t pts) {
4724 if (!mTrack->isTimedTrack())
4725 return INVALID_OPERATION;
4726
4727 PlaybackThread::TimedTrack* tt =
4728 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4729 return tt->queueTimedBuffer(buffer, pts);
4730}
4731
4732status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4733 const LinearTransform& xform, int target) {
4734
4735 if (!mTrack->isTimedTrack())
4736 return INVALID_OPERATION;
4737
4738 PlaybackThread::TimedTrack* tt =
4739 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4740 return tt->setMediaTimeTransform(
4741 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4742}
4743
Mathias Agopian65ab4712010-07-14 17:59:35 -07004744status_t AudioFlinger::TrackHandle::onTransact(
4745 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4746{
4747 return BnAudioTrack::onTransact(code, data, reply, flags);
4748}
4749
4750// ----------------------------------------------------------------------------
4751
4752sp<IAudioRecord> AudioFlinger::openRecord(
4753 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004754 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004755 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004756 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004757 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004758 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08004759 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004760 int *sessionId,
4761 status_t *status)
4762{
4763 sp<RecordThread::RecordTrack> recordTrack;
4764 sp<RecordHandle> recordHandle;
4765 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004766 status_t lStatus;
4767 RecordThread *thread;
4768 size_t inFrameCount;
4769 int lSessionId;
4770
4771 // check calling permissions
4772 if (!recordingAllowed()) {
4773 lStatus = PERMISSION_DENIED;
4774 goto Exit;
4775 }
4776
4777 // add client to list
4778 { // scope for mLock
4779 Mutex::Autolock _l(mLock);
4780 thread = checkRecordThread_l(input);
4781 if (thread == NULL) {
4782 lStatus = BAD_VALUE;
4783 goto Exit;
4784 }
4785
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004786 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004787
4788 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004789 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004790 lSessionId = *sessionId;
4791 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004792 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004793 if (sessionId != NULL) {
4794 *sessionId = lSessionId;
4795 }
4796 }
4797 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004798 recordTrack = thread->createRecordTrack_l(client,
4799 sampleRate,
4800 format,
4801 channelMask,
4802 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004803 lSessionId,
4804 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004805 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004806 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004807 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4808 // destructor is called by the TrackBase destructor with mLock held
4809 client.clear();
4810 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004811 goto Exit;
4812 }
4813
4814 // return to handle to client
4815 recordHandle = new RecordHandle(recordTrack);
4816 lStatus = NO_ERROR;
4817
4818Exit:
4819 if (status) {
4820 *status = lStatus;
4821 }
4822 return recordHandle;
4823}
4824
4825// ----------------------------------------------------------------------------
4826
4827AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4828 : BnAudioRecord(),
4829 mRecordTrack(recordTrack)
4830{
4831}
4832
4833AudioFlinger::RecordHandle::~RecordHandle() {
4834 stop();
4835}
4836
Glenn Kasten90716c52012-01-26 13:40:12 -08004837sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4838 return mRecordTrack->getCblk();
4839}
4840
Eric Laurenta011e352012-03-29 15:51:43 -07004841status_t AudioFlinger::RecordHandle::start(pid_t tid, int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01004842 ALOGV("RecordHandle::start()");
Eric Laurenta011e352012-03-29 15:51:43 -07004843 return mRecordTrack->start(tid, (AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004844}
4845
4846void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004847 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004848 mRecordTrack->stop();
4849}
4850
Mathias Agopian65ab4712010-07-14 17:59:35 -07004851status_t AudioFlinger::RecordHandle::onTransact(
4852 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4853{
4854 return BnAudioRecord::onTransact(code, data, reply, flags);
4855}
4856
4857// ----------------------------------------------------------------------------
4858
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004859AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4860 AudioStreamIn *input,
4861 uint32_t sampleRate,
4862 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004863 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004864 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004865 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004866 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4867 // mRsmpInIndex and mInputBytes set by readInputParameters()
4868 mReqChannelCount(popcount(channels)),
4869 mReqSampleRate(sampleRate)
4870 // mBytesRead is only meaningful while active, and so is cleared in start()
4871 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004872{
Glenn Kasten480b4682012-02-28 12:30:08 -08004873 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07004874
Mathias Agopian65ab4712010-07-14 17:59:35 -07004875 readInputParameters();
4876}
4877
4878
4879AudioFlinger::RecordThread::~RecordThread()
4880{
4881 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004882 delete mResampler;
4883 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004884}
4885
4886void AudioFlinger::RecordThread::onFirstRef()
4887{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004888 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004889}
4890
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004891status_t AudioFlinger::RecordThread::readyToRun()
4892{
4893 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004894 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004895 return status;
4896}
4897
Mathias Agopian65ab4712010-07-14 17:59:35 -07004898bool AudioFlinger::RecordThread::threadLoop()
4899{
4900 AudioBufferProvider::Buffer buffer;
4901 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004902 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004903
Eric Laurent44d98482010-09-30 16:12:31 -07004904 nsecs_t lastWarning = 0;
4905
Eric Laurentfeb0db62011-07-22 09:04:31 -07004906 acquireWakeLock();
4907
Mathias Agopian65ab4712010-07-14 17:59:35 -07004908 // start recording
4909 while (!exitPending()) {
4910
4911 processConfigEvents();
4912
4913 { // scope for mLock
4914 Mutex::Autolock _l(mLock);
4915 checkForNewParameters_l();
4916 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4917 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004918 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004919 mStandby = true;
4920 }
4921
4922 if (exitPending()) break;
4923
Eric Laurentfeb0db62011-07-22 09:04:31 -07004924 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004925 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004926 // go to sleep
4927 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004928 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004929 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004930 continue;
4931 }
4932 if (mActiveTrack != 0) {
4933 if (mActiveTrack->mState == TrackBase::PAUSING) {
4934 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004935 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004936 mStandby = true;
4937 }
4938 mActiveTrack.clear();
4939 mStartStopCond.broadcast();
4940 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4941 if (mReqChannelCount != mActiveTrack->channelCount()) {
4942 mActiveTrack.clear();
4943 mStartStopCond.broadcast();
4944 } else if (mBytesRead != 0) {
4945 // record start succeeds only if first read from audio input
4946 // succeeds
4947 if (mBytesRead > 0) {
4948 mActiveTrack->mState = TrackBase::ACTIVE;
4949 } else {
4950 mActiveTrack.clear();
4951 }
4952 mStartStopCond.broadcast();
4953 }
4954 mStandby = false;
4955 }
4956 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004957 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004958 }
4959
4960 if (mActiveTrack != 0) {
4961 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4962 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004963 unlockEffectChains(effectChains);
4964 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004965 continue;
4966 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004967 for (size_t i = 0; i < effectChains.size(); i ++) {
4968 effectChains[i]->process_l();
4969 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004970
Mathias Agopian65ab4712010-07-14 17:59:35 -07004971 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004972 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004973 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004974 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004975 // no resampling
4976 while (framesOut) {
4977 size_t framesIn = mFrameCount - mRsmpInIndex;
4978 if (framesIn) {
4979 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4980 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4981 if (framesIn > framesOut)
4982 framesIn = framesOut;
4983 mRsmpInIndex += framesIn;
4984 framesOut -= framesIn;
4985 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004986 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004987 memcpy(dst, src, framesIn * mFrameSize);
4988 } else {
4989 int16_t *src16 = (int16_t *)src;
4990 int16_t *dst16 = (int16_t *)dst;
4991 if (mChannelCount == 1) {
4992 while (framesIn--) {
4993 *dst16++ = *src16;
4994 *dst16++ = *src16++;
4995 }
4996 } else {
4997 while (framesIn--) {
4998 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4999 src16 += 2;
5000 }
5001 }
5002 }
5003 }
5004 if (framesOut && mFrameCount == mRsmpInIndex) {
5005 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005006 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005007 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005008 framesOut = 0;
5009 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07005010 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005011 mRsmpInIndex = 0;
5012 }
5013 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005014 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005015 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5016 // Force input into standby so that it tries to
5017 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005018 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005019 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005020 }
5021 mRsmpInIndex = mFrameCount;
5022 framesOut = 0;
5023 buffer.frameCount = 0;
5024 }
5025 }
5026 }
5027 } else {
5028 // resampling
5029
5030 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
5031 // alter output frame count as if we were expecting stereo samples
5032 if (mChannelCount == 1 && mReqChannelCount == 1) {
5033 framesOut >>= 1;
5034 }
5035 mResampler->resample(mRsmpOutBuffer, framesOut, this);
5036 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
5037 // are 32 bit aligned which should be always true.
5038 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005039 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005040 // the resampler always outputs stereo samples: do post stereo to mono conversion
5041 int16_t *src = (int16_t *)mRsmpOutBuffer;
5042 int16_t *dst = buffer.i16;
5043 while (framesOut--) {
5044 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
5045 src += 2;
5046 }
5047 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005048 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005049 }
5050
5051 }
Eric Laurenta011e352012-03-29 15:51:43 -07005052 if (mFramestoDrop == 0) {
5053 mActiveTrack->releaseBuffer(&buffer);
5054 } else {
5055 if (mFramestoDrop > 0) {
5056 mFramestoDrop -= buffer.frameCount;
5057 if (mFramestoDrop < 0) {
5058 mFramestoDrop = 0;
5059 }
5060 }
5061 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005062 mActiveTrack->overflow();
5063 }
5064 // client isn't retrieving buffers fast enough
5065 else {
Eric Laurent44d98482010-09-30 16:12:31 -07005066 if (!mActiveTrack->setOverflow()) {
5067 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08005068 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005069 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07005070 lastWarning = now;
5071 }
5072 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005073 // Release the processor for a while before asking for a new buffer.
5074 // This will give the application more chance to read from the buffer and
5075 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005076 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005077 }
5078 }
Eric Laurentec437d82011-07-26 20:54:46 -07005079 // enable changes in effect chain
5080 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005081 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005082 }
5083
5084 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005085 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005086 }
5087 mActiveTrack.clear();
5088
5089 mStartStopCond.broadcast();
5090
Eric Laurentfeb0db62011-07-22 09:04:31 -07005091 releaseWakeLock();
5092
Steve Block3856b092011-10-20 11:56:00 +01005093 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005094 return false;
5095}
5096
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005097
5098sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5099 const sp<AudioFlinger::Client>& client,
5100 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005101 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005102 int channelMask,
5103 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005104 int sessionId,
5105 status_t *status)
5106{
5107 sp<RecordTrack> track;
5108 status_t lStatus;
5109
5110 lStatus = initCheck();
5111 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005112 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005113 goto Exit;
5114 }
5115
5116 { // scope for mLock
5117 Mutex::Autolock _l(mLock);
5118
5119 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005120 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005121
Glenn Kasten7378ca52012-01-20 13:44:40 -08005122 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005123 lStatus = NO_MEMORY;
5124 goto Exit;
5125 }
5126
5127 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005128 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5129 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005130 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005131 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5132 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005133 }
5134 lStatus = NO_ERROR;
5135
5136Exit:
5137 if (status) {
5138 *status = lStatus;
5139 }
5140 return track;
5141}
5142
Eric Laurenta011e352012-03-29 15:51:43 -07005143status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5144 pid_t tid, AudioSystem::sync_event_t event,
5145 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005146{
Eric Laurenta011e352012-03-29 15:51:43 -07005147 ALOGV("RecordThread::start tid=%d, event %d, triggerSession %d", tid, event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005148 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005149 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07005150
5151 if (event == AudioSystem::SYNC_EVENT_NONE) {
5152 mSyncStartEvent.clear();
5153 mFramestoDrop = 0;
5154 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
5155 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
5156 triggerSession,
5157 recordTrack->sessionId(),
5158 syncStartEventCallback,
5159 this);
5160 mFramestoDrop = -1;
5161 }
5162
Mathias Agopian65ab4712010-07-14 17:59:35 -07005163 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005164 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005165 if (mActiveTrack != 0) {
5166 if (recordTrack != mActiveTrack.get()) {
5167 status = -EBUSY;
5168 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5169 mActiveTrack->mState = TrackBase::ACTIVE;
5170 }
5171 return status;
5172 }
5173
5174 recordTrack->mState = TrackBase::IDLE;
5175 mActiveTrack = recordTrack;
5176 mLock.unlock();
5177 status_t status = AudioSystem::startInput(mId);
5178 mLock.lock();
5179 if (status != NO_ERROR) {
5180 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07005181 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005182 return status;
5183 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005184 mRsmpInIndex = mFrameCount;
5185 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005186 if (mResampler != NULL) {
5187 mResampler->reset();
5188 }
5189 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005190 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005191 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005192 mWaitWorkCV.signal();
5193 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005194 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005195 mActiveTrack.clear();
5196 status = INVALID_OPERATION;
5197 goto startError;
5198 }
5199 mStartStopCond.wait(mLock);
5200 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005201 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005202 status = BAD_VALUE;
5203 goto startError;
5204 }
Steve Block3856b092011-10-20 11:56:00 +01005205 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005206 return status;
5207 }
5208startError:
5209 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07005210 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005211 return status;
5212}
5213
Eric Laurenta011e352012-03-29 15:51:43 -07005214void AudioFlinger::RecordThread::clearSyncStartEvent()
5215{
5216 if (mSyncStartEvent != 0) {
5217 mSyncStartEvent->cancel();
5218 }
5219 mSyncStartEvent.clear();
5220}
5221
5222void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5223{
5224 sp<SyncEvent> strongEvent = event.promote();
5225
5226 if (strongEvent != 0) {
5227 RecordThread *me = (RecordThread *)strongEvent->cookie();
5228 me->handleSyncStartEvent(strongEvent);
5229 }
5230}
5231
5232void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
5233{
5234 ALOGV("handleSyncStartEvent() mActiveTrack %p session %d event->listenerSession() %d",
5235 mActiveTrack.get(),
5236 mActiveTrack.get() ? mActiveTrack->sessionId() : 0,
5237 event->listenerSession());
5238
5239 if (mActiveTrack != 0 &&
5240 event == mSyncStartEvent) {
5241 // TODO: use actual buffer filling status instead of 2 buffers when info is available
5242 // from audio HAL
5243 mFramestoDrop = mFrameCount * 2;
5244 mSyncStartEvent.clear();
5245 }
5246}
5247
Mathias Agopian65ab4712010-07-14 17:59:35 -07005248void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005249 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005250 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005251 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005252 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005253 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5254 mActiveTrack->mState = TrackBase::PAUSING;
5255 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005256 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005257 return;
5258 }
5259 mStartStopCond.wait(mLock);
5260 // if we have been restarted, recordTrack == mActiveTrack.get() here
5261 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5262 mLock.unlock();
5263 AudioSystem::stopInput(mId);
5264 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005265 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005266 }
5267 }
5268 }
5269}
5270
Eric Laurenta011e352012-03-29 15:51:43 -07005271bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
5272{
5273 return false;
5274}
5275
5276status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
5277{
5278 if (!isValidSyncEvent(event)) {
5279 return BAD_VALUE;
5280 }
5281
5282 Mutex::Autolock _l(mLock);
5283
5284 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
5285 mTrack->setSyncEvent(event);
5286 return NO_ERROR;
5287 }
5288 return NAME_NOT_FOUND;
5289}
5290
Mathias Agopian65ab4712010-07-14 17:59:35 -07005291status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5292{
5293 const size_t SIZE = 256;
5294 char buffer[SIZE];
5295 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005296
5297 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5298 result.append(buffer);
5299
5300 if (mActiveTrack != 0) {
5301 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005302 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005303 mActiveTrack->dump(buffer, SIZE);
5304 result.append(buffer);
5305
5306 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5307 result.append(buffer);
5308 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5309 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005310 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005311 result.append(buffer);
5312 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5313 result.append(buffer);
5314 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5315 result.append(buffer);
5316
5317
5318 } else {
5319 result.append("No record client\n");
5320 }
5321 write(fd, result.string(), result.size());
5322
5323 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005324 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005325
5326 return NO_ERROR;
5327}
5328
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005329// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005330status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005331{
5332 size_t framesReq = buffer->frameCount;
5333 size_t framesReady = mFrameCount - mRsmpInIndex;
5334 int channelCount;
5335
5336 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005337 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005338 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005339 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005340 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5341 // Force input into standby so that it tries to
5342 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005343 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005344 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005345 }
Glenn Kastene0feee32011-12-13 11:53:26 -08005346 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005347 buffer->frameCount = 0;
5348 return NOT_ENOUGH_DATA;
5349 }
5350 mRsmpInIndex = 0;
5351 framesReady = mFrameCount;
5352 }
5353
5354 if (framesReq > framesReady) {
5355 framesReq = framesReady;
5356 }
5357
5358 if (mChannelCount == 1 && mReqChannelCount == 2) {
5359 channelCount = 1;
5360 } else {
5361 channelCount = 2;
5362 }
5363 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5364 buffer->frameCount = framesReq;
5365 return NO_ERROR;
5366}
5367
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005368// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07005369void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5370{
5371 mRsmpInIndex += buffer->frameCount;
5372 buffer->frameCount = 0;
5373}
5374
5375bool AudioFlinger::RecordThread::checkForNewParameters_l()
5376{
5377 bool reconfig = false;
5378
5379 while (!mNewParameters.isEmpty()) {
5380 status_t status = NO_ERROR;
5381 String8 keyValuePair = mNewParameters[0];
5382 AudioParameter param = AudioParameter(keyValuePair);
5383 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08005384 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005385 int reqSamplingRate = mReqSampleRate;
5386 int reqChannelCount = mReqChannelCount;
5387
5388 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5389 reqSamplingRate = value;
5390 reconfig = true;
5391 }
5392 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08005393 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005394 reconfig = true;
5395 }
5396 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005397 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005398 reconfig = true;
5399 }
5400 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5401 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08005402 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005403 // if frame count is changed after track creation
5404 if (mActiveTrack != 0) {
5405 status = INVALID_OPERATION;
5406 } else {
5407 reconfig = true;
5408 }
5409 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005410 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5411 // forward device change to effects that have requested to be
5412 // aware of attached audio device.
5413 for (size_t i = 0; i < mEffectChains.size(); i++) {
5414 mEffectChains[i]->setDevice_l(value);
5415 }
5416 // store input device and output device but do not forward output device to audio HAL.
5417 // Note that status is ignored by the caller for output device
5418 // (see AudioFlinger::setParameters()
5419 if (value & AUDIO_DEVICE_OUT_ALL) {
5420 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5421 status = BAD_VALUE;
5422 } else {
5423 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07005424 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5425 if (mTrack != NULL) {
5426 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005427 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005428 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5429 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5430 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005431 }
5432 mDevice |= (uint32_t)value;
5433 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005434 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005435 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005436 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005437 mInput->stream->common.standby(&mInput->stream->common);
5438 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5439 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005440 }
5441 if (reconfig) {
5442 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005443 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005444 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005445 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08005446 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
5447 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005448 status = NO_ERROR;
5449 }
5450 if (status == NO_ERROR) {
5451 readInputParameters();
5452 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5453 }
5454 }
5455 }
5456
5457 mNewParameters.removeAt(0);
5458
5459 mParamStatus = status;
5460 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07005461 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5462 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08005463 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005464 }
5465 return reconfig;
5466}
5467
5468String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5469{
Dima Zavinfce7a472011-04-19 22:30:36 -07005470 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005471 String8 out_s8 = String8();
5472
5473 Mutex::Autolock _l(mLock);
5474 if (initCheck() != NO_ERROR) {
5475 return out_s8;
5476 }
Dima Zavinfce7a472011-04-19 22:30:36 -07005477
Dima Zavin799a70e2011-04-18 16:57:27 -07005478 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07005479 out_s8 = String8(s);
5480 free(s);
5481 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005482}
5483
5484void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5485 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08005486 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005487
5488 switch (event) {
5489 case AudioSystem::INPUT_OPENED:
5490 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005491 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005492 desc.samplingRate = mSampleRate;
5493 desc.format = mFormat;
5494 desc.frameCount = mFrameCount;
5495 desc.latency = 0;
5496 param2 = &desc;
5497 break;
5498
5499 case AudioSystem::INPUT_CLOSED:
5500 default:
5501 break;
5502 }
5503 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5504}
5505
5506void AudioFlinger::RecordThread::readInputParameters()
5507{
Glenn Kastene9dd0172012-01-27 18:08:45 -08005508 delete mRsmpInBuffer;
5509 // mRsmpInBuffer is always assigned a new[] below
5510 delete mRsmpOutBuffer;
5511 mRsmpOutBuffer = NULL;
5512 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08005513 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005514
Dima Zavin799a70e2011-04-18 16:57:27 -07005515 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005516 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5517 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07005518 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08005519 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07005520 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005521 mFrameCount = mInputBytes / mFrameSize;
5522 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5523
Glenn Kasten53d76db2012-03-08 12:32:47 -08005524 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005525 {
5526 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005527 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5528 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005529 if (mChannelCount == 1 && mReqChannelCount == 2) {
5530 channelCount = 1;
5531 } else {
5532 channelCount = 2;
5533 }
5534 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5535 mResampler->setSampleRate(mSampleRate);
5536 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5537 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5538
5539 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5540 if (mChannelCount == 1 && mReqChannelCount == 1) {
5541 mFrameCount >>= 1;
5542 }
5543
5544 }
5545 mRsmpInIndex = mFrameCount;
5546}
5547
5548unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5549{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005550 Mutex::Autolock _l(mLock);
5551 if (initCheck() != NO_ERROR) {
5552 return 0;
5553 }
5554
Dima Zavin799a70e2011-04-18 16:57:27 -07005555 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005556}
5557
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005558uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5559{
5560 Mutex::Autolock _l(mLock);
5561 uint32_t result = 0;
5562 if (getEffectChain_l(sessionId) != 0) {
5563 result = EFFECT_SESSION;
5564 }
5565
5566 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5567 result |= TRACK_SESSION;
5568 }
5569
5570 return result;
5571}
5572
Eric Laurent59bd0da2011-08-01 09:52:20 -07005573AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5574{
5575 Mutex::Autolock _l(mLock);
5576 return mTrack;
5577}
5578
Glenn Kastenaed850d2012-01-26 09:46:34 -08005579AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005580{
5581 Mutex::Autolock _l(mLock);
5582 return mInput;
5583}
5584
5585AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5586{
5587 Mutex::Autolock _l(mLock);
5588 AudioStreamIn *input = mInput;
5589 mInput = NULL;
5590 return input;
5591}
5592
5593// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08005594audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005595{
5596 if (mInput == NULL) {
5597 return NULL;
5598 }
5599 return &mInput->stream->common;
5600}
5601
5602
Mathias Agopian65ab4712010-07-14 17:59:35 -07005603// ----------------------------------------------------------------------------
5604
Eric Laurenta4c5a552012-03-29 10:12:40 -07005605audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
5606{
5607 if (!settingsAllowed()) {
5608 return 0;
5609 }
5610 Mutex::Autolock _l(mLock);
5611 return loadHwModule_l(name);
5612}
5613
5614// loadHwModule_l() must be called with AudioFlinger::mLock held
5615audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
5616{
5617 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
5618 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
5619 ALOGW("loadHwModule() module %s already loaded", name);
5620 return mAudioHwDevs.keyAt(i);
5621 }
5622 }
5623
5624 const hw_module_t *mod;
5625 audio_hw_device_t *dev;
5626
5627 int rc = load_audio_interface(name, &mod, &dev);
5628 if (rc) {
5629 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
5630 return 0;
5631 }
5632
5633 mHardwareStatus = AUDIO_HW_INIT;
5634 rc = dev->init_check(dev);
5635 mHardwareStatus = AUDIO_HW_IDLE;
5636 if (rc) {
5637 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
5638 return 0;
5639 }
5640
5641 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
5642 (NULL != dev->set_master_volume)) {
5643 AutoMutex lock(mHardwareLock);
5644 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
5645 dev->set_master_volume(dev, mMasterVolume);
5646 mHardwareStatus = AUDIO_HW_IDLE;
5647 }
5648
5649 audio_module_handle_t handle = nextUniqueId();
5650 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
5651
5652 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
5653 name, mod->name, mod->id, handle);
5654
5655 return handle;
5656
5657}
5658
5659audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
5660 audio_devices_t *pDevices,
5661 uint32_t *pSamplingRate,
5662 audio_format_t *pFormat,
5663 audio_channel_mask_t *pChannelMask,
5664 uint32_t *pLatencyMs,
5665 audio_policy_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005666{
5667 status_t status;
5668 PlaybackThread *thread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005669 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005670 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Eric Laurenta4c5a552012-03-29 10:12:40 -07005671 audio_channel_mask_t channelMask = pChannelMask ? *pChannelMask : 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005672 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07005673 audio_stream_out_t *outStream;
5674 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005675
Eric Laurenta4c5a552012-03-29 10:12:40 -07005676 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
5677 module,
5678 pDevices ? *pDevices : 0,
5679 samplingRate,
5680 format,
5681 channelMask,
5682 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005683
5684 if (pDevices == NULL || *pDevices == 0) {
5685 return 0;
5686 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005687
Mathias Agopian65ab4712010-07-14 17:59:35 -07005688 Mutex::Autolock _l(mLock);
5689
Eric Laurenta4c5a552012-03-29 10:12:40 -07005690 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07005691 if (outHwDev == NULL)
5692 return 0;
5693
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005694 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Glenn Kasten58f30212012-01-12 12:27:51 -08005695 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Eric Laurenta4c5a552012-03-29 10:12:40 -07005696 &channelMask, &samplingRate, &outStream);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005697 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01005698 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005699 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005700 samplingRate,
5701 format,
Eric Laurenta4c5a552012-03-29 10:12:40 -07005702 channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005703 status);
5704
Dima Zavin799a70e2011-04-18 16:57:27 -07005705 if (outStream != NULL) {
5706 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005707 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07005708
Dima Zavinfce7a472011-04-19 22:30:36 -07005709 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5710 (format != AUDIO_FORMAT_PCM_16_BIT) ||
Eric Laurenta4c5a552012-03-29 10:12:40 -07005711 (channelMask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005712 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005713 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005714 } else {
5715 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005716 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005717 }
5718 mPlaybackThreads.add(id, thread);
5719
Glenn Kastena0d68332012-01-27 16:47:15 -08005720 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5721 if (pFormat != NULL) *pFormat = format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07005722 if (pChannelMask != NULL) *pChannelMask = channelMask;
Glenn Kastena0d68332012-01-27 16:47:15 -08005723 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005724
5725 // notify client processes of the new output creation
5726 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07005727
5728 // the first primary output opened designates the primary hw device
5729 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_POLICY_OUTPUT_FLAG_PRIMARY)) {
5730 ALOGI("Using module %d has the primary audio interface", module);
5731 mPrimaryHardwareDev = outHwDev;
5732
5733 AutoMutex lock(mHardwareLock);
5734 mHardwareStatus = AUDIO_HW_SET_MODE;
5735 outHwDev->set_mode(outHwDev, mMode);
5736
5737 // Determine the level of master volume support the primary audio HAL has,
5738 // and set the initial master volume at the same time.
5739 float initialVolume = 1.0;
5740 mMasterVolumeSupportLvl = MVS_NONE;
5741
5742 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
5743 if ((NULL != outHwDev->get_master_volume) &&
5744 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
5745 mMasterVolumeSupportLvl = MVS_FULL;
5746 } else {
5747 mMasterVolumeSupportLvl = MVS_SETONLY;
5748 initialVolume = 1.0;
5749 }
5750
5751 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
5752 if ((NULL == outHwDev->set_master_volume) ||
5753 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
5754 mMasterVolumeSupportLvl = MVS_NONE;
5755 }
5756 // now that we have a primary device, initialize master volume on other devices
5757 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
5758 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
5759
5760 if ((dev != mPrimaryHardwareDev) &&
5761 (NULL != dev->set_master_volume)) {
5762 dev->set_master_volume(dev, initialVolume);
5763 }
5764 }
5765 mHardwareStatus = AUDIO_HW_IDLE;
5766 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
5767 ? initialVolume
5768 : 1.0;
5769 mMasterVolume = initialVolume;
5770 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005771 return id;
5772 }
5773
5774 return 0;
5775}
5776
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005777audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
5778 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005779{
5780 Mutex::Autolock _l(mLock);
5781 MixerThread *thread1 = checkMixerThread_l(output1);
5782 MixerThread *thread2 = checkMixerThread_l(output2);
5783
5784 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005785 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005786 return 0;
5787 }
5788
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005789 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005790 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5791 thread->addOutputTrack(thread2);
5792 mPlaybackThreads.add(id, thread);
5793 // notify client processes of the new output creation
5794 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5795 return id;
5796}
5797
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005798status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005799{
5800 // keep strong reference on the playback thread so that
5801 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005802 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005803 {
5804 Mutex::Autolock _l(mLock);
5805 thread = checkPlaybackThread_l(output);
5806 if (thread == NULL) {
5807 return BAD_VALUE;
5808 }
5809
Steve Block3856b092011-10-20 11:56:00 +01005810 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005811
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005812 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005813 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005814 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005815 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5816 dupThread->removeOutputTrack((MixerThread *)thread.get());
5817 }
5818 }
5819 }
Glenn Kastena1117922012-01-26 10:53:32 -08005820 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005821 mPlaybackThreads.removeItem(output);
5822 }
5823 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005824 // The thread entity (active unit of execution) is no longer running here,
5825 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005826
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005827 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005828 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005829 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005830 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005831 out->hwDev->close_output_stream(out->hwDev, out->stream);
5832 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005833 }
5834 return NO_ERROR;
5835}
5836
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005837status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005838{
5839 Mutex::Autolock _l(mLock);
5840 PlaybackThread *thread = checkPlaybackThread_l(output);
5841
5842 if (thread == NULL) {
5843 return BAD_VALUE;
5844 }
5845
Steve Block3856b092011-10-20 11:56:00 +01005846 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005847 thread->suspend();
5848
5849 return NO_ERROR;
5850}
5851
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005852status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005853{
5854 Mutex::Autolock _l(mLock);
5855 PlaybackThread *thread = checkPlaybackThread_l(output);
5856
5857 if (thread == NULL) {
5858 return BAD_VALUE;
5859 }
5860
Steve Block3856b092011-10-20 11:56:00 +01005861 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005862
5863 thread->restore();
5864
5865 return NO_ERROR;
5866}
5867
Eric Laurenta4c5a552012-03-29 10:12:40 -07005868audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
5869 audio_devices_t *pDevices,
5870 uint32_t *pSamplingRate,
5871 audio_format_t *pFormat,
5872 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005873{
5874 status_t status;
5875 RecordThread *thread = NULL;
5876 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005877 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Eric Laurenta4c5a552012-03-29 10:12:40 -07005878 audio_channel_mask_t channelMask = pChannelMask ? *pChannelMask : 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005879 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005880 audio_format_t reqFormat = format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07005881 audio_channel_mask_t reqChannels = channelMask;
Dima Zavin799a70e2011-04-18 16:57:27 -07005882 audio_stream_in_t *inStream;
5883 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005884
5885 if (pDevices == NULL || *pDevices == 0) {
5886 return 0;
5887 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005888
Mathias Agopian65ab4712010-07-14 17:59:35 -07005889 Mutex::Autolock _l(mLock);
5890
Eric Laurenta4c5a552012-03-29 10:12:40 -07005891 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07005892 if (inHwDev == NULL)
5893 return 0;
5894
Glenn Kasten58f30212012-01-12 12:27:51 -08005895 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Eric Laurenta4c5a552012-03-29 10:12:40 -07005896 &channelMask, &samplingRate,
5897 (audio_in_acoustics_t)0,
Dima Zavin799a70e2011-04-18 16:57:27 -07005898 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07005899 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005900 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005901 samplingRate,
5902 format,
Eric Laurenta4c5a552012-03-29 10:12:40 -07005903 channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005904 status);
5905
5906 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5907 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5908 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005909 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005910 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005911 (samplingRate <= 2 * reqSamplingRate) &&
Eric Laurenta4c5a552012-03-29 10:12:40 -07005912 (popcount(channelMask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01005913 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005914 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Eric Laurenta4c5a552012-03-29 10:12:40 -07005915 &channelMask, &samplingRate,
5916 (audio_in_acoustics_t)0,
Dima Zavin799a70e2011-04-18 16:57:27 -07005917 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005918 }
5919
Dima Zavin799a70e2011-04-18 16:57:27 -07005920 if (inStream != NULL) {
5921 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5922
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005923 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005924 // Start record thread
5925 // RecorThread require both input and output device indication to forward to audio
5926 // pre processing modules
5927 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5928 thread = new RecordThread(this,
5929 input,
5930 reqSamplingRate,
5931 reqChannels,
5932 id,
5933 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005934 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005935 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005936 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5937 if (pFormat != NULL) *pFormat = format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07005938 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005939
Dima Zavin799a70e2011-04-18 16:57:27 -07005940 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005941
5942 // notify client processes of the new input creation
5943 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5944 return id;
5945 }
5946
5947 return 0;
5948}
5949
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005950status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005951{
5952 // keep strong reference on the record thread so that
5953 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005954 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005955 {
5956 Mutex::Autolock _l(mLock);
5957 thread = checkRecordThread_l(input);
5958 if (thread == NULL) {
5959 return BAD_VALUE;
5960 }
5961
Steve Block3856b092011-10-20 11:56:00 +01005962 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08005963 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005964 mRecordThreads.removeItem(input);
5965 }
5966 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005967 // The thread entity (active unit of execution) is no longer running here,
5968 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005969
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005970 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005971 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005972 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005973 in->hwDev->close_input_stream(in->hwDev, in->stream);
5974 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005975
5976 return NO_ERROR;
5977}
5978
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005979status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005980{
5981 Mutex::Autolock _l(mLock);
5982 MixerThread *dstThread = checkMixerThread_l(output);
5983 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005984 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005985 return BAD_VALUE;
5986 }
5987
Steve Block3856b092011-10-20 11:56:00 +01005988 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005989 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5990
5991 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5992 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08005993 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005994 MixerThread *srcThread = (MixerThread *)thread;
5995 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005996 }
Eric Laurentde070132010-07-13 04:45:46 -07005997 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005998
5999 return NO_ERROR;
6000}
6001
6002
6003int AudioFlinger::newAudioSessionId()
6004{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006005 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006006}
6007
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006008void AudioFlinger::acquireAudioSessionId(int audioSession)
6009{
6010 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006011 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006012 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006013 size_t num = mAudioSessionRefs.size();
6014 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006015 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006016 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6017 ref->mCnt++;
6018 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006019 return;
6020 }
6021 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006022 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
6023 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006024}
6025
6026void AudioFlinger::releaseAudioSessionId(int audioSession)
6027{
6028 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006029 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006030 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006031 size_t num = mAudioSessionRefs.size();
6032 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006033 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006034 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6035 ref->mCnt--;
6036 ALOGV(" decremented refcount to %d", ref->mCnt);
6037 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006038 mAudioSessionRefs.removeAt(i);
6039 delete ref;
6040 purgeStaleEffects_l();
6041 }
6042 return;
6043 }
6044 }
Steve Block5ff1dd52012-01-05 23:22:43 +00006045 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006046}
6047
6048void AudioFlinger::purgeStaleEffects_l() {
6049
Steve Block3856b092011-10-20 11:56:00 +01006050 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006051
6052 Vector< sp<EffectChain> > chains;
6053
6054 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6055 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
6056 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6057 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07006058 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
6059 chains.push(ec);
6060 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006061 }
6062 }
6063 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6064 sp<RecordThread> t = mRecordThreads.valueAt(i);
6065 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6066 sp<EffectChain> ec = t->mEffectChains[j];
6067 chains.push(ec);
6068 }
6069 }
6070
6071 for (size_t i = 0; i < chains.size(); i++) {
6072 sp<EffectChain> ec = chains[i];
6073 int sessionid = ec->sessionId();
6074 sp<ThreadBase> t = ec->mThread.promote();
6075 if (t == 0) {
6076 continue;
6077 }
6078 size_t numsessionrefs = mAudioSessionRefs.size();
6079 bool found = false;
6080 for (size_t k = 0; k < numsessionrefs; k++) {
6081 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006082 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01006083 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006084 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006085 found = true;
6086 break;
6087 }
6088 }
6089 if (!found) {
6090 // remove all effects from the chain
6091 while (ec->mEffects.size()) {
6092 sp<EffectModule> effect = ec->mEffects[0];
6093 effect->unPin();
6094 Mutex::Autolock _l (t->mLock);
6095 t->removeEffect_l(effect);
6096 for (size_t j = 0; j < effect->mHandles.size(); j++) {
6097 sp<EffectHandle> handle = effect->mHandles[j].promote();
6098 if (handle != 0) {
6099 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07006100 if (handle->mHasControl && handle->mEnabled) {
6101 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
6102 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006103 }
6104 }
6105 AudioSystem::unregisterEffect(effect->id());
6106 }
6107 }
6108 }
6109 return;
6110}
6111
Mathias Agopian65ab4712010-07-14 17:59:35 -07006112// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006113AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006114{
Glenn Kastena1117922012-01-26 10:53:32 -08006115 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006116}
6117
6118// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006119AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006120{
6121 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08006122 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006123}
6124
6125// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006126AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006127{
Glenn Kastena1117922012-01-26 10:53:32 -08006128 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006129}
6130
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006131uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07006132{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006133 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006134}
6135
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006136AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006137{
6138 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6139 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006140 AudioStreamOut *output = thread->getOutput();
6141 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006142 return thread;
6143 }
6144 }
6145 return NULL;
6146}
6147
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006148uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006149{
6150 PlaybackThread *thread = primaryPlaybackThread_l();
6151
6152 if (thread == NULL) {
6153 return 0;
6154 }
6155
6156 return thread->device();
6157}
6158
Eric Laurenta011e352012-03-29 15:51:43 -07006159sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
6160 int triggerSession,
6161 int listenerSession,
6162 sync_event_callback_t callBack,
6163 void *cookie)
6164{
6165 Mutex::Autolock _l(mLock);
6166
6167 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
6168 status_t playStatus = NAME_NOT_FOUND;
6169 status_t recStatus = NAME_NOT_FOUND;
6170 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6171 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
6172 if (playStatus == NO_ERROR) {
6173 return event;
6174 }
6175 }
6176 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6177 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
6178 if (recStatus == NO_ERROR) {
6179 return event;
6180 }
6181 }
6182 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
6183 mPendingSyncEvents.add(event);
6184 } else {
6185 ALOGV("createSyncEvent() invalid event %d", event->type());
6186 event.clear();
6187 }
6188 return event;
6189}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006190
Mathias Agopian65ab4712010-07-14 17:59:35 -07006191// ----------------------------------------------------------------------------
6192// Effect management
6193// ----------------------------------------------------------------------------
6194
6195
Glenn Kastenf587ba52012-01-26 16:25:10 -08006196status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006197{
6198 Mutex::Autolock _l(mLock);
6199 return EffectQueryNumberEffects(numEffects);
6200}
6201
Glenn Kastenf587ba52012-01-26 16:25:10 -08006202status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006203{
6204 Mutex::Autolock _l(mLock);
6205 return EffectQueryEffect(index, descriptor);
6206}
6207
Glenn Kasten5e92a782012-01-30 07:40:52 -08006208status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08006209 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006210{
6211 Mutex::Autolock _l(mLock);
6212 return EffectGetDescriptor(pUuid, descriptor);
6213}
6214
6215
Mathias Agopian65ab4712010-07-14 17:59:35 -07006216sp<IEffect> AudioFlinger::createEffect(pid_t pid,
6217 effect_descriptor_t *pDesc,
6218 const sp<IEffectClient>& effectClient,
6219 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006220 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006221 int sessionId,
6222 status_t *status,
6223 int *id,
6224 int *enabled)
6225{
6226 status_t lStatus = NO_ERROR;
6227 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006228 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006229
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006230 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006231 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006232
6233 if (pDesc == NULL) {
6234 lStatus = BAD_VALUE;
6235 goto Exit;
6236 }
6237
Eric Laurent84e9a102010-09-23 16:10:16 -07006238 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006239 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006240 lStatus = PERMISSION_DENIED;
6241 goto Exit;
6242 }
6243
Dima Zavinfce7a472011-04-19 22:30:36 -07006244 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07006245 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08006246 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006247 lStatus = PERMISSION_DENIED;
6248 goto Exit;
6249 }
6250
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006251 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006252 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006253 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07006254 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07006255 lStatus = BAD_VALUE;
6256 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07006257 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006258 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006259 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07006260 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006261 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07006262 }
6263 }
6264
Mathias Agopian65ab4712010-07-14 17:59:35 -07006265 {
6266 Mutex::Autolock _l(mLock);
6267
Mathias Agopian65ab4712010-07-14 17:59:35 -07006268
6269 if (!EffectIsNullUuid(&pDesc->uuid)) {
6270 // if uuid is specified, request effect descriptor
6271 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
6272 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006273 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006274 goto Exit;
6275 }
6276 } else {
6277 // if uuid is not specified, look for an available implementation
6278 // of the required type in effect factory
6279 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006280 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006281 lStatus = BAD_VALUE;
6282 goto Exit;
6283 }
6284 uint32_t numEffects = 0;
6285 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006286 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07006287 bool found = false;
6288
6289 lStatus = EffectQueryNumberEffects(&numEffects);
6290 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006291 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006292 goto Exit;
6293 }
6294 for (uint32_t i = 0; i < numEffects; i++) {
6295 lStatus = EffectQueryEffect(i, &desc);
6296 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006297 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006298 continue;
6299 }
6300 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
6301 // If matching type found save effect descriptor. If the session is
6302 // 0 and the effect is not auxiliary, continue enumeration in case
6303 // an auxiliary version of this effect type is available
6304 found = true;
6305 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07006306 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006307 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6308 break;
6309 }
6310 }
6311 }
6312 if (!found) {
6313 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00006314 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006315 goto Exit;
6316 }
6317 // For same effect type, chose auxiliary version over insert version if
6318 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07006319 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006320 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
6321 memcpy(&desc, &d, sizeof(effect_descriptor_t));
6322 }
6323 }
6324
6325 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07006326 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006327 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6328 lStatus = INVALID_OPERATION;
6329 goto Exit;
6330 }
6331
Eric Laurent59255e42011-07-27 19:49:51 -07006332 // check recording permission for visualizer
6333 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
6334 !recordingAllowed()) {
6335 lStatus = PERMISSION_DENIED;
6336 goto Exit;
6337 }
6338
Mathias Agopian65ab4712010-07-14 17:59:35 -07006339 // return effect descriptor
6340 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
6341
6342 // If output is not specified try to find a matching audio session ID in one of the
6343 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07006344 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
6345 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006346 // Note: io is never 0 when creating an effect on an input
6347 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006348 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07006349 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6350 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006351 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07006352 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07006353 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006354 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006355 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006356 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6357 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6358 io = mRecordThreads.keyAt(i);
6359 break;
6360 }
6361 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006362 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006363 // If no output thread contains the requested session ID, default to
6364 // first output. The effect chain will be moved to the correct output
6365 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006366 if (io == 0 && mPlaybackThreads.size()) {
6367 io = mPlaybackThreads.keyAt(0);
6368 }
Steve Block3856b092011-10-20 11:56:00 +01006369 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006370 }
6371 ThreadBase *thread = checkRecordThread_l(io);
6372 if (thread == NULL) {
6373 thread = checkPlaybackThread_l(io);
6374 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00006375 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006376 lStatus = BAD_VALUE;
6377 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07006378 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006379 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006380
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006381 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006382
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006383 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07006384 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6385 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006386 if (handle != 0 && id != NULL) {
6387 *id = handle->id();
6388 }
6389 }
6390
6391Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006392 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006393 *status = lStatus;
6394 }
6395 return handle;
6396}
6397
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006398status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
6399 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07006400{
Steve Block3856b092011-10-20 11:56:00 +01006401 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07006402 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006403 Mutex::Autolock _l(mLock);
6404 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006405 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006406 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006407 }
Eric Laurentde070132010-07-13 04:45:46 -07006408 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6409 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006410 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006411 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006412 }
Eric Laurentde070132010-07-13 04:45:46 -07006413 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6414 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006415 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006416 return BAD_VALUE;
6417 }
6418
6419 Mutex::Autolock _dl(dstThread->mLock);
6420 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07006421 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07006422
Mathias Agopian65ab4712010-07-14 17:59:35 -07006423 return NO_ERROR;
6424}
6425
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006426// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07006427status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07006428 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07006429 AudioFlinger::PlaybackThread *dstThread,
6430 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07006431{
Steve Block3856b092011-10-20 11:56:00 +01006432 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006433 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07006434
Eric Laurent59255e42011-07-27 19:49:51 -07006435 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006436 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006437 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006438 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07006439 return INVALID_OPERATION;
6440 }
6441
Eric Laurent39e94f82010-07-28 01:32:47 -07006442 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07006443 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07006444 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07006445 // removed.
6446 srcThread->removeEffectChain_l(chain);
6447
6448 // transfer all effects one by one so that new effect chain is created on new thread with
6449 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006450 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07006451 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006452 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07006453 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6454 while (effect != 0) {
6455 srcThread->removeEffect_l(effect);
6456 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07006457 // removeEffect_l() has stopped the effect if it was active so it must be restarted
6458 if (effect->state() == EffectModule::ACTIVE ||
6459 effect->state() == EffectModule::STOPPING) {
6460 effect->start();
6461 }
Eric Laurent39e94f82010-07-28 01:32:47 -07006462 // if the move request is not received from audio policy manager, the effect must be
6463 // re-registered with the new strategy and output
6464 if (dstChain == 0) {
6465 dstChain = effect->chain().promote();
6466 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006467 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07006468 srcThread->addEffect_l(effect);
6469 return NO_INIT;
6470 }
6471 strategy = dstChain->strategy();
6472 }
6473 if (reRegister) {
6474 AudioSystem::unregisterEffect(effect->id());
6475 AudioSystem::registerEffect(&effect->desc(),
6476 dstOutput,
6477 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07006478 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07006479 effect->id());
6480 }
Eric Laurentde070132010-07-13 04:45:46 -07006481 effect = chain->getEffectFromId_l(0);
6482 }
6483
6484 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006485}
6486
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006487
Mathias Agopian65ab4712010-07-14 17:59:35 -07006488// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006489sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07006490 const sp<AudioFlinger::Client>& client,
6491 const sp<IEffectClient>& effectClient,
6492 int32_t priority,
6493 int sessionId,
6494 effect_descriptor_t *desc,
6495 int *enabled,
6496 status_t *status
6497 )
6498{
6499 sp<EffectModule> effect;
6500 sp<EffectHandle> handle;
6501 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006502 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07006503 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006504 bool effectCreated = false;
6505 bool effectRegistered = false;
6506
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006507 lStatus = initCheck();
6508 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006509 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006510 goto Exit;
6511 }
6512
6513 // Do not allow effects with session ID 0 on direct output or duplicating threads
6514 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07006515 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006516 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07006517 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006518 lStatus = BAD_VALUE;
6519 goto Exit;
6520 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006521 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08006522 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006523 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006524 desc->name, desc->flags, mType);
6525 lStatus = BAD_VALUE;
6526 goto Exit;
6527 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006528
Steve Block3856b092011-10-20 11:56:00 +01006529 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006530
6531 { // scope for mLock
6532 Mutex::Autolock _l(mLock);
6533
6534 // check for existing effect chain with the requested audio session
6535 chain = getEffectChain_l(sessionId);
6536 if (chain == 0) {
6537 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006538 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006539 chain = new EffectChain(this, sessionId);
6540 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07006541 chain->setStrategy(getStrategyForSession_l(sessionId));
6542 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006543 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07006544 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006545 }
6546
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08006547 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006548
6549 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006550 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006551 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07006552 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006553 if (lStatus != NO_ERROR) {
6554 goto Exit;
6555 }
6556 effectRegistered = true;
6557 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07006558 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006559 lStatus = effect->status();
6560 if (lStatus != NO_ERROR) {
6561 goto Exit;
6562 }
Eric Laurentcab11242010-07-15 12:50:15 -07006563 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006564 if (lStatus != NO_ERROR) {
6565 goto Exit;
6566 }
6567 effectCreated = true;
6568
6569 effect->setDevice(mDevice);
6570 effect->setMode(mAudioFlinger->getMode());
6571 }
6572 // create effect handle and connect it to effect module
6573 handle = new EffectHandle(effect, client, effectClient, priority);
6574 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08006575 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006576 *enabled = (int)effect->isEnabled();
6577 }
6578 }
6579
6580Exit:
6581 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07006582 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006583 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07006584 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006585 }
6586 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07006587 AudioSystem::unregisterEffect(effect->id());
6588 }
6589 if (chainCreated) {
6590 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006591 }
6592 handle.clear();
6593 }
6594
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006595 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006596 *status = lStatus;
6597 }
6598 return handle;
6599}
6600
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006601sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6602{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006603 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08006604 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006605}
6606
Eric Laurentde070132010-07-13 04:45:46 -07006607// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6608// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006609status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07006610{
6611 // check for existing effect chain with the requested audio session
6612 int sessionId = effect->sessionId();
6613 sp<EffectChain> chain = getEffectChain_l(sessionId);
6614 bool chainCreated = false;
6615
6616 if (chain == 0) {
6617 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006618 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006619 chain = new EffectChain(this, sessionId);
6620 addEffectChain_l(chain);
6621 chain->setStrategy(getStrategyForSession_l(sessionId));
6622 chainCreated = true;
6623 }
Steve Block3856b092011-10-20 11:56:00 +01006624 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006625
6626 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006627 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07006628 this, effect->desc().name, chain.get());
6629 return BAD_VALUE;
6630 }
6631
6632 status_t status = chain->addEffect_l(effect);
6633 if (status != NO_ERROR) {
6634 if (chainCreated) {
6635 removeEffectChain_l(chain);
6636 }
6637 return status;
6638 }
6639
6640 effect->setDevice(mDevice);
6641 effect->setMode(mAudioFlinger->getMode());
6642 return NO_ERROR;
6643}
6644
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006645void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07006646
Steve Block3856b092011-10-20 11:56:00 +01006647 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006648 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07006649 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6650 detachAuxEffect_l(effect->id());
6651 }
6652
6653 sp<EffectChain> chain = effect->chain().promote();
6654 if (chain != 0) {
6655 // remove effect chain if removing last effect
6656 if (chain->removeEffect_l(effect) == 0) {
6657 removeEffectChain_l(chain);
6658 }
6659 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00006660 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006661 }
6662}
6663
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006664void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006665 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006666{
6667 effectChains = mEffectChains;
6668 for (size_t i = 0; i < mEffectChains.size(); i++) {
6669 mEffectChains[i]->lock();
6670 }
6671}
6672
6673void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006674 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006675{
6676 for (size_t i = 0; i < effectChains.size(); i++) {
6677 effectChains[i]->unlock();
6678 }
6679}
6680
6681sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6682{
6683 Mutex::Autolock _l(mLock);
6684 return getEffectChain_l(sessionId);
6685}
6686
6687sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6688{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006689 size_t size = mEffectChains.size();
6690 for (size_t i = 0; i < size; i++) {
6691 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08006692 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006693 }
6694 }
Glenn Kasten090f0192012-01-30 13:00:02 -08006695 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006696}
6697
Glenn Kastenf78aee72012-01-04 11:00:47 -08006698void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006699{
6700 Mutex::Autolock _l(mLock);
6701 size_t size = mEffectChains.size();
6702 for (size_t i = 0; i < size; i++) {
6703 mEffectChains[i]->setMode_l(mode);
6704 }
6705}
6706
6707void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006708 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08006709 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07006710
Mathias Agopian65ab4712010-07-14 17:59:35 -07006711 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006712 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006713 // delete the effect module if removing last handle on it
6714 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006715 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006716 removeEffect_l(effect);
6717 AudioSystem::unregisterEffect(effect->id());
6718 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006719 }
6720}
6721
6722status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6723{
6724 int session = chain->sessionId();
6725 int16_t *buffer = mMixBuffer;
6726 bool ownsBuffer = false;
6727
Steve Block3856b092011-10-20 11:56:00 +01006728 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006729 if (session > 0) {
6730 // Only one effect chain can be present in direct output thread and it uses
6731 // the mix buffer as input
6732 if (mType != DIRECT) {
6733 size_t numSamples = mFrameCount * mChannelCount;
6734 buffer = new int16_t[numSamples];
6735 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01006736 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006737 ownsBuffer = true;
6738 }
6739
6740 // Attach all tracks with same session ID to this chain.
6741 for (size_t i = 0; i < mTracks.size(); ++i) {
6742 sp<Track> track = mTracks[i];
6743 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006744 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006745 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006746 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006747 }
6748 }
6749
6750 // indicate all active tracks in the chain
6751 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6752 sp<Track> track = mActiveTracks[i].promote();
6753 if (track == 0) continue;
6754 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006755 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07006756 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006757 }
6758 }
6759 }
6760
6761 chain->setInBuffer(buffer, ownsBuffer);
6762 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006763 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006764 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006765 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6766 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006767 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006768 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6769 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006770 // Effect chain for other sessions are inserted at beginning of effect
6771 // chains list to be processed before output mix effects. Relative order between other
6772 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006773 size_t size = mEffectChains.size();
6774 size_t i = 0;
6775 for (i = 0; i < size; i++) {
6776 if (mEffectChains[i]->sessionId() < session) break;
6777 }
6778 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006779 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006780
6781 return NO_ERROR;
6782}
6783
6784size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6785{
6786 int session = chain->sessionId();
6787
Steve Block3856b092011-10-20 11:56:00 +01006788 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006789
6790 for (size_t i = 0; i < mEffectChains.size(); i++) {
6791 if (chain == mEffectChains[i]) {
6792 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006793 // detach all active tracks from the chain
6794 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6795 sp<Track> track = mActiveTracks[i].promote();
6796 if (track == 0) continue;
6797 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006798 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006799 chain.get(), session);
6800 chain->decActiveTrackCnt();
6801 }
6802 }
6803
Mathias Agopian65ab4712010-07-14 17:59:35 -07006804 // detach all tracks with same session ID from this chain
6805 for (size_t i = 0; i < mTracks.size(); ++i) {
6806 sp<Track> track = mTracks[i];
6807 if (session == track->sessionId()) {
6808 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006809 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006810 }
6811 }
Eric Laurentde070132010-07-13 04:45:46 -07006812 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006813 }
6814 }
6815 return mEffectChains.size();
6816}
6817
Eric Laurentde070132010-07-13 04:45:46 -07006818status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6819 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006820{
6821 Mutex::Autolock _l(mLock);
6822 return attachAuxEffect_l(track, EffectId);
6823}
6824
Eric Laurentde070132010-07-13 04:45:46 -07006825status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6826 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006827{
6828 status_t status = NO_ERROR;
6829
6830 if (EffectId == 0) {
6831 track->setAuxBuffer(0, NULL);
6832 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006833 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6834 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006835 if (effect != 0) {
6836 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6837 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6838 } else {
6839 status = INVALID_OPERATION;
6840 }
6841 } else {
6842 status = BAD_VALUE;
6843 }
6844 }
6845 return status;
6846}
6847
6848void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6849{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006850 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006851 sp<Track> track = mTracks[i];
6852 if (track->auxEffectId() == effectId) {
6853 attachAuxEffect_l(track, 0);
6854 }
6855 }
6856}
6857
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006858status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6859{
6860 // only one chain per input thread
6861 if (mEffectChains.size() != 0) {
6862 return INVALID_OPERATION;
6863 }
Steve Block3856b092011-10-20 11:56:00 +01006864 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006865
6866 chain->setInBuffer(NULL);
6867 chain->setOutBuffer(NULL);
6868
Eric Laurent59255e42011-07-27 19:49:51 -07006869 checkSuspendOnAddEffectChain_l(chain);
6870
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006871 mEffectChains.add(chain);
6872
6873 return NO_ERROR;
6874}
6875
6876size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6877{
Steve Block3856b092011-10-20 11:56:00 +01006878 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006879 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006880 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6881 chain.get(), mEffectChains.size(), this);
6882 if (mEffectChains.size() == 1) {
6883 mEffectChains.removeAt(0);
6884 }
6885 return 0;
6886}
6887
Mathias Agopian65ab4712010-07-14 17:59:35 -07006888// ----------------------------------------------------------------------------
6889// EffectModule implementation
6890// ----------------------------------------------------------------------------
6891
6892#undef LOG_TAG
6893#define LOG_TAG "AudioFlinger::EffectModule"
6894
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006895AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006896 const wp<AudioFlinger::EffectChain>& chain,
6897 effect_descriptor_t *desc,
6898 int id,
6899 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006900 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006901 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006902{
Steve Block3856b092011-10-20 11:56:00 +01006903 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006904 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08006905 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006906 return;
6907 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006908
6909 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6910
6911 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006912 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006913
6914 if (mStatus != NO_ERROR) {
6915 return;
6916 }
6917 lStatus = init();
6918 if (lStatus < 0) {
6919 mStatus = lStatus;
6920 goto Error;
6921 }
6922
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006923 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6924 mPinned = true;
6925 }
Steve Block3856b092011-10-20 11:56:00 +01006926 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006927 return;
6928Error:
6929 EffectRelease(mEffectInterface);
6930 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006931 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006932}
6933
6934AudioFlinger::EffectModule::~EffectModule()
6935{
Steve Block3856b092011-10-20 11:56:00 +01006936 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006937 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006938 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6939 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6940 sp<ThreadBase> thread = mThread.promote();
6941 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006942 audio_stream_t *stream = thread->stream();
6943 if (stream != NULL) {
6944 stream->remove_audio_effect(stream, mEffectInterface);
6945 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006946 }
6947 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006948 // release effect engine
6949 EffectRelease(mEffectInterface);
6950 }
6951}
6952
Glenn Kasten435dbe62012-01-30 10:15:48 -08006953status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006954{
6955 status_t status;
6956
6957 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006958 int priority = handle->priority();
6959 size_t size = mHandles.size();
6960 sp<EffectHandle> h;
6961 size_t i;
6962 for (i = 0; i < size; i++) {
6963 h = mHandles[i].promote();
6964 if (h == 0) continue;
6965 if (h->priority() <= priority) break;
6966 }
6967 // if inserted in first place, move effect control from previous owner to this handle
6968 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006969 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006970 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006971 enabled = h->enabled();
6972 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006973 }
Eric Laurent59255e42011-07-27 19:49:51 -07006974 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006975 status = NO_ERROR;
6976 } else {
6977 status = ALREADY_EXISTS;
6978 }
Steve Block3856b092011-10-20 11:56:00 +01006979 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006980 mHandles.insertAt(handle, i);
6981 return status;
6982}
6983
6984size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6985{
6986 Mutex::Autolock _l(mLock);
6987 size_t size = mHandles.size();
6988 size_t i;
6989 for (i = 0; i < size; i++) {
6990 if (mHandles[i] == handle) break;
6991 }
6992 if (i == size) {
6993 return size;
6994 }
Steve Block3856b092011-10-20 11:56:00 +01006995 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006996
6997 bool enabled = false;
6998 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006999 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01007000 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07007001 enabled = hdl->enabled();
7002 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007003 mHandles.removeAt(i);
7004 size = mHandles.size();
7005 // if removed from first place, move effect control from this handle to next in line
7006 if (i == 0 && size != 0) {
7007 sp<EffectHandle> h = mHandles[0].promote();
7008 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007009 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007010 }
7011 }
7012
Eric Laurentec437d82011-07-26 20:54:46 -07007013 // Prevent calls to process() and other functions on effect interface from now on.
7014 // The effect engine will be released by the destructor when the last strong reference on
7015 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007016 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07007017 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07007018 }
7019
Mathias Agopian65ab4712010-07-14 17:59:35 -07007020 return size;
7021}
7022
Eric Laurent59255e42011-07-27 19:49:51 -07007023sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
7024{
7025 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08007026 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007027}
7028
Glenn Kasten58123c32012-02-03 10:32:24 -08007029void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007030{
Glenn Kasten90bebef2012-01-27 15:24:38 -08007031 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007032 // keep a strong reference on this EffectModule to avoid calling the
7033 // destructor before we exit
7034 sp<EffectModule> keep(this);
7035 {
7036 sp<ThreadBase> thread = mThread.promote();
7037 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007038 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007039 }
7040 }
7041}
7042
7043void AudioFlinger::EffectModule::updateState() {
7044 Mutex::Autolock _l(mLock);
7045
7046 switch (mState) {
7047 case RESTART:
7048 reset_l();
7049 // FALL THROUGH
7050
7051 case STARTING:
7052 // clear auxiliary effect input buffer for next accumulation
7053 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7054 memset(mConfig.inputCfg.buffer.raw,
7055 0,
7056 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
7057 }
7058 start_l();
7059 mState = ACTIVE;
7060 break;
7061 case STOPPING:
7062 stop_l();
7063 mDisableWaitCnt = mMaxDisableWaitCnt;
7064 mState = STOPPED;
7065 break;
7066 case STOPPED:
7067 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
7068 // turn off sequence.
7069 if (--mDisableWaitCnt == 0) {
7070 reset_l();
7071 mState = IDLE;
7072 }
7073 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007074 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07007075 break;
7076 }
7077}
7078
7079void AudioFlinger::EffectModule::process()
7080{
7081 Mutex::Autolock _l(mLock);
7082
Eric Laurentec437d82011-07-26 20:54:46 -07007083 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007084 mConfig.inputCfg.buffer.raw == NULL ||
7085 mConfig.outputCfg.buffer.raw == NULL) {
7086 return;
7087 }
7088
Eric Laurent8f45bd72010-08-31 13:50:07 -07007089 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007090 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
7091 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08007092 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007093 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07007094 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007095 }
7096
7097 // do the actual processing in the effect engine
7098 int ret = (*mEffectInterface)->process(mEffectInterface,
7099 &mConfig.inputCfg.buffer,
7100 &mConfig.outputCfg.buffer);
7101
7102 // force transition to IDLE state when engine is ready
7103 if (mState == STOPPED && ret == -ENODATA) {
7104 mDisableWaitCnt = 1;
7105 }
7106
7107 // clear auxiliary effect input buffer for next accumulation
7108 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08007109 memset(mConfig.inputCfg.buffer.raw, 0,
7110 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007111 }
7112 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08007113 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7114 // If an insert effect is idle and input buffer is different from output buffer,
7115 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07007116 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07007117 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08007118 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
7119 int16_t *in = mConfig.inputCfg.buffer.s16;
7120 int16_t *out = mConfig.outputCfg.buffer.s16;
7121 for (size_t i = 0; i < frameCnt; i++) {
7122 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007123 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007124 }
7125 }
7126}
7127
7128void AudioFlinger::EffectModule::reset_l()
7129{
7130 if (mEffectInterface == NULL) {
7131 return;
7132 }
7133 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
7134}
7135
7136status_t AudioFlinger::EffectModule::configure()
7137{
7138 uint32_t channels;
7139 if (mEffectInterface == NULL) {
7140 return NO_INIT;
7141 }
7142
7143 sp<ThreadBase> thread = mThread.promote();
7144 if (thread == 0) {
7145 return DEAD_OBJECT;
7146 }
7147
7148 // TODO: handle configuration of effects replacing track process
7149 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007150 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007151 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07007152 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007153 }
7154
7155 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007156 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007157 } else {
7158 mConfig.inputCfg.channels = channels;
7159 }
7160 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07007161 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
7162 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007163 mConfig.inputCfg.samplingRate = thread->sampleRate();
7164 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
7165 mConfig.inputCfg.bufferProvider.cookie = NULL;
7166 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
7167 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
7168 mConfig.outputCfg.bufferProvider.cookie = NULL;
7169 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
7170 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
7171 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
7172 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07007173 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07007174 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07007175 // - in other sessions:
7176 // last effect in the chain accumulates in output buffer: input buffer != output buffer
7177 // other effect: overwrites output buffer: input buffer == output buffer
7178 // Auxiliary effect:
7179 // accumulates in output buffer: input buffer != output buffer
7180 // Therefore: accumulate <=> input buffer != output buffer
7181 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7182 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
7183 } else {
7184 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
7185 }
7186 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
7187 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
7188 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
7189 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
7190
Steve Block3856b092011-10-20 11:56:00 +01007191 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07007192 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
7193
Mathias Agopian65ab4712010-07-14 17:59:35 -07007194 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007195 uint32_t size = sizeof(int);
7196 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08007197 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07007198 sizeof(effect_config_t),
7199 &mConfig,
7200 &size,
7201 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007202 if (status == 0) {
7203 status = cmdStatus;
7204 }
7205
7206 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
7207 (1000 * mConfig.outputCfg.buffer.frameCount);
7208
7209 return status;
7210}
7211
7212status_t AudioFlinger::EffectModule::init()
7213{
7214 Mutex::Autolock _l(mLock);
7215 if (mEffectInterface == NULL) {
7216 return NO_INIT;
7217 }
7218 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007219 uint32_t size = sizeof(status_t);
7220 status_t status = (*mEffectInterface)->command(mEffectInterface,
7221 EFFECT_CMD_INIT,
7222 0,
7223 NULL,
7224 &size,
7225 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007226 if (status == 0) {
7227 status = cmdStatus;
7228 }
7229 return status;
7230}
7231
Eric Laurentec35a142011-10-05 17:42:25 -07007232status_t AudioFlinger::EffectModule::start()
7233{
7234 Mutex::Autolock _l(mLock);
7235 return start_l();
7236}
7237
Mathias Agopian65ab4712010-07-14 17:59:35 -07007238status_t AudioFlinger::EffectModule::start_l()
7239{
7240 if (mEffectInterface == NULL) {
7241 return NO_INIT;
7242 }
7243 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007244 uint32_t size = sizeof(status_t);
7245 status_t status = (*mEffectInterface)->command(mEffectInterface,
7246 EFFECT_CMD_ENABLE,
7247 0,
7248 NULL,
7249 &size,
7250 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007251 if (status == 0) {
7252 status = cmdStatus;
7253 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007254 if (status == 0 &&
7255 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7256 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7257 sp<ThreadBase> thread = mThread.promote();
7258 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007259 audio_stream_t *stream = thread->stream();
7260 if (stream != NULL) {
7261 stream->add_audio_effect(stream, mEffectInterface);
7262 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007263 }
7264 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007265 return status;
7266}
7267
Eric Laurentec437d82011-07-26 20:54:46 -07007268status_t AudioFlinger::EffectModule::stop()
7269{
7270 Mutex::Autolock _l(mLock);
7271 return stop_l();
7272}
7273
Mathias Agopian65ab4712010-07-14 17:59:35 -07007274status_t AudioFlinger::EffectModule::stop_l()
7275{
7276 if (mEffectInterface == NULL) {
7277 return NO_INIT;
7278 }
7279 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007280 uint32_t size = sizeof(status_t);
7281 status_t status = (*mEffectInterface)->command(mEffectInterface,
7282 EFFECT_CMD_DISABLE,
7283 0,
7284 NULL,
7285 &size,
7286 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007287 if (status == 0) {
7288 status = cmdStatus;
7289 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007290 if (status == 0 &&
7291 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7292 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7293 sp<ThreadBase> thread = mThread.promote();
7294 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007295 audio_stream_t *stream = thread->stream();
7296 if (stream != NULL) {
7297 stream->remove_audio_effect(stream, mEffectInterface);
7298 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007299 }
7300 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007301 return status;
7302}
7303
Eric Laurent25f43952010-07-28 05:40:18 -07007304status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
7305 uint32_t cmdSize,
7306 void *pCmdData,
7307 uint32_t *replySize,
7308 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007309{
7310 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007311// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007312
Eric Laurentec437d82011-07-26 20:54:46 -07007313 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007314 return NO_INIT;
7315 }
Eric Laurent25f43952010-07-28 05:40:18 -07007316 status_t status = (*mEffectInterface)->command(mEffectInterface,
7317 cmdCode,
7318 cmdSize,
7319 pCmdData,
7320 replySize,
7321 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007322 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07007323 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007324 for (size_t i = 1; i < mHandles.size(); i++) {
7325 sp<EffectHandle> h = mHandles[i].promote();
7326 if (h != 0) {
7327 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
7328 }
7329 }
7330 }
7331 return status;
7332}
7333
7334status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
7335{
Eric Laurentdb7c0792011-08-10 10:37:50 -07007336
Mathias Agopian65ab4712010-07-14 17:59:35 -07007337 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007338 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007339
7340 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007341 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
7342 if (enabled && status != NO_ERROR) {
7343 return status;
7344 }
7345
Mathias Agopian65ab4712010-07-14 17:59:35 -07007346 switch (mState) {
7347 // going from disabled to enabled
7348 case IDLE:
7349 mState = STARTING;
7350 break;
7351 case STOPPED:
7352 mState = RESTART;
7353 break;
7354 case STOPPING:
7355 mState = ACTIVE;
7356 break;
7357
7358 // going from enabled to disabled
7359 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007360 mState = STOPPED;
7361 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007362 case STARTING:
7363 mState = IDLE;
7364 break;
7365 case ACTIVE:
7366 mState = STOPPING;
7367 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007368 case DESTROYED:
7369 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007370 }
7371 for (size_t i = 1; i < mHandles.size(); i++) {
7372 sp<EffectHandle> h = mHandles[i].promote();
7373 if (h != 0) {
7374 h->setEnabled(enabled);
7375 }
7376 }
7377 }
7378 return NO_ERROR;
7379}
7380
Glenn Kastenc59c0042012-02-02 14:06:11 -08007381bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007382{
7383 switch (mState) {
7384 case RESTART:
7385 case STARTING:
7386 case ACTIVE:
7387 return true;
7388 case IDLE:
7389 case STOPPING:
7390 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07007391 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07007392 default:
7393 return false;
7394 }
7395}
7396
Glenn Kastenc59c0042012-02-02 14:06:11 -08007397bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07007398{
7399 switch (mState) {
7400 case RESTART:
7401 case ACTIVE:
7402 case STOPPING:
7403 case STOPPED:
7404 return true;
7405 case IDLE:
7406 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07007407 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007408 default:
7409 return false;
7410 }
7411}
7412
Mathias Agopian65ab4712010-07-14 17:59:35 -07007413status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7414{
7415 Mutex::Autolock _l(mLock);
7416 status_t status = NO_ERROR;
7417
7418 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7419 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07007420 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07007421 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7422 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007423 status_t cmdStatus;
7424 uint32_t volume[2];
7425 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07007426 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007427 volume[0] = *left;
7428 volume[1] = *right;
7429 if (controller) {
7430 pVolume = volume;
7431 }
Eric Laurent25f43952010-07-28 05:40:18 -07007432 status = (*mEffectInterface)->command(mEffectInterface,
7433 EFFECT_CMD_SET_VOLUME,
7434 size,
7435 volume,
7436 &size,
7437 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007438 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7439 *left = volume[0];
7440 *right = volume[1];
7441 }
7442 }
7443 return status;
7444}
7445
7446status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7447{
7448 Mutex::Autolock _l(mLock);
7449 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007450 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7451 // audio pre processing modules on RecordThread can receive both output and
7452 // input device indication in the same call
7453 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7454 if (dev) {
7455 status_t cmdStatus;
7456 uint32_t size = sizeof(status_t);
7457
7458 status = (*mEffectInterface)->command(mEffectInterface,
7459 EFFECT_CMD_SET_DEVICE,
7460 sizeof(uint32_t),
7461 &dev,
7462 &size,
7463 &cmdStatus);
7464 if (status == NO_ERROR) {
7465 status = cmdStatus;
7466 }
7467 }
7468 dev = device & AUDIO_DEVICE_IN_ALL;
7469 if (dev) {
7470 status_t cmdStatus;
7471 uint32_t size = sizeof(status_t);
7472
7473 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7474 EFFECT_CMD_SET_INPUT_DEVICE,
7475 sizeof(uint32_t),
7476 &dev,
7477 &size,
7478 &cmdStatus);
7479 if (status2 == NO_ERROR) {
7480 status2 = cmdStatus;
7481 }
7482 if (status == NO_ERROR) {
7483 status = status2;
7484 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007485 }
7486 }
7487 return status;
7488}
7489
Glenn Kastenf78aee72012-01-04 11:00:47 -08007490status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007491{
7492 Mutex::Autolock _l(mLock);
7493 status_t status = NO_ERROR;
7494 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007495 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007496 uint32_t size = sizeof(status_t);
7497 status = (*mEffectInterface)->command(mEffectInterface,
7498 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08007499 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07007500 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07007501 &size,
7502 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007503 if (status == NO_ERROR) {
7504 status = cmdStatus;
7505 }
7506 }
7507 return status;
7508}
7509
Eric Laurent59255e42011-07-27 19:49:51 -07007510void AudioFlinger::EffectModule::setSuspended(bool suspended)
7511{
7512 Mutex::Autolock _l(mLock);
7513 mSuspended = suspended;
7514}
Glenn Kastena3a85482012-01-04 11:01:11 -08007515
7516bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07007517{
7518 Mutex::Autolock _l(mLock);
7519 return mSuspended;
7520}
7521
Mathias Agopian65ab4712010-07-14 17:59:35 -07007522status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7523{
7524 const size_t SIZE = 256;
7525 char buffer[SIZE];
7526 String8 result;
7527
7528 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7529 result.append(buffer);
7530
7531 bool locked = tryLock(mLock);
7532 // failed to lock - AudioFlinger is probably deadlocked
7533 if (!locked) {
7534 result.append("\t\tCould not lock Fx mutex:\n");
7535 }
7536
7537 result.append("\t\tSession Status State Engine:\n");
7538 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7539 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7540 result.append(buffer);
7541
7542 result.append("\t\tDescriptor:\n");
7543 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7544 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7545 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7546 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7547 result.append(buffer);
7548 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7549 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7550 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7551 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7552 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07007553 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007554 mDescriptor.apiVersion,
7555 mDescriptor.flags);
7556 result.append(buffer);
7557 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7558 mDescriptor.name);
7559 result.append(buffer);
7560 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7561 mDescriptor.implementor);
7562 result.append(buffer);
7563
7564 result.append("\t\t- Input configuration:\n");
7565 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7566 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7567 (uint32_t)mConfig.inputCfg.buffer.raw,
7568 mConfig.inputCfg.buffer.frameCount,
7569 mConfig.inputCfg.samplingRate,
7570 mConfig.inputCfg.channels,
7571 mConfig.inputCfg.format);
7572 result.append(buffer);
7573
7574 result.append("\t\t- Output configuration:\n");
7575 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7576 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7577 (uint32_t)mConfig.outputCfg.buffer.raw,
7578 mConfig.outputCfg.buffer.frameCount,
7579 mConfig.outputCfg.samplingRate,
7580 mConfig.outputCfg.channels,
7581 mConfig.outputCfg.format);
7582 result.append(buffer);
7583
7584 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7585 result.append(buffer);
7586 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7587 for (size_t i = 0; i < mHandles.size(); ++i) {
7588 sp<EffectHandle> handle = mHandles[i].promote();
7589 if (handle != 0) {
7590 handle->dump(buffer, SIZE);
7591 result.append(buffer);
7592 }
7593 }
7594
7595 result.append("\n");
7596
7597 write(fd, result.string(), result.length());
7598
7599 if (locked) {
7600 mLock.unlock();
7601 }
7602
7603 return NO_ERROR;
7604}
7605
7606// ----------------------------------------------------------------------------
7607// EffectHandle implementation
7608// ----------------------------------------------------------------------------
7609
7610#undef LOG_TAG
7611#define LOG_TAG "AudioFlinger::EffectHandle"
7612
7613AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7614 const sp<AudioFlinger::Client>& client,
7615 const sp<IEffectClient>& effectClient,
7616 int32_t priority)
7617 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007618 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007619 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007620{
Steve Block3856b092011-10-20 11:56:00 +01007621 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007622
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007623 if (client == 0) {
7624 return;
7625 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007626 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7627 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7628 if (mCblkMemory != 0) {
7629 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7630
Glenn Kastena0d68332012-01-27 16:47:15 -08007631 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007632 new(mCblk) effect_param_cblk_t();
7633 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007634 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007635 } else {
Steve Block29357bc2012-01-06 19:20:56 +00007636 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007637 return;
7638 }
7639}
7640
7641AudioFlinger::EffectHandle::~EffectHandle()
7642{
Steve Block3856b092011-10-20 11:56:00 +01007643 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007644 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01007645 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007646}
7647
7648status_t AudioFlinger::EffectHandle::enable()
7649{
Steve Block3856b092011-10-20 11:56:00 +01007650 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007651 if (!mHasControl) return INVALID_OPERATION;
7652 if (mEffect == 0) return DEAD_OBJECT;
7653
Eric Laurentdb7c0792011-08-10 10:37:50 -07007654 if (mEnabled) {
7655 return NO_ERROR;
7656 }
7657
Eric Laurent59255e42011-07-27 19:49:51 -07007658 mEnabled = true;
7659
7660 sp<ThreadBase> thread = mEffect->thread().promote();
7661 if (thread != 0) {
7662 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7663 }
7664
7665 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7666 if (mEffect->suspended()) {
7667 return NO_ERROR;
7668 }
7669
Eric Laurentdb7c0792011-08-10 10:37:50 -07007670 status_t status = mEffect->setEnabled(true);
7671 if (status != NO_ERROR) {
7672 if (thread != 0) {
7673 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7674 }
7675 mEnabled = false;
7676 }
7677 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007678}
7679
7680status_t AudioFlinger::EffectHandle::disable()
7681{
Steve Block3856b092011-10-20 11:56:00 +01007682 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007683 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07007684 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007685
Eric Laurentdb7c0792011-08-10 10:37:50 -07007686 if (!mEnabled) {
7687 return NO_ERROR;
7688 }
Eric Laurent59255e42011-07-27 19:49:51 -07007689 mEnabled = false;
7690
7691 if (mEffect->suspended()) {
7692 return NO_ERROR;
7693 }
7694
7695 status_t status = mEffect->setEnabled(false);
7696
7697 sp<ThreadBase> thread = mEffect->thread().promote();
7698 if (thread != 0) {
7699 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7700 }
7701
7702 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007703}
7704
7705void AudioFlinger::EffectHandle::disconnect()
7706{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007707 disconnect(true);
7708}
7709
Glenn Kasten58123c32012-02-03 10:32:24 -08007710void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007711{
Glenn Kasten58123c32012-02-03 10:32:24 -08007712 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007713 if (mEffect == 0) {
7714 return;
7715 }
Glenn Kasten58123c32012-02-03 10:32:24 -08007716 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07007717
Eric Laurenta85a74a2011-10-19 11:44:54 -07007718 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007719 sp<ThreadBase> thread = mEffect->thread().promote();
7720 if (thread != 0) {
7721 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7722 }
Eric Laurent59255e42011-07-27 19:49:51 -07007723 }
7724
Mathias Agopian65ab4712010-07-14 17:59:35 -07007725 // release sp on module => module destructor can be called now
7726 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007727 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08007728 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08007729 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007730 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7731 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08007732 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007733 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07007734 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7735 mClient.clear();
7736 }
7737}
7738
Eric Laurent25f43952010-07-28 05:40:18 -07007739status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7740 uint32_t cmdSize,
7741 void *pCmdData,
7742 uint32_t *replySize,
7743 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007744{
Steve Block3856b092011-10-20 11:56:00 +01007745// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07007746// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007747
7748 // only get parameter command is permitted for applications not controlling the effect
7749 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7750 return INVALID_OPERATION;
7751 }
7752 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007753 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007754
7755 // handle commands that are not forwarded transparently to effect engine
7756 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7757 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7758 // no risk to block the whole media server process or mixer threads is we are stuck here
7759 Mutex::Autolock _l(mCblk->lock);
7760 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7761 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7762 mCblk->serverIndex = 0;
7763 mCblk->clientIndex = 0;
7764 return BAD_VALUE;
7765 }
7766 status_t status = NO_ERROR;
7767 while (mCblk->serverIndex < mCblk->clientIndex) {
7768 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007769 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007770 int *p = (int *)(mBuffer + mCblk->serverIndex);
7771 int size = *p++;
7772 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007773 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007774 break;
7775 }
7776 effect_param_t *param = (effect_param_t *)p;
7777 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007778 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007779 mCblk->serverIndex += size;
7780 continue;
7781 }
Eric Laurent25f43952010-07-28 05:40:18 -07007782 uint32_t psize = sizeof(effect_param_t) +
7783 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7784 param->vsize;
7785 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7786 psize,
7787 p,
7788 &rsize,
7789 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007790 // stop at first error encountered
7791 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007792 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007793 *(int *)pReplyData = reply;
7794 break;
7795 } else if (reply != NO_ERROR) {
7796 *(int *)pReplyData = reply;
7797 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007798 }
7799 mCblk->serverIndex += size;
7800 }
7801 mCblk->serverIndex = 0;
7802 mCblk->clientIndex = 0;
7803 return status;
7804 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007805 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007806 return enable();
7807 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007808 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007809 return disable();
7810 }
7811
7812 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7813}
7814
Eric Laurent59255e42011-07-27 19:49:51 -07007815void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007816{
Steve Block3856b092011-10-20 11:56:00 +01007817 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007818
7819 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007820 mEnabled = enabled;
7821
Mathias Agopian65ab4712010-07-14 17:59:35 -07007822 if (signal && mEffectClient != 0) {
7823 mEffectClient->controlStatusChanged(hasControl);
7824 }
7825}
7826
Eric Laurent25f43952010-07-28 05:40:18 -07007827void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7828 uint32_t cmdSize,
7829 void *pCmdData,
7830 uint32_t replySize,
7831 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007832{
7833 if (mEffectClient != 0) {
7834 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7835 }
7836}
7837
7838
7839
7840void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7841{
7842 if (mEffectClient != 0) {
7843 mEffectClient->enableStatusChanged(enabled);
7844 }
7845}
7846
7847status_t AudioFlinger::EffectHandle::onTransact(
7848 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7849{
7850 return BnEffect::onTransact(code, data, reply, flags);
7851}
7852
7853
7854void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7855{
Glenn Kastena0d68332012-01-27 16:47:15 -08007856 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007857
7858 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08007859 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007860 mPriority,
7861 mHasControl,
7862 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007863 mCblk ? mCblk->clientIndex : 0,
7864 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007865 );
7866
7867 if (locked) {
7868 mCblk->lock.unlock();
7869 }
7870}
7871
7872#undef LOG_TAG
7873#define LOG_TAG "AudioFlinger::EffectChain"
7874
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007875AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007876 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007877 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007878 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7879 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007880{
Dima Zavinfce7a472011-04-19 22:30:36 -07007881 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007882 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007883 return;
7884 }
7885 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7886 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007887}
7888
7889AudioFlinger::EffectChain::~EffectChain()
7890{
7891 if (mOwnInBuffer) {
7892 delete mInBuffer;
7893 }
7894
7895}
7896
Eric Laurent59255e42011-07-27 19:49:51 -07007897// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007898sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007899{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007900 size_t size = mEffects.size();
7901
7902 for (size_t i = 0; i < size; i++) {
7903 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007904 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007905 }
7906 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007907 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007908}
7909
Eric Laurent59255e42011-07-27 19:49:51 -07007910// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007911sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007912{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007913 size_t size = mEffects.size();
7914
7915 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007916 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7917 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007918 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007919 }
7920 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007921 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007922}
7923
Eric Laurent59255e42011-07-27 19:49:51 -07007924// getEffectFromType_l() must be called with ThreadBase::mLock held
7925sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7926 const effect_uuid_t *type)
7927{
Eric Laurent59255e42011-07-27 19:49:51 -07007928 size_t size = mEffects.size();
7929
7930 for (size_t i = 0; i < size; i++) {
7931 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007932 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007933 }
7934 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007935 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007936}
7937
Mathias Agopian65ab4712010-07-14 17:59:35 -07007938// Must be called with EffectChain::mLock locked
7939void AudioFlinger::EffectChain::process_l()
7940{
Eric Laurentdac69112010-09-28 14:09:57 -07007941 sp<ThreadBase> thread = mThread.promote();
7942 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007943 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007944 return;
7945 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007946 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7947 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007948 // always process effects unless no more tracks are on the session and the effect tail
7949 // has been rendered
7950 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007951 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007952 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007953
Eric Laurent544fe9b2011-11-11 15:42:52 -08007954 if (!tracksOnSession && mTailBufferCount == 0) {
7955 doProcess = false;
7956 }
7957
7958 if (activeTrackCnt() == 0) {
7959 // if no track is active and the effect tail has not been rendered,
7960 // the input buffer must be cleared here as the mixer process will not do it
7961 if (tracksOnSession || mTailBufferCount > 0) {
7962 size_t numSamples = thread->frameCount() * thread->channelCount();
7963 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7964 if (mTailBufferCount > 0) {
7965 mTailBufferCount--;
7966 }
7967 }
7968 }
Eric Laurentdac69112010-09-28 14:09:57 -07007969 }
7970
Mathias Agopian65ab4712010-07-14 17:59:35 -07007971 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007972 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007973 for (size_t i = 0; i < size; i++) {
7974 mEffects[i]->process();
7975 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007976 }
7977 for (size_t i = 0; i < size; i++) {
7978 mEffects[i]->updateState();
7979 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007980}
7981
Eric Laurentcab11242010-07-15 12:50:15 -07007982// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007983status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007984{
7985 effect_descriptor_t desc = effect->desc();
7986 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7987
7988 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007989 effect->setChain(this);
7990 sp<ThreadBase> thread = mThread.promote();
7991 if (thread == 0) {
7992 return NO_INIT;
7993 }
7994 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007995
7996 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7997 // Auxiliary effects are inserted at the beginning of mEffects vector as
7998 // they are processed first and accumulated in chain input buffer
7999 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07008000
Mathias Agopian65ab4712010-07-14 17:59:35 -07008001 // the input buffer for auxiliary effect contains mono samples in
8002 // 32 bit format. This is to avoid saturation in AudoMixer
8003 // accumulation stage. Saturation is done in EffectModule::process() before
8004 // calling the process in effect engine
8005 size_t numSamples = thread->frameCount();
8006 int32_t *buffer = new int32_t[numSamples];
8007 memset(buffer, 0, numSamples * sizeof(int32_t));
8008 effect->setInBuffer((int16_t *)buffer);
8009 // auxiliary effects output samples to chain input buffer for further processing
8010 // by insert effects
8011 effect->setOutBuffer(mInBuffer);
8012 } else {
8013 // Insert effects are inserted at the end of mEffects vector as they are processed
8014 // after track and auxiliary effects.
8015 // Insert effect order as a function of indicated preference:
8016 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
8017 // another effect is present
8018 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
8019 // last effect claiming first position
8020 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
8021 // first effect claiming last position
8022 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
8023 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
8024 // already present
8025
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008026 size_t size = mEffects.size();
8027 size_t idx_insert = size;
8028 ssize_t idx_insert_first = -1;
8029 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008030
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008031 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008032 effect_descriptor_t d = mEffects[i]->desc();
8033 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
8034 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
8035 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
8036 // check invalid effect chaining combinations
8037 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
8038 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008039 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008040 return INVALID_OPERATION;
8041 }
8042 // remember position of first insert effect and by default
8043 // select this as insert position for new effect
8044 if (idx_insert == size) {
8045 idx_insert = i;
8046 }
8047 // remember position of last insert effect claiming
8048 // first position
8049 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
8050 idx_insert_first = i;
8051 }
8052 // remember position of first insert effect claiming
8053 // last position
8054 if (iPref == EFFECT_FLAG_INSERT_LAST &&
8055 idx_insert_last == -1) {
8056 idx_insert_last = i;
8057 }
8058 }
8059 }
8060
8061 // modify idx_insert from first position if needed
8062 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
8063 if (idx_insert_last != -1) {
8064 idx_insert = idx_insert_last;
8065 } else {
8066 idx_insert = size;
8067 }
8068 } else {
8069 if (idx_insert_first != -1) {
8070 idx_insert = idx_insert_first + 1;
8071 }
8072 }
8073
8074 // always read samples from chain input buffer
8075 effect->setInBuffer(mInBuffer);
8076
8077 // if last effect in the chain, output samples to chain
8078 // output buffer, otherwise to chain input buffer
8079 if (idx_insert == size) {
8080 if (idx_insert != 0) {
8081 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
8082 mEffects[idx_insert-1]->configure();
8083 }
8084 effect->setOutBuffer(mOutBuffer);
8085 } else {
8086 effect->setOutBuffer(mInBuffer);
8087 }
8088 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008089
Steve Block3856b092011-10-20 11:56:00 +01008090 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008091 }
8092 effect->configure();
8093 return NO_ERROR;
8094}
8095
Eric Laurentcab11242010-07-15 12:50:15 -07008096// removeEffect_l() must be called with PlaybackThread::mLock held
8097size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008098{
8099 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008100 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008101 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
8102
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008103 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008104 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07008105 // calling stop here will remove pre-processing effect from the audio HAL.
8106 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
8107 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07008108 if (mEffects[i]->state() == EffectModule::ACTIVE ||
8109 mEffects[i]->state() == EffectModule::STOPPING) {
8110 mEffects[i]->stop();
8111 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008112 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
8113 delete[] effect->inBuffer();
8114 } else {
8115 if (i == size - 1 && i != 0) {
8116 mEffects[i - 1]->setOutBuffer(mOutBuffer);
8117 mEffects[i - 1]->configure();
8118 }
8119 }
8120 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01008121 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008122 break;
8123 }
8124 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008125
8126 return mEffects.size();
8127}
8128
Eric Laurentcab11242010-07-15 12:50:15 -07008129// setDevice_l() must be called with PlaybackThread::mLock held
8130void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008131{
8132 size_t size = mEffects.size();
8133 for (size_t i = 0; i < size; i++) {
8134 mEffects[i]->setDevice(device);
8135 }
8136}
8137
Eric Laurentcab11242010-07-15 12:50:15 -07008138// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08008139void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008140{
8141 size_t size = mEffects.size();
8142 for (size_t i = 0; i < size; i++) {
8143 mEffects[i]->setMode(mode);
8144 }
8145}
8146
Eric Laurentcab11242010-07-15 12:50:15 -07008147// setVolume_l() must be called with PlaybackThread::mLock held
8148bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008149{
8150 uint32_t newLeft = *left;
8151 uint32_t newRight = *right;
8152 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07008153 int ctrlIdx = -1;
8154 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008155
Eric Laurentcab11242010-07-15 12:50:15 -07008156 // first update volume controller
8157 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07008158 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07008159 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
8160 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07008161 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07008162 break;
8163 }
8164 }
8165
8166 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07008167 if (hasControl) {
8168 *left = mNewLeftVolume;
8169 *right = mNewRightVolume;
8170 }
8171 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07008172 }
8173
8174 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07008175 mLeftVolume = newLeft;
8176 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008177
8178 // second get volume update from volume controller
8179 if (ctrlIdx >= 0) {
8180 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07008181 mNewLeftVolume = newLeft;
8182 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008183 }
8184 // then indicate volume to all other effects in chain.
8185 // Pass altered volume to effects before volume controller
8186 // and requested volume to effects after controller
8187 uint32_t lVol = newLeft;
8188 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008189
Mathias Agopian65ab4712010-07-14 17:59:35 -07008190 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07008191 if ((int)i == ctrlIdx) continue;
8192 // this also works for ctrlIdx == -1 when there is no volume controller
8193 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008194 lVol = *left;
8195 rVol = *right;
8196 }
8197 mEffects[i]->setVolume(&lVol, &rVol, false);
8198 }
8199 *left = newLeft;
8200 *right = newRight;
8201
8202 return hasControl;
8203}
8204
Mathias Agopian65ab4712010-07-14 17:59:35 -07008205status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
8206{
8207 const size_t SIZE = 256;
8208 char buffer[SIZE];
8209 String8 result;
8210
8211 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
8212 result.append(buffer);
8213
8214 bool locked = tryLock(mLock);
8215 // failed to lock - AudioFlinger is probably deadlocked
8216 if (!locked) {
8217 result.append("\tCould not lock mutex:\n");
8218 }
8219
Eric Laurentcab11242010-07-15 12:50:15 -07008220 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
8221 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008222 mEffects.size(),
8223 (uint32_t)mInBuffer,
8224 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008225 mActiveTrackCnt);
8226 result.append(buffer);
8227 write(fd, result.string(), result.size());
8228
8229 for (size_t i = 0; i < mEffects.size(); ++i) {
8230 sp<EffectModule> effect = mEffects[i];
8231 if (effect != 0) {
8232 effect->dump(fd, args);
8233 }
8234 }
8235
8236 if (locked) {
8237 mLock.unlock();
8238 }
8239
8240 return NO_ERROR;
8241}
8242
Eric Laurent59255e42011-07-27 19:49:51 -07008243// must be called with ThreadBase::mLock held
8244void AudioFlinger::EffectChain::setEffectSuspended_l(
8245 const effect_uuid_t *type, bool suspend)
8246{
8247 sp<SuspendedEffectDesc> desc;
8248 // use effect type UUID timelow as key as there is no real risk of identical
8249 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008250 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008251 if (suspend) {
8252 if (index >= 0) {
8253 desc = mSuspendedEffects.valueAt(index);
8254 } else {
8255 desc = new SuspendedEffectDesc();
8256 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
8257 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01008258 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008259 }
8260 if (desc->mRefCount++ == 0) {
8261 sp<EffectModule> effect = getEffectIfEnabled(type);
8262 if (effect != 0) {
8263 desc->mEffect = effect;
8264 effect->setSuspended(true);
8265 effect->setEnabled(false);
8266 }
8267 }
8268 } else {
8269 if (index < 0) {
8270 return;
8271 }
8272 desc = mSuspendedEffects.valueAt(index);
8273 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008274 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008275 desc->mRefCount = 1;
8276 }
8277 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01008278 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008279 if (desc->mEffect != 0) {
8280 sp<EffectModule> effect = desc->mEffect.promote();
8281 if (effect != 0) {
8282 effect->setSuspended(false);
8283 sp<EffectHandle> handle = effect->controlHandle();
8284 if (handle != 0) {
8285 effect->setEnabled(handle->enabled());
8286 }
8287 }
8288 desc->mEffect.clear();
8289 }
8290 mSuspendedEffects.removeItemsAt(index);
8291 }
8292 }
8293}
8294
8295// must be called with ThreadBase::mLock held
8296void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
8297{
8298 sp<SuspendedEffectDesc> desc;
8299
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008300 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07008301 if (suspend) {
8302 if (index >= 0) {
8303 desc = mSuspendedEffects.valueAt(index);
8304 } else {
8305 desc = new SuspendedEffectDesc();
8306 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01008307 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07008308 }
8309 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08008310 Vector< sp<EffectModule> > effects;
8311 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07008312 for (size_t i = 0; i < effects.size(); i++) {
8313 setEffectSuspended_l(&effects[i]->desc().type, true);
8314 }
8315 }
8316 } else {
8317 if (index < 0) {
8318 return;
8319 }
8320 desc = mSuspendedEffects.valueAt(index);
8321 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008322 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008323 desc->mRefCount = 1;
8324 }
8325 if (--desc->mRefCount == 0) {
8326 Vector<const effect_uuid_t *> types;
8327 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
8328 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
8329 continue;
8330 }
8331 types.add(&mSuspendedEffects.valueAt(i)->mType);
8332 }
8333 for (size_t i = 0; i < types.size(); i++) {
8334 setEffectSuspended_l(types[i], false);
8335 }
Steve Block3856b092011-10-20 11:56:00 +01008336 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008337 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
8338 }
8339 }
8340}
8341
Eric Laurent6bffdb82011-09-23 08:40:41 -07008342
8343// The volume effect is used for automated tests only
8344#ifndef OPENSL_ES_H_
8345static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
8346 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
8347const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
8348#endif //OPENSL_ES_H_
8349
Eric Laurentdb7c0792011-08-10 10:37:50 -07008350bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
8351{
8352 // auxiliary effects and visualizer are never suspended on output mix
8353 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8354 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07008355 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8356 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008357 return false;
8358 }
8359 return true;
8360}
8361
Glenn Kastend0539712012-01-30 12:56:03 -08008362void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07008363{
Glenn Kastend0539712012-01-30 12:56:03 -08008364 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07008365 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08008366 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8367 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07008368 }
Eric Laurent59255e42011-07-27 19:49:51 -07008369 }
Eric Laurent59255e42011-07-27 19:49:51 -07008370}
8371
8372sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8373 const effect_uuid_t *type)
8374{
Glenn Kasten090f0192012-01-30 13:00:02 -08008375 sp<EffectModule> effect = getEffectFromType_l(type);
8376 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008377}
8378
8379void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8380 bool enabled)
8381{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008382 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008383 if (enabled) {
8384 if (index < 0) {
8385 // if the effect is not suspend check if all effects are suspended
8386 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8387 if (index < 0) {
8388 return;
8389 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07008390 if (!isEffectEligibleForSuspend(effect->desc())) {
8391 return;
8392 }
Eric Laurent59255e42011-07-27 19:49:51 -07008393 setEffectSuspended_l(&effect->desc().type, enabled);
8394 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07008395 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008396 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07008397 return;
8398 }
Eric Laurent59255e42011-07-27 19:49:51 -07008399 }
Steve Block3856b092011-10-20 11:56:00 +01008400 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008401 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008402 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8403 // if effect is requested to suspended but was not yet enabled, supend it now.
8404 if (desc->mEffect == 0) {
8405 desc->mEffect = effect;
8406 effect->setEnabled(false);
8407 effect->setSuspended(true);
8408 }
8409 } else {
8410 if (index < 0) {
8411 return;
8412 }
Steve Block3856b092011-10-20 11:56:00 +01008413 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008414 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008415 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8416 desc->mEffect.clear();
8417 effect->setSuspended(false);
8418 }
8419}
8420
Mathias Agopian65ab4712010-07-14 17:59:35 -07008421#undef LOG_TAG
8422#define LOG_TAG "AudioFlinger"
8423
8424// ----------------------------------------------------------------------------
8425
8426status_t AudioFlinger::onTransact(
8427 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8428{
8429 return BnAudioFlinger::onTransact(code, data, reply, flags);
8430}
8431
Mathias Agopian65ab4712010-07-14 17:59:35 -07008432}; // namespace android