blob: 0c86e2095771ac10cfe3cdd7c5b250f352ca260b [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>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070030#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070031#include <binder/Parcel.h>
32#include <binder/IPCThreadState.h>
33#include <utils/String16.h>
34#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070035#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070036
Dima Zavinfce7a472011-04-19 22:30:36 -070037#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070038#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080039#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040
Glenn Kastend3cee2f2012-03-13 17:55:35 -070041#undef ADD_BATTERY_DATA
42
43#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080044#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080045#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070046#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070047
48#include <private/media/AudioTrackShared.h>
49#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070050
Dima Zavin64760242011-05-11 14:15:23 -070051#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070052#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070053
54#include "AudioMixer.h"
55#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080056#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Mathias Agopian65ab4712010-07-14 17:59:35 -070058#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070059#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070060#include <audio_effects/effect_ns.h>
61#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070062
Glenn Kasten3b21c502011-12-15 09:52:39 -080063#include <audio_utils/primitives.h>
64
Eric Laurentfeb0db62011-07-22 09:04:31 -070065#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080066
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070067// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080068#ifdef DEBUG_CPU_USAGE
69#include <cpustats/CentralTendencyStatistics.h>
70#include <cpustats/ThreadCpuUsage.h>
71#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070072
John Grossman4ff14ba2012-02-08 16:37:41 -080073#include <common_time/cc_helper.h>
74#include <common_time/local_clock.h>
75
Glenn Kasten58912562012-04-03 10:45:00 -070076#include "FastMixer.h"
77
78// NBAIO implementations
79#include "AudioStreamOutSink.h"
80#include "MonoPipe.h"
81#include "MonoPipeReader.h"
Glenn Kastenfbae5da2012-05-21 09:17:20 -070082#include "Pipe.h"
83#include "PipeReader.h"
Glenn Kasten58912562012-04-03 10:45:00 -070084#include "SourceAudioBufferProvider.h"
85
Glenn Kasten1dc28b72012-04-24 10:01:03 -070086#include "SchedulingPolicyService.h"
Glenn Kasten58912562012-04-03 10:45:00 -070087
Mathias Agopian65ab4712010-07-14 17:59:35 -070088// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
John Grossman1c345192012-03-27 14:00:17 -070090// Note: the following macro is used for extremely verbose logging message. In
91// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
92// 0; but one side effect of this is to turn all LOGV's as well. Some messages
93// are so verbose that we want to suppress them even when we have ALOG_ASSERT
94// turned on. Do not uncomment the #def below unless you really know what you
95// are doing and want to see all of the extremely verbose messages.
96//#define VERY_VERY_VERBOSE_LOGGING
97#ifdef VERY_VERY_VERBOSE_LOGGING
98#define ALOGVV ALOGV
99#else
100#define ALOGVV(a...) do { } while(0)
101#endif
Eric Laurentde070132010-07-13 04:45:46 -0700102
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103namespace android {
104
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800105static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
106static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700107
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800109static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110
111// retry counts for buffer fill timeout
112// 50 * ~20msecs = 1 second
113static const int8_t kMaxTrackRetries = 50;
114static const int8_t kMaxTrackStartupRetries = 50;
115// allow less retry attempts on direct output thread.
116// direct outputs can be a scarce resource in audio hardware and should
117// be released as quickly as possible.
118static const int8_t kMaxTrackRetriesDirect = 2;
119
120static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -0800121static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700122
Glenn Kasten7dede872011-12-13 11:04:14 -0800123// don't warn about blocked writes or record buffer overflows more often than this
124static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700125
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700126// RecordThread loop sleep time upon application overrun or audio HAL read error
127static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700128
Glenn Kasten7dede872011-12-13 11:04:14 -0800129// maximum time to wait for setParameters to complete
130static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700131
Eric Laurent7cafbb32011-11-22 18:50:29 -0800132// minimum sleep time for the mixer thread loop when tracks are active but in underrun
133static const uint32_t kMinThreadSleepTimeUs = 5000;
134// maximum divider applied to the active sleep time in the mixer thread loop
135static const uint32_t kMaxThreadSleepTimeShift = 2;
136
Glenn Kasten58912562012-04-03 10:45:00 -0700137// minimum normal mix buffer size, expressed in milliseconds rather than frames
138static const uint32_t kMinNormalMixBufferSizeMs = 20;
Glenn Kasten4adcede2012-05-14 12:26:02 -0700139// maximum normal mix buffer size
140static const uint32_t kMaxNormalMixBufferSizeMs = 24;
Glenn Kasten58912562012-04-03 10:45:00 -0700141
John Grossman4ff14ba2012-02-08 16:37:41 -0800142nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800143
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700144// Whether to use fast mixer
145static const enum {
146 FastMixer_Never, // never initialize or use: for debugging only
147 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
148 // normal mixer multiplier is 1
149 FastMixer_Static, // initialize if needed, then use all the time if initialized,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700150 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700151 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700152 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700153 // FIXME for FastMixer_Dynamic:
154 // Supporting this option will require fixing HALs that can't handle large writes.
155 // For example, one HAL implementation returns an error from a large write,
156 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
157 // We could either fix the HAL implementations, or provide a wrapper that breaks
158 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
159} kUseFastMixer = FastMixer_Static;
160
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700161static uint32_t gScreenState; // incremented by 2 when screen state changes, bit 0 == 1 means "off"
162 // AudioFlinger::setParameters() updates, other threads read w/o lock
163
Mathias Agopian65ab4712010-07-14 17:59:35 -0700164// ----------------------------------------------------------------------------
165
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700166#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800167// To collect the amplifier usage
168static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800169 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
170 if (service == NULL) {
171 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800172 return;
173 }
174
175 service->addBatteryData(params);
176}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700177#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800178
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700179static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700180{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700181 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700182 int rc;
183
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700184 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
185 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
186 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
187 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700188 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700189 }
190 rc = audio_hw_device_open(mod, dev);
191 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
192 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
193 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700194 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700195 }
196 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
197 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
198 rc = BAD_VALUE;
199 goto out;
200 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700201 return 0;
202
203out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700204 *dev = NULL;
205 return rc;
206}
207
Mathias Agopian65ab4712010-07-14 17:59:35 -0700208// ----------------------------------------------------------------------------
209
210AudioFlinger::AudioFlinger()
211 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800212 mPrimaryHardwareDev(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700213 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800214 mMasterVolume(1.0f),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700215 mMasterVolumeSW(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800216 mMasterVolumeSupportLvl(MVS_NONE),
217 mMasterMute(false),
218 mNextUniqueId(1),
219 mMode(AUDIO_MODE_INVALID),
220 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700222}
223
224void AudioFlinger::onFirstRef()
225{
Dima Zavin799a70e2011-04-18 16:57:27 -0700226 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700227
Eric Laurent93575202011-01-18 18:39:02 -0800228 Mutex::Autolock _l(mLock);
229
Dima Zavin799a70e2011-04-18 16:57:27 -0700230 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800231 char val_str[PROPERTY_VALUE_MAX] = { 0 };
232 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
233 uint32_t int_val;
234 if (1 == sscanf(val_str, "%u", &int_val)) {
235 mStandbyTimeInNsecs = milliseconds(int_val);
236 ALOGI("Using %u mSec as standby time.", int_val);
237 } else {
238 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
239 ALOGI("Using default %u mSec as standby time.",
240 (uint32_t)(mStandbyTimeInNsecs / 1000000));
241 }
242 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700243
Eric Laurenta4c5a552012-03-29 10:12:40 -0700244 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700245}
246
247AudioFlinger::~AudioFlinger()
248{
249 while (!mRecordThreads.isEmpty()) {
250 // closeInput() will remove first entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700251 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700252 }
253 while (!mPlaybackThreads.isEmpty()) {
254 // closeOutput() will remove first entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700255 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700256 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700257
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800258 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
259 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700260 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
261 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700262 }
263}
264
Eric Laurenta4c5a552012-03-29 10:12:40 -0700265static const char * const audio_interfaces[] = {
266 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
267 AUDIO_HARDWARE_MODULE_ID_A2DP,
268 AUDIO_HARDWARE_MODULE_ID_USB,
269};
270#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
271
272audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(audio_module_handle_t module, uint32_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700273{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700274 // if module is 0, the request comes from an old policy manager and we should load
275 // well known modules
276 if (module == 0) {
277 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
278 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
279 loadHwModule_l(audio_interfaces[i]);
280 }
281 } else {
282 // check a match for the requested module handle
283 AudioHwDevice *audioHwdevice = mAudioHwDevs.valueFor(module);
284 if (audioHwdevice != NULL) {
285 return audioHwdevice->hwDevice();
286 }
287 }
288 // then try to find a module supporting the requested device.
Dima Zavin799a70e2011-04-18 16:57:27 -0700289 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700290 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700291 if ((dev->get_supported_devices(dev) & devices) == devices)
292 return dev;
293 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700294
Dima Zavin799a70e2011-04-18 16:57:27 -0700295 return NULL;
296}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700297
298status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
299{
300 const size_t SIZE = 256;
301 char buffer[SIZE];
302 String8 result;
303
304 result.append("Clients:\n");
305 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800306 sp<Client> client = mClients.valueAt(i).promote();
307 if (client != 0) {
308 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
309 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700310 }
311 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700312
313 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800314 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700315 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
316 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800317 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700318 result.append(buffer);
319 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700320 write(fd, result.string(), result.size());
321 return NO_ERROR;
322}
323
324
325status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
326{
327 const size_t SIZE = 256;
328 char buffer[SIZE];
329 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800330 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700331
John Grossman4ff14ba2012-02-08 16:37:41 -0800332 snprintf(buffer, SIZE, "Hardware status: %d\n"
333 "Standby Time mSec: %u\n",
334 hardwareStatus,
335 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700336 result.append(buffer);
337 write(fd, result.string(), result.size());
338 return NO_ERROR;
339}
340
341status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
342{
343 const size_t SIZE = 256;
344 char buffer[SIZE];
345 String8 result;
346 snprintf(buffer, SIZE, "Permission Denial: "
347 "can't dump AudioFlinger from pid=%d, uid=%d\n",
348 IPCThreadState::self()->getCallingPid(),
349 IPCThreadState::self()->getCallingUid());
350 result.append(buffer);
351 write(fd, result.string(), result.size());
352 return NO_ERROR;
353}
354
355static bool tryLock(Mutex& mutex)
356{
357 bool locked = false;
358 for (int i = 0; i < kDumpLockRetries; ++i) {
359 if (mutex.tryLock() == NO_ERROR) {
360 locked = true;
361 break;
362 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800363 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700364 }
365 return locked;
366}
367
368status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
369{
Glenn Kasten44deb052012-02-05 18:09:08 -0800370 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700371 dumpPermissionDenial(fd, args);
372 } else {
373 // get state of hardware lock
374 bool hardwareLocked = tryLock(mHardwareLock);
375 if (!hardwareLocked) {
376 String8 result(kHardwareLockedString);
377 write(fd, result.string(), result.size());
378 } else {
379 mHardwareLock.unlock();
380 }
381
382 bool locked = tryLock(mLock);
383
384 // failed to lock - AudioFlinger is probably deadlocked
385 if (!locked) {
386 String8 result(kDeadlockedString);
387 write(fd, result.string(), result.size());
388 }
389
390 dumpClients(fd, args);
391 dumpInternals(fd, args);
392
393 // dump playback threads
394 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
395 mPlaybackThreads.valueAt(i)->dump(fd, args);
396 }
397
398 // dump record threads
399 for (size_t i = 0; i < mRecordThreads.size(); i++) {
400 mRecordThreads.valueAt(i)->dump(fd, args);
401 }
402
Dima Zavin799a70e2011-04-18 16:57:27 -0700403 // dump all hardware devs
404 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700405 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700406 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700407 }
408 if (locked) mLock.unlock();
409 }
410 return NO_ERROR;
411}
412
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800413sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
414{
415 // If pid is already in the mClients wp<> map, then use that entry
416 // (for which promote() is always != 0), otherwise create a new entry and Client.
417 sp<Client> client = mClients.valueFor(pid).promote();
418 if (client == 0) {
419 client = new Client(this, pid);
420 mClients.add(pid, client);
421 }
422
423 return client;
424}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700425
426// IAudioFlinger interface
427
428
429sp<IAudioTrack> AudioFlinger::createTrack(
430 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800431 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700432 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800433 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700434 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700435 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800436 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700437 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800438 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800439 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700440 int *sessionId,
441 status_t *status)
442{
443 sp<PlaybackThread::Track> track;
444 sp<TrackHandle> trackHandle;
445 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700446 status_t lStatus;
447 int lSessionId;
448
Glenn Kasten263709e2012-01-06 08:40:01 -0800449 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
450 // but if someone uses binder directly they could bypass that and cause us to crash
451 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000452 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700453 lStatus = BAD_VALUE;
454 goto Exit;
455 }
456
457 {
458 Mutex::Autolock _l(mLock);
459 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700460 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700461 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000462 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700463 lStatus = BAD_VALUE;
464 goto Exit;
465 }
466
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800467 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700468
Steve Block3856b092011-10-20 11:56:00 +0100469 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700470 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700471 // check if an effect chain with the same session ID is present on another
472 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700473 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700474 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
475 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700476 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700477 if (sessions & PlaybackThread::EFFECT_SESSION) {
478 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700479 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700480 }
Eric Laurentde070132010-07-13 04:45:46 -0700481 }
482 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700483 lSessionId = *sessionId;
484 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700485 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700486 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700487 if (sessionId != NULL) {
488 *sessionId = lSessionId;
489 }
490 }
Steve Block3856b092011-10-20 11:56:00 +0100491 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700492
493 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800494 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700495
496 // move effect chain to this output thread if an effect on same session was waiting
497 // for a track to be created
498 if (lStatus == NO_ERROR && effectThread != NULL) {
499 Mutex::Autolock _dl(thread->mLock);
500 Mutex::Autolock _sl(effectThread->mLock);
501 moveEffectChain_l(lSessionId, effectThread, thread, true);
502 }
Eric Laurenta011e352012-03-29 15:51:43 -0700503
504 // Look for sync events awaiting for a session to be used.
505 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
506 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
507 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700508 if (lStatus == NO_ERROR) {
509 track->setSyncEvent(mPendingSyncEvents[i]);
510 } else {
511 mPendingSyncEvents[i]->cancel();
512 }
Eric Laurenta011e352012-03-29 15:51:43 -0700513 mPendingSyncEvents.removeAt(i);
514 i--;
515 }
516 }
517 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700518 }
519 if (lStatus == NO_ERROR) {
520 trackHandle = new TrackHandle(track);
521 } else {
522 // remove local strong reference to Client before deleting the Track so that the Client
523 // destructor is called by the TrackBase destructor with mLock held
524 client.clear();
525 track.clear();
526 }
527
528Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700529 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700530 *status = lStatus;
531 }
532 return trackHandle;
533}
534
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800535uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700536{
537 Mutex::Autolock _l(mLock);
538 PlaybackThread *thread = checkPlaybackThread_l(output);
539 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000540 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700541 return 0;
542 }
543 return thread->sampleRate();
544}
545
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800546int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700547{
548 Mutex::Autolock _l(mLock);
549 PlaybackThread *thread = checkPlaybackThread_l(output);
550 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000551 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700552 return 0;
553 }
554 return thread->channelCount();
555}
556
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800557audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700558{
559 Mutex::Autolock _l(mLock);
560 PlaybackThread *thread = checkPlaybackThread_l(output);
561 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000562 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800563 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700564 }
565 return thread->format();
566}
567
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800568size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700569{
570 Mutex::Autolock _l(mLock);
571 PlaybackThread *thread = checkPlaybackThread_l(output);
572 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000573 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700574 return 0;
575 }
Glenn Kasten58912562012-04-03 10:45:00 -0700576 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
577 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700578 return thread->frameCount();
579}
580
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800581uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700582{
583 Mutex::Autolock _l(mLock);
584 PlaybackThread *thread = checkPlaybackThread_l(output);
585 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000586 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700587 return 0;
588 }
589 return thread->latency();
590}
591
592status_t AudioFlinger::setMasterVolume(float value)
593{
Eric Laurenta1884f92011-08-23 08:25:03 -0700594 status_t ret = initCheck();
595 if (ret != NO_ERROR) {
596 return ret;
597 }
598
Mathias Agopian65ab4712010-07-14 17:59:35 -0700599 // check calling permissions
600 if (!settingsAllowed()) {
601 return PERMISSION_DENIED;
602 }
603
John Grossman4ff14ba2012-02-08 16:37:41 -0800604 float swmv = value;
605
Eric Laurenta4c5a552012-03-29 10:12:40 -0700606 Mutex::Autolock _l(mLock);
607
Mathias Agopian65ab4712010-07-14 17:59:35 -0700608 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800609 if (MVS_NONE != mMasterVolumeSupportLvl) {
610 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
611 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700612 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
John Grossman4ff14ba2012-02-08 16:37:41 -0800613
614 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
615 if (NULL != dev->set_master_volume) {
616 dev->set_master_volume(dev, value);
617 }
618 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800619 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800620
621 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700622 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700623
John Grossman4ff14ba2012-02-08 16:37:41 -0800624 mMasterVolume = value;
625 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800626 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700627 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700628
629 return NO_ERROR;
630}
631
Glenn Kastenf78aee72012-01-04 11:00:47 -0800632status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700633{
Eric Laurenta1884f92011-08-23 08:25:03 -0700634 status_t ret = initCheck();
635 if (ret != NO_ERROR) {
636 return ret;
637 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700638
639 // check calling permissions
640 if (!settingsAllowed()) {
641 return PERMISSION_DENIED;
642 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800643 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000644 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700645 return BAD_VALUE;
646 }
647
648 { // scope for the lock
649 AutoMutex lock(mHardwareLock);
650 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700651 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700652 mHardwareStatus = AUDIO_HW_IDLE;
653 }
654
655 if (NO_ERROR == ret) {
656 Mutex::Autolock _l(mLock);
657 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800658 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700659 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700660 }
661
662 return ret;
663}
664
665status_t AudioFlinger::setMicMute(bool state)
666{
Eric Laurenta1884f92011-08-23 08:25:03 -0700667 status_t ret = initCheck();
668 if (ret != NO_ERROR) {
669 return ret;
670 }
671
Mathias Agopian65ab4712010-07-14 17:59:35 -0700672 // check calling permissions
673 if (!settingsAllowed()) {
674 return PERMISSION_DENIED;
675 }
676
677 AutoMutex lock(mHardwareLock);
678 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700679 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700680 mHardwareStatus = AUDIO_HW_IDLE;
681 return ret;
682}
683
684bool AudioFlinger::getMicMute() const
685{
Eric Laurenta1884f92011-08-23 08:25:03 -0700686 status_t ret = initCheck();
687 if (ret != NO_ERROR) {
688 return false;
689 }
690
Dima Zavinfce7a472011-04-19 22:30:36 -0700691 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800692 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700693 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700694 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700695 mHardwareStatus = AUDIO_HW_IDLE;
696 return state;
697}
698
699status_t AudioFlinger::setMasterMute(bool muted)
700{
701 // check calling permissions
702 if (!settingsAllowed()) {
703 return PERMISSION_DENIED;
704 }
705
Eric Laurent93575202011-01-18 18:39:02 -0800706 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800707 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700708 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800709 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700710 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700711
712 return NO_ERROR;
713}
714
715float AudioFlinger::masterVolume() const
716{
Glenn Kasten98067102011-12-13 11:47:54 -0800717 Mutex::Autolock _l(mLock);
718 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700719}
720
John Grossman4ff14ba2012-02-08 16:37:41 -0800721float AudioFlinger::masterVolumeSW() const
722{
723 Mutex::Autolock _l(mLock);
724 return masterVolumeSW_l();
725}
726
Mathias Agopian65ab4712010-07-14 17:59:35 -0700727bool AudioFlinger::masterMute() const
728{
Glenn Kasten98067102011-12-13 11:47:54 -0800729 Mutex::Autolock _l(mLock);
730 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700731}
732
John Grossman4ff14ba2012-02-08 16:37:41 -0800733float AudioFlinger::masterVolume_l() const
734{
735 if (MVS_FULL == mMasterVolumeSupportLvl) {
736 float ret_val;
737 AutoMutex lock(mHardwareLock);
738
739 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800740 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
741 (NULL != mPrimaryHardwareDev->get_master_volume),
742 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800743
744 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
745 mHardwareStatus = AUDIO_HW_IDLE;
746 return ret_val;
747 }
748
749 return mMasterVolume;
750}
751
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800752status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
753 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700754{
755 // check calling permissions
756 if (!settingsAllowed()) {
757 return PERMISSION_DENIED;
758 }
759
Glenn Kasten263709e2012-01-06 08:40:01 -0800760 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000761 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700762 return BAD_VALUE;
763 }
764
765 AutoMutex lock(mLock);
766 PlaybackThread *thread = NULL;
767 if (output) {
768 thread = checkPlaybackThread_l(output);
769 if (thread == NULL) {
770 return BAD_VALUE;
771 }
772 }
773
774 mStreamTypes[stream].volume = value;
775
776 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800777 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700778 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700779 }
780 } else {
781 thread->setStreamVolume(stream, value);
782 }
783
784 return NO_ERROR;
785}
786
Glenn Kastenfff6d712012-01-12 16:38:12 -0800787status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700788{
789 // check calling permissions
790 if (!settingsAllowed()) {
791 return PERMISSION_DENIED;
792 }
793
Glenn Kasten263709e2012-01-06 08:40:01 -0800794 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700795 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000796 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700797 return BAD_VALUE;
798 }
799
Eric Laurent93575202011-01-18 18:39:02 -0800800 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700801 mStreamTypes[stream].mute = muted;
802 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700803 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700804
805 return NO_ERROR;
806}
807
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800808float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700809{
Glenn Kasten263709e2012-01-06 08:40:01 -0800810 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700811 return 0.0f;
812 }
813
814 AutoMutex lock(mLock);
815 float volume;
816 if (output) {
817 PlaybackThread *thread = checkPlaybackThread_l(output);
818 if (thread == NULL) {
819 return 0.0f;
820 }
821 volume = thread->streamVolume(stream);
822 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800823 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700824 }
825
826 return volume;
827}
828
Glenn Kastenfff6d712012-01-12 16:38:12 -0800829bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700830{
Glenn Kasten263709e2012-01-06 08:40:01 -0800831 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700832 return true;
833 }
834
Glenn Kasten6637baa2012-01-09 09:40:36 -0800835 AutoMutex lock(mLock);
836 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700837}
838
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800839status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700840{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800841 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700842 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
843 // check calling permissions
844 if (!settingsAllowed()) {
845 return PERMISSION_DENIED;
846 }
847
Mathias Agopian65ab4712010-07-14 17:59:35 -0700848 // ioHandle == 0 means the parameters are global to the audio hardware interface
849 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700850 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700851 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800852 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700853 AutoMutex lock(mHardwareLock);
854 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
855 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
856 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
857 status_t result = dev->set_parameters(dev, keyValuePairs.string());
858 final_result = result ?: final_result;
859 }
860 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800861 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700862 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
863 AudioParameter param = AudioParameter(keyValuePairs);
864 String8 value;
865 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700866 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
867 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700868 for (size_t i = 0; i < mRecordThreads.size(); i++) {
869 sp<RecordThread> thread = mRecordThreads.valueAt(i);
870 RecordThread::RecordTrack *track = thread->track();
871 if (track != NULL) {
872 audio_devices_t device = (audio_devices_t)(
873 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700874 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700875 thread->setEffectSuspended(FX_IID_AEC,
876 suspend,
877 track->sessionId());
878 thread->setEffectSuspended(FX_IID_NS,
879 suspend,
880 track->sessionId());
881 }
882 }
Eric Laurentbee53372011-08-29 12:42:48 -0700883 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700884 }
885 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700886 String8 screenState;
887 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
888 bool isOff = screenState == "off";
889 if (isOff != (gScreenState & 1)) {
890 gScreenState = ((gScreenState & ~1) + 2) | isOff;
891 }
892 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700893 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700894 }
895
896 // hold a strong ref on thread in case closeOutput() or closeInput() is called
897 // and the thread is exited once the lock is released
898 sp<ThreadBase> thread;
899 {
900 Mutex::Autolock _l(mLock);
901 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -0700902 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700903 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800904 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700905 // indicate output device change to all input threads for pre processing
906 AudioParameter param = AudioParameter(keyValuePairs);
907 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700908 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
909 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700910 for (size_t i = 0; i < mRecordThreads.size(); i++) {
911 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
912 }
913 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700914 }
915 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800916 if (thread != 0) {
917 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700918 }
919 return BAD_VALUE;
920}
921
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800922String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700923{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800924// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700925// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
926
Eric Laurenta4c5a552012-03-29 10:12:40 -0700927 Mutex::Autolock _l(mLock);
928
Mathias Agopian65ab4712010-07-14 17:59:35 -0700929 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700930 String8 out_s8;
931
Dima Zavin799a70e2011-04-18 16:57:27 -0700932 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800933 char *s;
934 {
935 AutoMutex lock(mHardwareLock);
936 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700937 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800938 s = dev->get_parameters(dev, keys.string());
939 mHardwareStatus = AUDIO_HW_IDLE;
940 }
John Grossmanef7740b2012-02-09 11:28:36 -0800941 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700942 free(s);
943 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700944 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700945 }
946
Mathias Agopian65ab4712010-07-14 17:59:35 -0700947 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
948 if (playbackThread != NULL) {
949 return playbackThread->getParameters(keys);
950 }
951 RecordThread *recordThread = checkRecordThread_l(ioHandle);
952 if (recordThread != NULL) {
953 return recordThread->getParameters(keys);
954 }
955 return String8("");
956}
957
Glenn Kastendd8104c2012-07-02 12:42:44 -0700958size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
959 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700960{
Eric Laurenta1884f92011-08-23 08:25:03 -0700961 status_t ret = initCheck();
962 if (ret != NO_ERROR) {
963 return 0;
964 }
965
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800966 AutoMutex lock(mHardwareLock);
967 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700968 struct audio_config config = {
969 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -0700970 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700971 format: format,
972 };
973 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800974 mHardwareStatus = AUDIO_HW_IDLE;
975 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700976}
977
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800978unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700979{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700980 Mutex::Autolock _l(mLock);
981
982 RecordThread *recordThread = checkRecordThread_l(ioHandle);
983 if (recordThread != NULL) {
984 return recordThread->getInputFramesLost();
985 }
986 return 0;
987}
988
989status_t AudioFlinger::setVoiceVolume(float value)
990{
Eric Laurenta1884f92011-08-23 08:25:03 -0700991 status_t ret = initCheck();
992 if (ret != NO_ERROR) {
993 return ret;
994 }
995
Mathias Agopian65ab4712010-07-14 17:59:35 -0700996 // check calling permissions
997 if (!settingsAllowed()) {
998 return PERMISSION_DENIED;
999 }
1000
1001 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001002 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -07001003 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001004 mHardwareStatus = AUDIO_HW_IDLE;
1005
1006 return ret;
1007}
1008
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001009status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1010 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001011{
1012 status_t status;
1013
1014 Mutex::Autolock _l(mLock);
1015
1016 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1017 if (playbackThread != NULL) {
1018 return playbackThread->getRenderPosition(halFrames, dspFrames);
1019 }
1020
1021 return BAD_VALUE;
1022}
1023
1024void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1025{
1026
1027 Mutex::Autolock _l(mLock);
1028
Glenn Kastenbb001922012-02-03 11:10:26 -08001029 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001030 if (mNotificationClients.indexOfKey(pid) < 0) {
1031 sp<NotificationClient> notificationClient = new NotificationClient(this,
1032 client,
1033 pid);
Steve Block3856b092011-10-20 11:56:00 +01001034 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001035
1036 mNotificationClients.add(pid, notificationClient);
1037
1038 sp<IBinder> binder = client->asBinder();
1039 binder->linkToDeath(notificationClient);
1040
1041 // the config change is always sent from playback or record threads to avoid deadlock
1042 // with AudioSystem::gLock
1043 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1044 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1045 }
1046
1047 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1048 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1049 }
1050 }
1051}
1052
1053void AudioFlinger::removeNotificationClient(pid_t pid)
1054{
1055 Mutex::Autolock _l(mLock);
1056
Glenn Kastena3b09252012-01-20 09:19:01 -08001057 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001058
Steve Block3856b092011-10-20 11:56:00 +01001059 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001060 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001061 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001062 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001063 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001064 ALOGV(" pid %d @ %d", ref->mPid, i);
1065 if (ref->mPid == pid) {
1066 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001067 mAudioSessionRefs.removeAt(i);
1068 delete ref;
1069 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001070 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001071 } else {
1072 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001073 }
1074 }
1075 if (removed) {
1076 purgeStaleEffects_l();
1077 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078}
1079
1080// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001081void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001082{
1083 size_t size = mNotificationClients.size();
1084 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001085 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1086 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001087 }
1088}
1089
1090// removeClient_l() must be called with AudioFlinger::mLock held
1091void AudioFlinger::removeClient_l(pid_t pid)
1092{
Steve Block3856b092011-10-20 11:56:00 +01001093 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001094 mClients.removeItem(pid);
1095}
1096
Eric Laurent717e1282012-06-29 16:36:52 -07001097// getEffectThread_l() must be called with AudioFlinger::mLock held
1098sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1099{
1100 sp<PlaybackThread> thread;
1101
1102 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1103 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1104 ALOG_ASSERT(thread == 0);
1105 thread = mPlaybackThreads.valueAt(i);
1106 }
1107 }
1108
1109 return thread;
1110}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001111
1112// ----------------------------------------------------------------------------
1113
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001114AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1115 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001116 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001117 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001118 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001119 // mChannelMask
1120 mChannelCount(0),
1121 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1122 mParamStatus(NO_ERROR),
Glenn Kasten94479fd2012-07-09 15:39:54 -07001123 mStandby(false), mDevice((audio_devices_t) device), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001124 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001125{
1126}
1127
1128AudioFlinger::ThreadBase::~ThreadBase()
1129{
1130 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001131 // do not lock the mutex in destructor
1132 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001133 if (mPowerManager != 0) {
1134 sp<IBinder> binder = mPowerManager->asBinder();
1135 binder->unlinkToDeath(mDeathRecipient);
1136 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001137}
1138
1139void AudioFlinger::ThreadBase::exit()
1140{
Steve Block3856b092011-10-20 11:56:00 +01001141 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001142 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001143 // This lock prevents the following race in thread (uniprocessor for illustration):
1144 // if (!exitPending()) {
1145 // // context switch from here to exit()
1146 // // exit() calls requestExit(), what exitPending() observes
1147 // // exit() calls signal(), which is dropped since no waiters
1148 // // context switch back from exit() to here
1149 // mWaitWorkCV.wait(...);
1150 // // now thread is hung
1151 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001152 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001153 requestExit();
1154 mWaitWorkCV.signal();
1155 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001156 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1157 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001158 requestExitAndWait();
1159}
1160
Mathias Agopian65ab4712010-07-14 17:59:35 -07001161status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1162{
1163 status_t status;
1164
Steve Block3856b092011-10-20 11:56:00 +01001165 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001166 Mutex::Autolock _l(mLock);
1167
1168 mNewParameters.add(keyValuePairs);
1169 mWaitWorkCV.signal();
1170 // wait condition with timeout in case the thread loop has exited
1171 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001172 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001173 status = mParamStatus;
1174 mWaitWorkCV.signal();
1175 } else {
1176 status = TIMED_OUT;
1177 }
1178 return status;
1179}
1180
1181void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1182{
1183 Mutex::Autolock _l(mLock);
1184 sendConfigEvent_l(event, param);
1185}
1186
1187// sendConfigEvent_l() must be called with ThreadBase::mLock held
1188void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1189{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001190 ConfigEvent configEvent;
1191 configEvent.mEvent = event;
1192 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001193 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001194 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001195 mWaitWorkCV.signal();
1196}
1197
1198void AudioFlinger::ThreadBase::processConfigEvents()
1199{
1200 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001201 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001202 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001203 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001204 mConfigEvents.removeAt(0);
1205 // release mLock before locking AudioFlinger mLock: lock order is always
1206 // AudioFlinger then ThreadBase to avoid cross deadlock
1207 mLock.unlock();
1208 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001209 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001210 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001211 mLock.lock();
1212 }
1213 mLock.unlock();
1214}
1215
1216status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1217{
1218 const size_t SIZE = 256;
1219 char buffer[SIZE];
1220 String8 result;
1221
1222 bool locked = tryLock(mLock);
1223 if (!locked) {
1224 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1225 write(fd, buffer, strlen(buffer));
1226 }
1227
Eric Laurent612bbb52012-03-14 15:03:26 -07001228 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1229 result.append(buffer);
1230 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1231 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001232 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1233 result.append(buffer);
1234 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1235 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001236 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1237 result.append(buffer);
1238 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001239 result.append(buffer);
1240 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1241 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001242 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1243 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001244 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1245 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001246 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001247 result.append(buffer);
1248
1249 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1250 result.append(buffer);
1251 result.append(" Index Command");
1252 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1253 snprintf(buffer, SIZE, "\n %02d ", i);
1254 result.append(buffer);
1255 result.append(mNewParameters[i]);
1256 }
1257
1258 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1259 result.append(buffer);
1260 snprintf(buffer, SIZE, " Index event param\n");
1261 result.append(buffer);
1262 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001263 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001264 result.append(buffer);
1265 }
1266 result.append("\n");
1267
1268 write(fd, result.string(), result.size());
1269
1270 if (locked) {
1271 mLock.unlock();
1272 }
1273 return NO_ERROR;
1274}
1275
Eric Laurent1d2bff02011-07-24 17:49:51 -07001276status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1277{
1278 const size_t SIZE = 256;
1279 char buffer[SIZE];
1280 String8 result;
1281
1282 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1283 write(fd, buffer, strlen(buffer));
1284
1285 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1286 sp<EffectChain> chain = mEffectChains[i];
1287 if (chain != 0) {
1288 chain->dump(fd, args);
1289 }
1290 }
1291 return NO_ERROR;
1292}
1293
Eric Laurentfeb0db62011-07-22 09:04:31 -07001294void AudioFlinger::ThreadBase::acquireWakeLock()
1295{
1296 Mutex::Autolock _l(mLock);
1297 acquireWakeLock_l();
1298}
1299
1300void AudioFlinger::ThreadBase::acquireWakeLock_l()
1301{
1302 if (mPowerManager == 0) {
1303 // use checkService() to avoid blocking if power service is not up yet
1304 sp<IBinder> binder =
1305 defaultServiceManager()->checkService(String16("power"));
1306 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001307 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001308 } else {
1309 mPowerManager = interface_cast<IPowerManager>(binder);
1310 binder->linkToDeath(mDeathRecipient);
1311 }
1312 }
1313 if (mPowerManager != 0) {
1314 sp<IBinder> binder = new BBinder();
1315 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1316 binder,
1317 String16(mName));
1318 if (status == NO_ERROR) {
1319 mWakeLockToken = binder;
1320 }
Steve Block3856b092011-10-20 11:56:00 +01001321 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001322 }
1323}
1324
1325void AudioFlinger::ThreadBase::releaseWakeLock()
1326{
1327 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001328 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001329}
1330
1331void AudioFlinger::ThreadBase::releaseWakeLock_l()
1332{
1333 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001334 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001335 if (mPowerManager != 0) {
1336 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1337 }
1338 mWakeLockToken.clear();
1339 }
1340}
1341
1342void AudioFlinger::ThreadBase::clearPowerManager()
1343{
1344 Mutex::Autolock _l(mLock);
1345 releaseWakeLock_l();
1346 mPowerManager.clear();
1347}
1348
1349void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1350{
1351 sp<ThreadBase> thread = mThread.promote();
1352 if (thread != 0) {
1353 thread->clearPowerManager();
1354 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001355 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001356}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001357
Eric Laurent59255e42011-07-27 19:49:51 -07001358void AudioFlinger::ThreadBase::setEffectSuspended(
1359 const effect_uuid_t *type, bool suspend, int sessionId)
1360{
1361 Mutex::Autolock _l(mLock);
1362 setEffectSuspended_l(type, suspend, sessionId);
1363}
1364
1365void AudioFlinger::ThreadBase::setEffectSuspended_l(
1366 const effect_uuid_t *type, bool suspend, int sessionId)
1367{
Glenn Kasten090f0192012-01-30 13:00:02 -08001368 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001369 if (chain != 0) {
1370 if (type != NULL) {
1371 chain->setEffectSuspended_l(type, suspend);
1372 } else {
1373 chain->setEffectSuspendedAll_l(suspend);
1374 }
1375 }
1376
1377 updateSuspendedSessions_l(type, suspend, sessionId);
1378}
1379
1380void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1381{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001382 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001383 if (index < 0) {
1384 return;
1385 }
1386
1387 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1388 mSuspendedSessions.editValueAt(index);
1389
1390 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001391 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001392 for (int j = 0; j < desc->mRefCount; j++) {
1393 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1394 chain->setEffectSuspendedAll_l(true);
1395 } else {
Steve Block3856b092011-10-20 11:56:00 +01001396 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001397 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001398 chain->setEffectSuspended_l(&desc->mType, true);
1399 }
1400 }
1401 }
1402}
1403
Eric Laurent59255e42011-07-27 19:49:51 -07001404void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1405 bool suspend,
1406 int sessionId)
1407{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001408 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001409
1410 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1411
1412 if (suspend) {
1413 if (index >= 0) {
1414 sessionEffects = mSuspendedSessions.editValueAt(index);
1415 } else {
1416 mSuspendedSessions.add(sessionId, sessionEffects);
1417 }
1418 } else {
1419 if (index < 0) {
1420 return;
1421 }
1422 sessionEffects = mSuspendedSessions.editValueAt(index);
1423 }
1424
1425
1426 int key = EffectChain::kKeyForSuspendAll;
1427 if (type != NULL) {
1428 key = type->timeLow;
1429 }
1430 index = sessionEffects.indexOfKey(key);
1431
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001432 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001433 if (suspend) {
1434 if (index >= 0) {
1435 desc = sessionEffects.valueAt(index);
1436 } else {
1437 desc = new SuspendedSessionDesc();
1438 if (type != NULL) {
1439 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1440 }
1441 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001442 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001443 }
1444 desc->mRefCount++;
1445 } else {
1446 if (index < 0) {
1447 return;
1448 }
1449 desc = sessionEffects.valueAt(index);
1450 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001451 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001452 sessionEffects.removeItemsAt(index);
1453 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001454 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001455 sessionId);
1456 mSuspendedSessions.removeItem(sessionId);
1457 }
1458 }
1459 }
1460 if (!sessionEffects.isEmpty()) {
1461 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1462 }
1463}
1464
1465void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1466 bool enabled,
1467 int sessionId)
1468{
1469 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001470 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1471}
Eric Laurent59255e42011-07-27 19:49:51 -07001472
Eric Laurenta85a74a2011-10-19 11:44:54 -07001473void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1474 bool enabled,
1475 int sessionId)
1476{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001477 if (mType != RECORD) {
1478 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1479 // another session. This gives the priority to well behaved effect control panels
1480 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001481 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1482 // global effects
1483 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001484 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1485 }
1486 }
Eric Laurent59255e42011-07-27 19:49:51 -07001487
1488 sp<EffectChain> chain = getEffectChain_l(sessionId);
1489 if (chain != 0) {
1490 chain->checkSuspendOnEffectEnabled(effect, enabled);
1491 }
1492}
1493
Mathias Agopian65ab4712010-07-14 17:59:35 -07001494// ----------------------------------------------------------------------------
1495
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001496AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1497 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001498 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001499 uint32_t device,
1500 type_t type)
1501 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001502 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1503 // Assumes constructor is called by AudioFlinger with it's mLock held,
1504 // but it would be safer to explicitly pass initial masterMute as parameter
1505 mMasterMute(audioFlinger->masterMute_l()),
1506 // mStreamTypes[] initialized in constructor body
1507 mOutput(output),
1508 // Assumes constructor is called by AudioFlinger with it's mLock held,
1509 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001510 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001511 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001512 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001513 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001514 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001515 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001516 // index 0 is reserved for normal mixer's submix
1517 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001518{
Glenn Kasten480b4682012-02-28 12:30:08 -08001519 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001520
Mathias Agopian65ab4712010-07-14 17:59:35 -07001521 readOutputParameters();
1522
Glenn Kasten263709e2012-01-06 08:40:01 -08001523 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001524 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1525 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1526 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001527 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1528 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001529 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001530 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1531 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001532}
1533
1534AudioFlinger::PlaybackThread::~PlaybackThread()
1535{
1536 delete [] mMixBuffer;
1537}
1538
1539status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1540{
1541 dumpInternals(fd, args);
1542 dumpTracks(fd, args);
1543 dumpEffectChains(fd, args);
1544 return NO_ERROR;
1545}
1546
1547status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1548{
1549 const size_t SIZE = 256;
1550 char buffer[SIZE];
1551 String8 result;
1552
Glenn Kasten58912562012-04-03 10:45:00 -07001553 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1554 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1555 const stream_type_t *st = &mStreamTypes[i];
1556 if (i > 0) {
1557 result.appendFormat(", ");
1558 }
1559 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1560 if (st->mute) {
1561 result.append("M");
1562 }
1563 }
1564 result.append("\n");
1565 write(fd, result.string(), result.length());
1566 result.clear();
1567
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1569 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001570 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001571 for (size_t i = 0; i < mTracks.size(); ++i) {
1572 sp<Track> track = mTracks[i];
1573 if (track != 0) {
1574 track->dump(buffer, SIZE);
1575 result.append(buffer);
1576 }
1577 }
1578
1579 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1580 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001581 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001582 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001583 sp<Track> track = mActiveTracks[i].promote();
1584 if (track != 0) {
1585 track->dump(buffer, SIZE);
1586 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001587 }
1588 }
1589 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001590
1591 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1592 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1593 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1594 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1595
Mathias Agopian65ab4712010-07-14 17:59:35 -07001596 return NO_ERROR;
1597}
1598
Mathias Agopian65ab4712010-07-14 17:59:35 -07001599status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1600{
1601 const size_t SIZE = 256;
1602 char buffer[SIZE];
1603 String8 result;
1604
1605 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1606 result.append(buffer);
1607 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1608 result.append(buffer);
1609 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1610 result.append(buffer);
1611 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1612 result.append(buffer);
1613 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1614 result.append(buffer);
1615 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1616 result.append(buffer);
1617 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1618 result.append(buffer);
1619 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001620 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001621
1622 dumpBase(fd, args);
1623
1624 return NO_ERROR;
1625}
1626
1627// Thread virtuals
1628status_t AudioFlinger::PlaybackThread::readyToRun()
1629{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001630 status_t status = initCheck();
1631 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001632 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001633 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001634 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001635 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001636 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001637}
1638
1639void AudioFlinger::PlaybackThread::onFirstRef()
1640{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001641 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001642}
1643
1644// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001645sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001646 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001647 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001648 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001649 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001650 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001651 int frameCount,
1652 const sp<IMemory>& sharedBuffer,
1653 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001654 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001655 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001656 status_t *status)
1657{
1658 sp<Track> track;
1659 status_t lStatus;
1660
Glenn Kasten73d22752012-03-19 13:38:30 -07001661 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1662
1663 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001664 if (flags & IAudioFlinger::TRACK_FAST) {
1665 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001666 // not timed
1667 (!isTimed) &&
1668 // either of these use cases:
1669 (
1670 // use case 1: shared buffer with any frame count
1671 (
1672 (sharedBuffer != 0)
1673 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001674 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001675 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001676 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001677 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001678 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001679 )
1680 ) &&
1681 // PCM data
1682 audio_is_linear_pcm(format) &&
1683 // mono or stereo
1684 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1685 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001686#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001687 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001688 (sampleRate == mSampleRate) &&
1689#endif
1690 // normal mixer has an associated fast mixer
1691 hasFastMixer() &&
1692 // there are sufficient fast track slots available
1693 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001694 // FIXME test that MixerThread for this fast track has a capable output HAL
1695 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001696 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001697 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1698 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001699 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001700 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001701 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001702 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001703 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001704 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten254af182012-07-03 14:59:05 -07001705 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001706 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1707 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1708 audio_is_linear_pcm(format),
1709 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001710 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001711 // For compatibility with AudioTrack calculation, buffer depth is forced
1712 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1713 // This is probably too conservative, but legacy application code may depend on it.
1714 // If you change this calculation, also review the start threshold which is related.
1715 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1716 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1717 if (minBufCount < 2) {
1718 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001719 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001720 int minFrameCount = mNormalFrameCount * minBufCount;
1721 if (frameCount < minFrameCount) {
1722 frameCount = minFrameCount;
1723 }
1724 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001725 }
1726
Mathias Agopian65ab4712010-07-14 17:59:35 -07001727 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001728 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1729 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001730 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001731 "for output %p with format %d",
1732 sampleRate, format, channelMask, mOutput, mFormat);
1733 lStatus = BAD_VALUE;
1734 goto Exit;
1735 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001736 }
1737 } else {
1738 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1739 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001740 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001741 lStatus = BAD_VALUE;
1742 goto Exit;
1743 }
1744 }
1745
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001746 lStatus = initCheck();
1747 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001748 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001749 goto Exit;
1750 }
1751
1752 { // scope for mLock
1753 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001754
1755 // all tracks in same audio session must share the same routing strategy otherwise
1756 // conflicts will happen when tracks are moved from one output to another by audio policy
1757 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001758 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001759 for (size_t i = 0; i < mTracks.size(); ++i) {
1760 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001761 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001762 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001763 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001764 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001765 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001766 lStatus = BAD_VALUE;
1767 goto Exit;
1768 }
1769 }
1770 }
1771
John Grossman4ff14ba2012-02-08 16:37:41 -08001772 if (!isTimed) {
1773 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001774 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001775 } else {
1776 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1777 channelMask, frameCount, sharedBuffer, sessionId);
1778 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001779 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001780 lStatus = NO_MEMORY;
1781 goto Exit;
1782 }
1783 mTracks.add(track);
1784
1785 sp<EffectChain> chain = getEffectChain_l(sessionId);
1786 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001787 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001788 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001789 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001790 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001791 }
1792 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001793
Glenn Kasten3acbd052012-02-28 10:39:56 -08001794 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1795 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1796 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1797 // so ask activity manager to do this on our behalf
1798 int err = requestPriority(callingPid, tid, 1);
1799 if (err != 0) {
1800 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1801 1, callingPid, tid, err);
1802 }
1803 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001804
Mathias Agopian65ab4712010-07-14 17:59:35 -07001805 lStatus = NO_ERROR;
1806
1807Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001808 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001809 *status = lStatus;
1810 }
1811 return track;
1812}
1813
Eric Laurente737cda2012-05-22 18:55:44 -07001814uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1815{
1816 if (mFastMixer != NULL) {
1817 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1818 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1819 }
1820 return latency;
1821}
1822
1823uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1824{
1825 return latency;
1826}
1827
Mathias Agopian65ab4712010-07-14 17:59:35 -07001828uint32_t AudioFlinger::PlaybackThread::latency() const
1829{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001830 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001831 return latency_l();
1832}
1833uint32_t AudioFlinger::PlaybackThread::latency_l() const
1834{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001835 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001836 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001837 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001838 return 0;
1839 }
1840}
1841
Glenn Kasten6637baa2012-01-09 09:40:36 -08001842void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001843{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001844 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001845 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001846}
1847
Glenn Kasten6637baa2012-01-09 09:40:36 -08001848void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001849{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001850 Mutex::Autolock _l(mLock);
1851 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001852}
1853
Glenn Kasten6637baa2012-01-09 09:40:36 -08001854void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001855{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001856 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001857 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001858}
1859
Glenn Kasten6637baa2012-01-09 09:40:36 -08001860void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001862 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001863 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001864}
1865
Glenn Kastenfff6d712012-01-12 16:38:12 -08001866float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001867{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001868 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001869 return mStreamTypes[stream].volume;
1870}
1871
Mathias Agopian65ab4712010-07-14 17:59:35 -07001872// addTrack_l() must be called with ThreadBase::mLock held
1873status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1874{
1875 status_t status = ALREADY_EXISTS;
1876
1877 // set retry count for buffer fill
1878 track->mRetryCount = kMaxTrackStartupRetries;
1879 if (mActiveTracks.indexOf(track) < 0) {
1880 // the track is newly added, make sure it fills up all its
1881 // buffers before playing. This is to ensure the client will
1882 // effectively get the latency it requested.
1883 track->mFillingUpStatus = Track::FS_FILLING;
1884 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001885 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001886 mActiveTracks.add(track);
1887 if (track->mainBuffer() != mMixBuffer) {
1888 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1889 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001890 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001891 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001892 }
1893 }
1894
1895 status = NO_ERROR;
1896 }
1897
Steve Block3856b092011-10-20 11:56:00 +01001898 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001899 mWaitWorkCV.broadcast();
1900
1901 return status;
1902}
1903
1904// destroyTrack_l() must be called with ThreadBase::mLock held
1905void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1906{
1907 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001908 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001909 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001910 removeTrack_l(track);
1911 }
1912}
1913
1914void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1915{
Eric Laurent29864602012-05-08 18:57:51 -07001916 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001917 mTracks.remove(track);
1918 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001919 // redundant as track is about to be destroyed, for dumpsys only
1920 track->mName = -1;
1921 if (track->isFastTrack()) {
1922 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001923 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001924 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1925 mFastTrackAvailMask |= 1 << index;
1926 // redundant as track is about to be destroyed, for dumpsys only
1927 track->mFastIndex = -1;
1928 }
Eric Laurentb469b942011-05-09 12:09:06 -07001929 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1930 if (chain != 0) {
1931 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001932 }
1933}
1934
1935String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1936{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001937 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001938 char *s;
1939
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001940 Mutex::Autolock _l(mLock);
1941 if (initCheck() != NO_ERROR) {
1942 return out_s8;
1943 }
1944
Dima Zavin799a70e2011-04-18 16:57:27 -07001945 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001946 out_s8 = String8(s);
1947 free(s);
1948 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001949}
1950
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001951// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001952void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1953 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001954 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001955
Steve Block3856b092011-10-20 11:56:00 +01001956 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001957
1958 switch (event) {
1959 case AudioSystem::OUTPUT_OPENED:
1960 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001961 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001962 desc.samplingRate = mSampleRate;
1963 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001964 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001965 desc.latency = latency();
1966 param2 = &desc;
1967 break;
1968
1969 case AudioSystem::STREAM_CONFIG_CHANGED:
1970 param2 = &param;
1971 case AudioSystem::OUTPUT_CLOSED:
1972 default:
1973 break;
1974 }
1975 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1976}
1977
1978void AudioFlinger::PlaybackThread::readOutputParameters()
1979{
Dima Zavin799a70e2011-04-18 16:57:27 -07001980 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001981 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1982 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001983 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001984 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001985 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001986 if (mFrameCount & 15) {
1987 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1988 mFrameCount);
1989 }
1990
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001991 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07001992 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001993 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07001994 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07001995 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1996 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1997 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1998 maxNormalFrameCount = maxNormalFrameCount & ~15;
1999 if (maxNormalFrameCount < minNormalFrameCount) {
2000 maxNormalFrameCount = minNormalFrameCount;
2001 }
2002 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2003 if (multiplier <= 1.0) {
2004 multiplier = 1.0;
2005 } else if (multiplier <= 2.0) {
2006 if (2 * mFrameCount <= maxNormalFrameCount) {
2007 multiplier = 2.0;
2008 } else {
2009 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2010 }
2011 } else {
2012 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2013 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2014 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2015 // FIXME this rounding up should not be done if no HAL SRC
2016 uint32_t truncMult = (uint32_t) multiplier;
2017 if ((truncMult & 1)) {
2018 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2019 ++truncMult;
2020 }
2021 }
2022 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002023 }
Glenn Kasten58912562012-04-03 10:45:00 -07002024 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002025 mNormalFrameCount = multiplier * mFrameCount;
2026 // round up to nearest 16 frames to satisfy AudioMixer
2027 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002028 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002029
Glenn Kastene9dd0172012-01-27 18:08:45 -08002030 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002031 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2032 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002033
Eric Laurentde070132010-07-13 04:45:46 -07002034 // force reconfiguration of effect chains and engines to take new buffer size and audio
2035 // parameters into account
2036 // Note that mLock is not held when readOutputParameters() is called from the constructor
2037 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2038 // matter.
2039 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2040 Vector< sp<EffectChain> > effectChains = mEffectChains;
2041 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002042 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002043 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002044}
2045
Eric Laurente737cda2012-05-22 18:55:44 -07002046
Mathias Agopian65ab4712010-07-14 17:59:35 -07002047status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2048{
Glenn Kastena0d68332012-01-27 16:47:15 -08002049 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002050 return BAD_VALUE;
2051 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002052 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002053 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002054 return INVALID_OPERATION;
2055 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002056 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002057
Dima Zavin799a70e2011-04-18 16:57:27 -07002058 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002059}
2060
Eric Laurent39e94f82010-07-28 01:32:47 -07002061uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002062{
2063 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002064 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002065 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002066 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002067 }
2068
2069 for (size_t i = 0; i < mTracks.size(); ++i) {
2070 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002071 if (sessionId == track->sessionId() &&
2072 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002073 result |= TRACK_SESSION;
2074 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002075 }
2076 }
2077
Eric Laurent39e94f82010-07-28 01:32:47 -07002078 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002079}
2080
Eric Laurentde070132010-07-13 04:45:46 -07002081uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2082{
Dima Zavinfce7a472011-04-19 22:30:36 -07002083 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002084 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002085 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2086 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002087 }
2088 for (size_t i = 0; i < mTracks.size(); i++) {
2089 sp<Track> track = mTracks[i];
2090 if (sessionId == track->sessionId() &&
2091 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002092 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002093 }
2094 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002095 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002096}
2097
Mathias Agopian65ab4712010-07-14 17:59:35 -07002098
Glenn Kastenaed850d2012-01-26 09:46:34 -08002099AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002100{
2101 Mutex::Autolock _l(mLock);
2102 return mOutput;
2103}
2104
2105AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2106{
2107 Mutex::Autolock _l(mLock);
2108 AudioStreamOut *output = mOutput;
2109 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002110 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2111 // must push a NULL and wait for ack
2112 mOutputSink.clear();
2113 mPipeSink.clear();
2114 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002115 return output;
2116}
2117
2118// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002119audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002120{
2121 if (mOutput == NULL) {
2122 return NULL;
2123 }
2124 return &mOutput->stream->common;
2125}
2126
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002127uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002128{
Eric Laurentab9071b2012-06-04 13:45:29 -07002129 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002130}
2131
Eric Laurenta011e352012-03-29 15:51:43 -07002132status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2133{
2134 if (!isValidSyncEvent(event)) {
2135 return BAD_VALUE;
2136 }
2137
2138 Mutex::Autolock _l(mLock);
2139
2140 for (size_t i = 0; i < mTracks.size(); ++i) {
2141 sp<Track> track = mTracks[i];
2142 if (event->triggerSession() == track->sessionId()) {
2143 track->setSyncEvent(event);
2144 return NO_ERROR;
2145 }
2146 }
2147
2148 return NAME_NOT_FOUND;
2149}
2150
2151bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2152{
2153 switch (event->type()) {
2154 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2155 return true;
2156 default:
2157 break;
2158 }
2159 return false;
2160}
2161
Eric Laurent44a957f2012-05-15 15:26:05 -07002162void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2163{
2164 size_t count = tracksToRemove.size();
2165 if (CC_UNLIKELY(count)) {
2166 for (size_t i = 0 ; i < count ; i++) {
2167 const sp<Track>& track = tracksToRemove.itemAt(i);
2168 if ((track->sharedBuffer() != 0) &&
2169 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2170 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2171 }
2172 }
2173 }
2174
2175}
2176
Mathias Agopian65ab4712010-07-14 17:59:35 -07002177// ----------------------------------------------------------------------------
2178
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002179AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002180 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002181 : PlaybackThread(audioFlinger, output, id, device, type),
2182 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002183 // mFastMixer below
2184 mFastMixerFutex(0)
2185 // mOutputSink below
2186 // mPipeSink below
2187 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002188{
Glenn Kasten58912562012-04-03 10:45:00 -07002189 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002190 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002191 "mFrameCount=%d, mNormalFrameCount=%d",
2192 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2193 mNormalFrameCount);
2194 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2195
Mathias Agopian65ab4712010-07-14 17:59:35 -07002196 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002197 if (mChannelCount != FCC_2) {
2198 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002199 }
Glenn Kasten58912562012-04-03 10:45:00 -07002200
2201 // create an NBAIO sink for the HAL output stream, and negotiate
2202 mOutputSink = new AudioStreamOutSink(output->stream);
2203 size_t numCounterOffers = 0;
2204 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2205 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2206 ALOG_ASSERT(index == 0);
2207
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002208 // initialize fast mixer depending on configuration
2209 bool initFastMixer;
2210 switch (kUseFastMixer) {
2211 case FastMixer_Never:
2212 initFastMixer = false;
2213 break;
2214 case FastMixer_Always:
2215 initFastMixer = true;
2216 break;
2217 case FastMixer_Static:
2218 case FastMixer_Dynamic:
2219 initFastMixer = mFrameCount < mNormalFrameCount;
2220 break;
2221 }
2222 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002223
2224 // create a MonoPipe to connect our submix to FastMixer
2225 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002226 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2227 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2228 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2229 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002230 const NBAIO_Format offers[1] = {format};
2231 size_t numCounterOffers = 0;
2232 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2233 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002234 monoPipe->setAvgFrames((mScreenState & 1) ?
2235 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002236 mPipeSink = monoPipe;
2237
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002238#ifdef TEE_SINK_FRAMES
2239 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2240 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2241 numCounterOffers = 0;
2242 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2243 ALOG_ASSERT(index == 0);
2244 mTeeSink = teeSink;
2245 PipeReader *teeSource = new PipeReader(*teeSink);
2246 numCounterOffers = 0;
2247 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2248 ALOG_ASSERT(index == 0);
2249 mTeeSource = teeSource;
2250#endif
2251
Glenn Kasten58912562012-04-03 10:45:00 -07002252 // create fast mixer and configure it initially with just one fast track for our submix
2253 mFastMixer = new FastMixer();
2254 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002255#ifdef STATE_QUEUE_DUMP
2256 sq->setObserverDump(&mStateQueueObserverDump);
2257 sq->setMutatorDump(&mStateQueueMutatorDump);
2258#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002259 FastMixerState *state = sq->begin();
2260 FastTrack *fastTrack = &state->mFastTracks[0];
2261 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2262 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2263 fastTrack->mVolumeProvider = NULL;
2264 fastTrack->mGeneration++;
2265 state->mFastTracksGen++;
2266 state->mTrackMask = 1;
2267 // fast mixer will use the HAL output sink
2268 state->mOutputSink = mOutputSink.get();
2269 state->mOutputSinkGen++;
2270 state->mFrameCount = mFrameCount;
2271 state->mCommand = FastMixerState::COLD_IDLE;
2272 // already done in constructor initialization list
2273 //mFastMixerFutex = 0;
2274 state->mColdFutexAddr = &mFastMixerFutex;
2275 state->mColdGen++;
2276 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002277 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002278 sq->end();
2279 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2280
2281 // start the fast mixer
2282 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002283 pid_t tid = mFastMixer->getTid();
2284 int err = requestPriority(getpid_cached, tid, 2);
2285 if (err != 0) {
2286 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2287 2, getpid_cached, tid, err);
2288 }
Glenn Kasten58912562012-04-03 10:45:00 -07002289
Glenn Kastenc15d6652012-05-30 14:52:57 -07002290#ifdef AUDIO_WATCHDOG
2291 // create and start the watchdog
2292 mAudioWatchdog = new AudioWatchdog();
2293 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2294 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2295 tid = mAudioWatchdog->getTid();
2296 err = requestPriority(getpid_cached, tid, 1);
2297 if (err != 0) {
2298 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2299 1, getpid_cached, tid, err);
2300 }
2301#endif
2302
Glenn Kasten58912562012-04-03 10:45:00 -07002303 } else {
2304 mFastMixer = NULL;
2305 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002306
2307 switch (kUseFastMixer) {
2308 case FastMixer_Never:
2309 case FastMixer_Dynamic:
2310 mNormalSink = mOutputSink;
2311 break;
2312 case FastMixer_Always:
2313 mNormalSink = mPipeSink;
2314 break;
2315 case FastMixer_Static:
2316 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2317 break;
2318 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002319}
2320
2321AudioFlinger::MixerThread::~MixerThread()
2322{
Glenn Kasten58912562012-04-03 10:45:00 -07002323 if (mFastMixer != NULL) {
2324 FastMixerStateQueue *sq = mFastMixer->sq();
2325 FastMixerState *state = sq->begin();
2326 if (state->mCommand == FastMixerState::COLD_IDLE) {
2327 int32_t old = android_atomic_inc(&mFastMixerFutex);
2328 if (old == -1) {
2329 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2330 }
2331 }
2332 state->mCommand = FastMixerState::EXIT;
2333 sq->end();
2334 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2335 mFastMixer->join();
2336 // Though the fast mixer thread has exited, it's state queue is still valid.
2337 // We'll use that extract the final state which contains one remaining fast track
2338 // corresponding to our sub-mix.
2339 state = sq->begin();
2340 ALOG_ASSERT(state->mTrackMask == 1);
2341 FastTrack *fastTrack = &state->mFastTracks[0];
2342 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2343 delete fastTrack->mBufferProvider;
2344 sq->end(false /*didModify*/);
2345 delete mFastMixer;
Glenn Kastenc15d6652012-05-30 14:52:57 -07002346 if (mAudioWatchdog != 0) {
2347 mAudioWatchdog->requestExit();
2348 mAudioWatchdog->requestExitAndWait();
2349 mAudioWatchdog.clear();
2350 }
Glenn Kasten58912562012-04-03 10:45:00 -07002351 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002352 delete mAudioMixer;
2353}
2354
Glenn Kasten83efdd02012-02-24 07:21:32 -08002355class CpuStats {
2356public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002357 CpuStats();
2358 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002359#ifdef DEBUG_CPU_USAGE
2360private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002361 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2362 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2363
2364 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2365
2366 int mCpuNum; // thread's current CPU number
2367 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002368#endif
2369};
2370
Glenn Kasten190a46f2012-03-06 11:27:10 -08002371CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002372#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002373 : mCpuNum(-1), mCpukHz(-1)
2374#endif
2375{
2376}
2377
2378void CpuStats::sample(const String8 &title) {
2379#ifdef DEBUG_CPU_USAGE
2380 // get current thread's delta CPU time in wall clock ns
2381 double wcNs;
2382 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2383
2384 // record sample for wall clock statistics
2385 if (valid) {
2386 mWcStats.sample(wcNs);
2387 }
2388
2389 // get the current CPU number
2390 int cpuNum = sched_getcpu();
2391
2392 // get the current CPU frequency in kHz
2393 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2394
2395 // check if either CPU number or frequency changed
2396 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2397 mCpuNum = cpuNum;
2398 mCpukHz = cpukHz;
2399 // ignore sample for purposes of cycles
2400 valid = false;
2401 }
2402
2403 // if no change in CPU number or frequency, then record sample for cycle statistics
2404 if (valid && mCpukHz > 0) {
2405 double cycles = wcNs * cpukHz * 0.000001;
2406 mHzStats.sample(cycles);
2407 }
2408
2409 unsigned n = mWcStats.n();
2410 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002411 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002412 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002413 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2414 double perLoop = elapsed / (double) n;
2415 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002416 double perLoop1k = perLoop * 0.001;
2417 double mean = mWcStats.mean();
2418 double stddev = mWcStats.stddev();
2419 double minimum = mWcStats.minimum();
2420 double maximum = mWcStats.maximum();
2421 double meanCycles = mHzStats.mean();
2422 double stddevCycles = mHzStats.stddev();
2423 double minCycles = mHzStats.minimum();
2424 double maxCycles = mHzStats.maximum();
2425 mCpuUsage.resetElapsed();
2426 mWcStats.reset();
2427 mHzStats.reset();
2428 ALOGD("CPU usage for %s over past %.1f secs\n"
2429 " (%u mixer loops at %.1f mean ms per loop):\n"
2430 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2431 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2432 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2433 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002434 elapsed * .000000001, n, perLoop * .000001,
2435 mean * .001,
2436 stddev * .001,
2437 minimum * .001,
2438 maximum * .001,
2439 mean / perLoop100,
2440 stddev / perLoop100,
2441 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002442 maximum / perLoop100,
2443 meanCycles / perLoop1k,
2444 stddevCycles / perLoop1k,
2445 minCycles / perLoop1k,
2446 maxCycles / perLoop1k);
2447
Glenn Kasten83efdd02012-02-24 07:21:32 -08002448 }
2449 }
2450#endif
2451};
2452
Glenn Kasten37d825e2012-02-24 07:21:48 -08002453void AudioFlinger::PlaybackThread::checkSilentMode_l()
2454{
2455 if (!mMasterMute) {
2456 char value[PROPERTY_VALUE_MAX];
2457 if (property_get("ro.audio.silent", value, "0") > 0) {
2458 char *endptr;
2459 unsigned long ul = strtoul(value, &endptr, 0);
2460 if (*endptr == '\0' && ul != 0) {
2461 ALOGD("Silence is golden");
2462 // The setprop command will not allow a property to be changed after
2463 // the first time it is set, so we don't have to worry about un-muting.
2464 setMasterMute_l(true);
2465 }
2466 }
2467 }
2468}
2469
Glenn Kasten000f0e32012-03-01 17:10:56 -08002470bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002471{
2472 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002473
Glenn Kasten000f0e32012-03-01 17:10:56 -08002474 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002475
2476 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002477 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002478
Glenn Kasten000f0e32012-03-01 17:10:56 -08002479 // DUPLICATING
2480 // FIXME could this be made local to while loop?
2481 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002482
Glenn Kasten66fcab92012-02-24 14:59:21 -08002483 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002484 sleepTime = idleSleepTime;
2485
Glenn Kasten9f34a362012-03-20 16:46:41 -07002486 if (mType == MIXER) {
2487 sleepTimeShift = 0;
2488 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002489
Glenn Kasten83efdd02012-02-24 07:21:32 -08002490 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002491 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002492
Eric Laurentfeb0db62011-07-22 09:04:31 -07002493 acquireWakeLock();
2494
Mathias Agopian65ab4712010-07-14 17:59:35 -07002495 while (!exitPending())
2496 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002497 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002498
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002499 Vector< sp<EffectChain> > effectChains;
2500
Mathias Agopian65ab4712010-07-14 17:59:35 -07002501 processConfigEvents();
2502
Mathias Agopian65ab4712010-07-14 17:59:35 -07002503 { // scope for mLock
2504
2505 Mutex::Autolock _l(mLock);
2506
2507 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002508 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002509 }
2510
Glenn Kastenfa26a852012-03-06 11:28:04 -08002511 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002512
Mathias Agopian65ab4712010-07-14 17:59:35 -07002513 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002514 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002515 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002516 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002517
2518 threadLoop_standby();
2519
Mathias Agopian65ab4712010-07-14 17:59:35 -07002520 mStandby = true;
2521 mBytesWritten = 0;
2522 }
2523
Glenn Kasten3e074702012-02-28 18:40:35 -08002524 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002525 // we're about to wait, flush the binder command buffer
2526 IPCThreadState::self()->flushCommands();
2527
Glenn Kastenfa26a852012-03-06 11:28:04 -08002528 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002529
Mathias Agopian65ab4712010-07-14 17:59:35 -07002530 if (exitPending()) break;
2531
Eric Laurentfeb0db62011-07-22 09:04:31 -07002532 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002533 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002534 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002535 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002536 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002537 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002538
Eric Laurentda747442012-04-25 18:53:13 -07002539 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002540 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002541
Glenn Kasten37d825e2012-02-24 07:21:48 -08002542 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002543
Glenn Kasten000f0e32012-03-01 17:10:56 -08002544 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002545 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002546 if (mType == MIXER) {
2547 sleepTimeShift = 0;
2548 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002549
Mathias Agopian65ab4712010-07-14 17:59:35 -07002550 continue;
2551 }
2552 }
2553
Glenn Kasten81028042012-04-30 18:15:12 -07002554 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002555 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002556
2557 // prevent any changes in effect chain list and in each effect chain
2558 // during mixing and effect process as the audio buffers could be deleted
2559 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002560 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002561 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002562
Glenn Kastenfec279f2012-03-08 07:47:15 -08002563 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002564 threadLoop_mix();
2565 } else {
2566 threadLoop_sleepTime();
2567 }
2568
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002569 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002570 sleepTime = suspendSleepTimeUs();
2571 }
2572
2573 // only process effects if we're going to write
2574 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002575 for (size_t i = 0; i < effectChains.size(); i ++) {
2576 effectChains[i]->process_l();
2577 }
2578 }
2579
2580 // enable changes in effect chain
2581 unlockEffectChains(effectChains);
2582
2583 // sleepTime == 0 means we must write to audio hardware
2584 if (sleepTime == 0) {
2585
2586 threadLoop_write();
2587
2588if (mType == MIXER) {
2589 // write blocked detection
2590 nsecs_t now = systemTime();
2591 nsecs_t delta = now - mLastWriteTime;
2592 if (!mStandby && delta > maxPeriod) {
2593 mNumDelayedWrites++;
2594 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002595#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002596 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002597#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002598 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2599 ns2ms(delta), mNumDelayedWrites, this);
2600 lastWarning = now;
2601 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002602 }
2603}
2604
2605 mStandby = false;
2606 } else {
2607 usleep(sleepTime);
2608 }
2609
Glenn Kasten58912562012-04-03 10:45:00 -07002610 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002611 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002612 // same lock. This will also mutate and push a new fast mixer state.
2613 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002614 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002615
Glenn Kastenfa26a852012-03-06 11:28:04 -08002616 // FIXME I don't understand the need for this here;
2617 // it was in the original code but maybe the
2618 // assignment in saveOutputTracks() makes this unnecessary?
2619 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002620
2621 // Effect chains will be actually deleted here if they were removed from
2622 // mEffectChains list during mixing or effects processing
2623 effectChains.clear();
2624
2625 // FIXME Note that the above .clear() is no longer necessary since effectChains
2626 // is now local to this block, but will keep it for now (at least until merge done).
2627 }
2628
Glenn Kasten9f34a362012-03-20 16:46:41 -07002629 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2630 if (mType == MIXER || mType == DIRECT) {
2631 // put output stream into standby mode
2632 if (!mStandby) {
2633 mOutput->stream->common.standby(&mOutput->stream->common);
2634 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002635 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002636
2637 releaseWakeLock();
2638
2639 ALOGV("Thread %p type %d exiting", this, mType);
2640 return false;
2641}
2642
Glenn Kasten58912562012-04-03 10:45:00 -07002643void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2644{
Glenn Kasten58912562012-04-03 10:45:00 -07002645 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2646}
2647
2648void AudioFlinger::MixerThread::threadLoop_write()
2649{
2650 // FIXME we should only do one push per cycle; confirm this is true
2651 // Start the fast mixer if it's not already running
2652 if (mFastMixer != NULL) {
2653 FastMixerStateQueue *sq = mFastMixer->sq();
2654 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002655 if (state->mCommand != FastMixerState::MIX_WRITE &&
2656 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002657 if (state->mCommand == FastMixerState::COLD_IDLE) {
2658 int32_t old = android_atomic_inc(&mFastMixerFutex);
2659 if (old == -1) {
2660 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2661 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002662 if (mAudioWatchdog != 0) {
2663 mAudioWatchdog->resume();
2664 }
Glenn Kasten58912562012-04-03 10:45:00 -07002665 }
2666 state->mCommand = FastMixerState::MIX_WRITE;
2667 sq->end();
2668 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002669 if (kUseFastMixer == FastMixer_Dynamic) {
2670 mNormalSink = mPipeSink;
2671 }
Glenn Kasten58912562012-04-03 10:45:00 -07002672 } else {
2673 sq->end(false /*didModify*/);
2674 }
2675 }
2676 PlaybackThread::threadLoop_write();
2677}
2678
Glenn Kasten000f0e32012-03-01 17:10:56 -08002679// shared by MIXER and DIRECT, overridden by DUPLICATING
2680void AudioFlinger::PlaybackThread::threadLoop_write()
2681{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002682 // FIXME rewrite to reduce number of system calls
2683 mLastWriteTime = systemTime();
2684 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002685 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002686
Eric Laurent67c0a582012-05-01 19:31:12 -07002687 // If an NBAIO sink is present, use it to write the normal mixer's submix
2688 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002689#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002690 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002691#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002692 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002693#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002694 // update the setpoint when gScreenState changes
2695 uint32_t screenState = gScreenState;
2696 if (screenState != mScreenState) {
2697 mScreenState = screenState;
2698 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2699 if (pipe != NULL) {
2700 pipe->setAvgFrames((mScreenState & 1) ?
2701 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2702 }
2703 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002704 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002705#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002706 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002707#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002708 if (framesWritten > 0) {
2709 bytesWritten = framesWritten << mBitShift;
2710 } else {
2711 bytesWritten = framesWritten;
2712 }
2713 // otherwise use the HAL / AudioStreamOut directly
2714 } else {
2715 // Direct output thread.
2716 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002717 }
2718
Eric Laurent67c0a582012-05-01 19:31:12 -07002719 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002720 mNumWrites++;
2721 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002722}
2723
Glenn Kasten58912562012-04-03 10:45:00 -07002724void AudioFlinger::MixerThread::threadLoop_standby()
2725{
2726 // Idle the fast mixer if it's currently running
2727 if (mFastMixer != NULL) {
2728 FastMixerStateQueue *sq = mFastMixer->sq();
2729 FastMixerState *state = sq->begin();
2730 if (!(state->mCommand & FastMixerState::IDLE)) {
2731 state->mCommand = FastMixerState::COLD_IDLE;
2732 state->mColdFutexAddr = &mFastMixerFutex;
2733 state->mColdGen++;
2734 mFastMixerFutex = 0;
2735 sq->end();
2736 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2737 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002738 if (kUseFastMixer == FastMixer_Dynamic) {
2739 mNormalSink = mOutputSink;
2740 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002741 if (mAudioWatchdog != 0) {
2742 mAudioWatchdog->pause();
2743 }
Glenn Kasten58912562012-04-03 10:45:00 -07002744 } else {
2745 sq->end(false /*didModify*/);
2746 }
2747 }
2748 PlaybackThread::threadLoop_standby();
2749}
2750
Glenn Kasten000f0e32012-03-01 17:10:56 -08002751// shared by MIXER and DIRECT, overridden by DUPLICATING
2752void AudioFlinger::PlaybackThread::threadLoop_standby()
2753{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002754 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002755 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002756}
2757
2758void AudioFlinger::MixerThread::threadLoop_mix()
2759{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002760 // obtain the presentation timestamp of the next output buffer
2761 int64_t pts;
2762 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002763
Glenn Kasten952eeb22012-03-06 11:30:57 -08002764 if (NULL != mOutput->stream->get_next_write_timestamp) {
2765 status = mOutput->stream->get_next_write_timestamp(
2766 mOutput->stream, &pts);
2767 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002768
Glenn Kasten952eeb22012-03-06 11:30:57 -08002769 if (status != NO_ERROR) {
2770 pts = AudioBufferProvider::kInvalidPTS;
2771 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002772
Glenn Kasten952eeb22012-03-06 11:30:57 -08002773 // mix buffers...
2774 mAudioMixer->process(pts);
2775 // increase sleep time progressively when application underrun condition clears.
2776 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2777 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2778 // such that we would underrun the audio HAL.
2779 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2780 sleepTimeShift--;
2781 }
2782 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002783 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002784 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002785}
2786
2787void AudioFlinger::MixerThread::threadLoop_sleepTime()
2788{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002789 // If no tracks are ready, sleep once for the duration of an output
2790 // buffer size, then write 0s to the output
2791 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002792 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002793 sleepTime = activeSleepTime >> sleepTimeShift;
2794 if (sleepTime < kMinThreadSleepTimeUs) {
2795 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002796 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002797 // reduce sleep time in case of consecutive application underruns to avoid
2798 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2799 // duration we would end up writing less data than needed by the audio HAL if
2800 // the condition persists.
2801 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2802 sleepTimeShift++;
2803 }
2804 } else {
2805 sleepTime = idleSleepTime;
2806 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002807 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002808 memset (mMixBuffer, 0, mixBufferSize);
2809 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002810 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002811 }
2812 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002813}
2814
2815// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002816AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002817 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002818{
2819
Glenn Kasten29c23c32012-01-26 13:37:52 -08002820 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002821 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002822 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002823 size_t mixedTracks = 0;
2824 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002825 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002826 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002827 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002828
2829 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002830 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002831
Eric Laurent571d49c2010-08-11 05:20:11 -07002832 if (masterMute) {
2833 masterVolume = 0;
2834 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002835 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002836 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002837 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002838 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002839 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002840 masterVolume = (float)((v + (1 << 23)) >> 24);
2841 chain.clear();
2842 }
2843
Glenn Kasten288ed212012-04-25 17:52:27 -07002844 // prepare a new state to push
2845 FastMixerStateQueue *sq = NULL;
2846 FastMixerState *state = NULL;
2847 bool didModify = false;
2848 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2849 if (mFastMixer != NULL) {
2850 sq = mFastMixer->sq();
2851 state = sq->begin();
2852 }
2853
Mathias Agopian65ab4712010-07-14 17:59:35 -07002854 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002855 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002856 if (t == 0) continue;
2857
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002858 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002859 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002860
Glenn Kasten288ed212012-04-25 17:52:27 -07002861 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002862 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002863
2864 // It's theoretically possible (though unlikely) for a fast track to be created
2865 // and then removed within the same normal mix cycle. This is not a problem, as
2866 // the track never becomes active so it's fast mixer slot is never touched.
2867 // The converse, of removing an (active) track and then creating a new track
2868 // at the identical fast mixer slot within the same normal mix cycle,
2869 // is impossible because the slot isn't marked available until the end of each cycle.
2870 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002871 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2872 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002873 FastTrack *fastTrack = &state->mFastTracks[j];
2874
2875 // Determine whether the track is currently in underrun condition,
2876 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002877 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2878 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002879 uint32_t recentFull = (underruns.mBitFields.mFull -
2880 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2881 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2882 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2883 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2884 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2885 uint32_t recentUnderruns = recentPartial + recentEmpty;
2886 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002887 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002888 // or stopped which can occur when flush() is called while active
2889 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002890 track->mUnderrunCount += recentUnderruns;
2891 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002892
Glenn Kastend08f48c2012-05-01 18:14:02 -07002893 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002894 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002895 bool isActive = true;
2896 switch (track->mState) {
2897 case TrackBase::STOPPING_1:
2898 // track stays active in STOPPING_1 state until first underrun
2899 if (recentUnderruns > 0) {
2900 track->mState = TrackBase::STOPPING_2;
2901 }
2902 break;
2903 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002904 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002905 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002906 break;
2907 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002908 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002909 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002910 break;
2911 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002912 if (recentFull > 0 || recentPartial > 0) {
2913 // track has provided at least some frames recently: reset retry count
2914 track->mRetryCount = kMaxTrackRetries;
2915 }
2916 if (recentUnderruns == 0) {
2917 // no recent underruns: stay active
2918 break;
2919 }
2920 // there has recently been an underrun of some kind
2921 if (track->sharedBuffer() == 0) {
2922 // were any of the recent underruns "empty" (no frames available)?
2923 if (recentEmpty == 0) {
2924 // no, then ignore the partial underruns as they are allowed indefinitely
2925 break;
2926 }
2927 // there has recently been an "empty" underrun: decrement the retry counter
2928 if (--(track->mRetryCount) > 0) {
2929 break;
2930 }
2931 // indicate to client process that the track was disabled because of underrun;
2932 // it will then automatically call start() when data is available
2933 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2934 // remove from active list, but state remains ACTIVE [confusing but true]
2935 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002936 break;
2937 }
2938 // fall through
2939 case TrackBase::STOPPING_2:
2940 case TrackBase::PAUSED:
2941 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002942 case TrackBase::STOPPED:
2943 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07002944 // Check for presentation complete if track is inactive
2945 // We have consumed all the buffers of this track.
2946 // This would be incomplete if we auto-paused on underrun
2947 {
2948 size_t audioHALFrames =
2949 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2950 size_t framesWritten =
2951 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2952 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2953 // track stays in active list until presentation is complete
2954 break;
2955 }
2956 }
2957 if (track->isStopping_2()) {
2958 track->mState = TrackBase::STOPPED;
2959 }
2960 if (track->isStopped()) {
2961 // Can't reset directly, as fast mixer is still polling this track
2962 // track->reset();
2963 // So instead mark this track as needing to be reset after push with ack
2964 resetMask |= 1 << i;
2965 }
2966 isActive = false;
2967 break;
2968 case TrackBase::IDLE:
2969 default:
2970 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07002971 }
2972
2973 if (isActive) {
2974 // was it previously inactive?
2975 if (!(state->mTrackMask & (1 << j))) {
2976 ExtendedAudioBufferProvider *eabp = track;
2977 VolumeProvider *vp = track;
2978 fastTrack->mBufferProvider = eabp;
2979 fastTrack->mVolumeProvider = vp;
2980 fastTrack->mSampleRate = track->mSampleRate;
2981 fastTrack->mChannelMask = track->mChannelMask;
2982 fastTrack->mGeneration++;
2983 state->mTrackMask |= 1 << j;
2984 didModify = true;
2985 // no acknowledgement required for newly active tracks
2986 }
2987 // cache the combined master volume and stream type volume for fast mixer; this
2988 // lacks any synchronization or barrier so VolumeProvider may read a stale value
2989 track->mCachedVolume = track->isMuted() ?
2990 0 : masterVolume * mStreamTypes[track->streamType()].volume;
2991 ++fastTracks;
2992 } else {
2993 // was it previously active?
2994 if (state->mTrackMask & (1 << j)) {
2995 fastTrack->mBufferProvider = NULL;
2996 fastTrack->mGeneration++;
2997 state->mTrackMask &= ~(1 << j);
2998 didModify = true;
2999 // If any fast tracks were removed, we must wait for acknowledgement
3000 // because we're about to decrement the last sp<> on those tracks.
3001 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003002 } else {
3003 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003004 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003005 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003006 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003007 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003008 }
3009 continue;
3010 }
3011
3012 { // local variable scope to avoid goto warning
3013
Mathias Agopian65ab4712010-07-14 17:59:35 -07003014 audio_track_cblk_t* cblk = track->cblk();
3015
3016 // The first time a track is added we wait
3017 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003018 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003019 // make sure that we have enough frames to mix one full buffer.
3020 // enforce this condition only once to enable draining the buffer in case the client
3021 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003022 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003023 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003024 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003025 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003026 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003027 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003028 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003029 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003030 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003031 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003032 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003033 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003034 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3035 // the minimum track buffer size is normally twice the number of frames necessary
3036 // to fill one buffer and the resampler should not leave more than one buffer worth
3037 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003038 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003039 }
3040 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003041 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003042 !track->isPaused() && !track->isTerminated())
3043 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003044 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003045
3046 mixedTracks++;
3047
3048 // track->mainBuffer() != mMixBuffer means there is an effect chain
3049 // connected to the track
3050 chain.clear();
3051 if (track->mainBuffer() != mMixBuffer) {
3052 chain = getEffectChain_l(track->sessionId());
3053 // Delegate volume control to effect in track effect chain if needed
3054 if (chain != 0) {
3055 tracksWithEffect++;
3056 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003057 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003058 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003059 }
3060 }
3061
3062
3063 int param = AudioMixer::VOLUME;
3064 if (track->mFillingUpStatus == Track::FS_FILLED) {
3065 // no ramp for the first volume setting
3066 track->mFillingUpStatus = Track::FS_ACTIVE;
3067 if (track->mState == TrackBase::RESUMING) {
3068 track->mState = TrackBase::ACTIVE;
3069 param = AudioMixer::RAMP_VOLUME;
3070 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003071 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003072 } else if (cblk->server != 0) {
3073 // If the track is stopped before the first frame was mixed,
3074 // do not apply ramp
3075 param = AudioMixer::RAMP_VOLUME;
3076 }
3077
3078 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003079 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003080 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003081 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003082 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003083 if (track->isPausing()) {
3084 track->setPaused();
3085 }
3086 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003087
Mathias Agopian65ab4712010-07-14 17:59:35 -07003088 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003089 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003090 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003091 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003092 vl = vlr & 0xFFFF;
3093 vr = vlr >> 16;
3094 // track volumes come from shared memory, so can't be trusted and must be clamped
3095 if (vl > MAX_GAIN_INT) {
3096 ALOGV("Track left volume out of range: %04X", vl);
3097 vl = MAX_GAIN_INT;
3098 }
3099 if (vr > MAX_GAIN_INT) {
3100 ALOGV("Track right volume out of range: %04X", vr);
3101 vr = MAX_GAIN_INT;
3102 }
3103 // now apply the master volume and stream type volume
3104 vl = (uint32_t)(v * vl) << 12;
3105 vr = (uint32_t)(v * vr) << 12;
3106 // assuming master volume and stream type volume each go up to 1.0,
3107 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003108
Glenn Kasten05632a52012-01-03 14:22:33 -08003109 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3110 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003111 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003112 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003113 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003114 }
3115 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003116 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003117 // Delegate volume control to effect in track effect chain if needed
3118 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3119 // Do not ramp volume if volume is controlled by effect
3120 param = AudioMixer::VOLUME;
3121 track->mHasVolumeController = true;
3122 } else {
3123 // force no volume ramp when volume controller was just disabled or removed
3124 // from effect chain to avoid volume spike
3125 if (track->mHasVolumeController) {
3126 param = AudioMixer::VOLUME;
3127 }
3128 track->mHasVolumeController = false;
3129 }
3130
3131 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003132 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003133 vl = (vl + (1 << 11)) >> 12;
3134 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3135 vr = (vr + (1 << 11)) >> 12;
3136 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003137
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003138 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 -07003139
Mathias Agopian65ab4712010-07-14 17:59:35 -07003140 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003141 mAudioMixer->setBufferProvider(name, track);
3142 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003143
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003144 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3145 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3146 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003147 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003148 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003149 AudioMixer::TRACK,
3150 AudioMixer::FORMAT, (void *)track->format());
3151 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003152 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003153 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003154 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003155 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003156 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003157 AudioMixer::RESAMPLE,
3158 AudioMixer::SAMPLE_RATE,
3159 (void *)(cblk->sampleRate));
3160 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003161 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003162 AudioMixer::TRACK,
3163 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3164 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003165 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003166 AudioMixer::TRACK,
3167 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3168
3169 // reset retry count
3170 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003171
Eric Laurent27741442012-01-17 19:20:12 -08003172 // If one track is ready, set the mixer ready if:
3173 // - the mixer was not ready during previous round OR
3174 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003175 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003176 mixerStatus != MIXER_TRACKS_ENABLED) {
3177 mixerStatus = MIXER_TRACKS_READY;
3178 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003179 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003180 // clear effect chain input buffer if an active track underruns to avoid sending
3181 // previous audio buffer again to effects
3182 chain = getEffectChain_l(track->sessionId());
3183 if (chain != 0) {
3184 chain->clearInputBuffer();
3185 }
3186
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003187 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Eric Laurent83faee02012-04-27 18:24:29 -07003188 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3189 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003190 // We have consumed all the buffers of this track.
3191 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003192 // TODO: use actual buffer filling status instead of latency when available from
3193 // audio HAL
3194 size_t audioHALFrames =
3195 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3196 size_t framesWritten =
3197 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3198 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003199 if (track->isStopped()) {
3200 track->reset();
3201 }
Eric Laurenta011e352012-03-29 15:51:43 -07003202 tracksToRemove->add(track);
3203 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003204 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003205 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003206 // No buffers for this track. Give it a few chances to
3207 // fill a buffer, then remove it from active list.
3208 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003209 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003210 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003211 // indicate to client process that the track was disabled because of underrun;
3212 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003213 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003214 // If one track is not ready, mark the mixer also not ready if:
3215 // - the mixer was ready during previous round OR
3216 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003217 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003218 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003219 mixerStatus = MIXER_TRACKS_ENABLED;
3220 }
3221 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003222 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003223 }
Glenn Kasten58912562012-04-03 10:45:00 -07003224
3225 } // local variable scope to avoid goto warning
3226track_is_ready: ;
3227
Mathias Agopian65ab4712010-07-14 17:59:35 -07003228 }
3229
Glenn Kasten288ed212012-04-25 17:52:27 -07003230 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003231 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003232 if (didModify) {
3233 state->mFastTracksGen++;
3234 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3235 if (kUseFastMixer == FastMixer_Dynamic &&
3236 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3237 state->mCommand = FastMixerState::COLD_IDLE;
3238 state->mColdFutexAddr = &mFastMixerFutex;
3239 state->mColdGen++;
3240 mFastMixerFutex = 0;
3241 if (kUseFastMixer == FastMixer_Dynamic) {
3242 mNormalSink = mOutputSink;
3243 }
3244 // If we go into cold idle, need to wait for acknowledgement
3245 // so that fast mixer stops doing I/O.
3246 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003247 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003248 }
3249 sq->end();
3250 }
3251 if (sq != NULL) {
3252 sq->end(didModify);
3253 sq->push(block);
3254 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07003255 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3256 mAudioWatchdog->pause();
3257 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003258
3259 // Now perform the deferred reset on fast tracks that have stopped
3260 while (resetMask != 0) {
3261 size_t i = __builtin_ctz(resetMask);
3262 ALOG_ASSERT(i < count);
3263 resetMask &= ~(1 << i);
3264 sp<Track> t = mActiveTracks[i].promote();
3265 if (t == 0) continue;
3266 Track* track = t.get();
3267 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3268 track->reset();
3269 }
Glenn Kasten58912562012-04-03 10:45:00 -07003270
Mathias Agopian65ab4712010-07-14 17:59:35 -07003271 // remove all the tracks that need to be...
3272 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003273 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003274 for (size_t i=0 ; i<count ; i++) {
3275 const sp<Track>& track = tracksToRemove->itemAt(i);
3276 mActiveTracks.remove(track);
3277 if (track->mainBuffer() != mMixBuffer) {
3278 chain = getEffectChain_l(track->sessionId());
3279 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003280 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003281 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003282 }
3283 }
3284 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003285 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003286 }
3287 }
3288 }
3289
3290 // mix buffer must be cleared if all tracks are connected to an
3291 // effect chain as in this case the mixer will not write to
3292 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003293 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3294 // FIXME as a performance optimization, should remember previous zero status
3295 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003296 }
3297
Glenn Kasten58912562012-04-03 10:45:00 -07003298 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003299 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003300 if (fastTracks > 0) {
3301 mixerStatus = MIXER_TRACKS_READY;
3302 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003303 return mixerStatus;
3304}
3305
Glenn Kasten66fcab92012-02-24 14:59:21 -08003306/*
3307The derived values that are cached:
3308 - mixBufferSize from frame count * frame size
3309 - activeSleepTime from activeSleepTimeUs()
3310 - idleSleepTime from idleSleepTimeUs()
3311 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3312 - maxPeriod from frame count and sample rate (MIXER only)
3313
3314The parameters that affect these derived values are:
3315 - frame count
3316 - frame size
3317 - sample rate
3318 - device type: A2DP or not
3319 - device latency
3320 - format: PCM or not
3321 - active sleep time
3322 - idle sleep time
3323*/
3324
3325void AudioFlinger::PlaybackThread::cacheParameters_l()
3326{
Glenn Kasten58912562012-04-03 10:45:00 -07003327 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003328 activeSleepTime = activeSleepTimeUs();
3329 idleSleepTime = idleSleepTimeUs();
3330}
3331
Eric Laurent22167852012-06-20 12:26:32 -07003332void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003333{
Steve Block3856b092011-10-20 11:56:00 +01003334 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003335 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003336 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003337
Mathias Agopian65ab4712010-07-14 17:59:35 -07003338 size_t size = mTracks.size();
3339 for (size_t i = 0; i < size; i++) {
3340 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003341 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003342 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003343 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003344 }
3345 }
3346}
3347
Mathias Agopian65ab4712010-07-14 17:59:35 -07003348// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003349int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003350{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003351 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003352}
3353
3354// deleteTrackName_l() must be called with ThreadBase::mLock held
3355void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3356{
Steve Block3856b092011-10-20 11:56:00 +01003357 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003358 mAudioMixer->deleteTrackName(name);
3359}
3360
3361// checkForNewParameters_l() must be called with ThreadBase::mLock held
3362bool AudioFlinger::MixerThread::checkForNewParameters_l()
3363{
Glenn Kasten58912562012-04-03 10:45:00 -07003364 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3365 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003366 bool reconfig = false;
3367
3368 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003369
3370 if (mFastMixer != NULL) {
3371 FastMixerStateQueue *sq = mFastMixer->sq();
3372 FastMixerState *state = sq->begin();
3373 if (!(state->mCommand & FastMixerState::IDLE)) {
3374 previousCommand = state->mCommand;
3375 state->mCommand = FastMixerState::HOT_IDLE;
3376 sq->end();
3377 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3378 } else {
3379 sq->end(false /*didModify*/);
3380 }
3381 }
3382
Mathias Agopian65ab4712010-07-14 17:59:35 -07003383 status_t status = NO_ERROR;
3384 String8 keyValuePair = mNewParameters[0];
3385 AudioParameter param = AudioParameter(keyValuePair);
3386 int value;
3387
3388 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3389 reconfig = true;
3390 }
3391 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003392 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003393 status = BAD_VALUE;
3394 } else {
3395 reconfig = true;
3396 }
3397 }
3398 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003399 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003400 status = BAD_VALUE;
3401 } else {
3402 reconfig = true;
3403 }
3404 }
3405 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3406 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003407 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003408 // if frame count is changed after track creation
3409 if (!mTracks.isEmpty()) {
3410 status = INVALID_OPERATION;
3411 } else {
3412 reconfig = true;
3413 }
3414 }
3415 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003416#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003417 // when changing the audio output device, call addBatteryData to notify
3418 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003419 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003420 uint32_t params = 0;
3421 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003422 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003423 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3424 }
3425
3426 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003427 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003428 // check if any other device (except speaker) is on
3429 if (value & deviceWithoutSpeaker ) {
3430 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3431 }
3432
3433 if (params != 0) {
3434 addBatteryData(params);
3435 }
3436 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003437#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003438
Mathias Agopian65ab4712010-07-14 17:59:35 -07003439 // forward device change to effects that have requested to be
3440 // aware of attached audio device.
Glenn Kasten94479fd2012-07-09 15:39:54 -07003441 mDevice = (audio_devices_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003442 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003443 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003444 }
3445 }
3446
3447 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003448 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003449 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003450 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003451 mOutput->stream->common.standby(&mOutput->stream->common);
3452 mStandby = true;
3453 mBytesWritten = 0;
3454 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003455 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003456 }
3457 if (status == NO_ERROR && reconfig) {
3458 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003459 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3460 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003461 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003462 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003463 for (size_t i = 0; i < mTracks.size() ; i++) {
Glenn Kasten254af182012-07-03 14:59:05 -07003464 int name = getTrackName_l(mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003465 if (name < 0) break;
3466 mTracks[i]->mName = name;
3467 // limit track sample rate to 2 x new output sample rate
3468 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3469 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3470 }
3471 }
3472 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3473 }
3474 }
3475
3476 mNewParameters.removeAt(0);
3477
3478 mParamStatus = status;
3479 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003480 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3481 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003482 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003483 }
Glenn Kasten58912562012-04-03 10:45:00 -07003484
3485 if (!(previousCommand & FastMixerState::IDLE)) {
3486 ALOG_ASSERT(mFastMixer != NULL);
3487 FastMixerStateQueue *sq = mFastMixer->sq();
3488 FastMixerState *state = sq->begin();
3489 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3490 state->mCommand = previousCommand;
3491 sq->end();
3492 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3493 }
3494
Mathias Agopian65ab4712010-07-14 17:59:35 -07003495 return reconfig;
3496}
3497
3498status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3499{
3500 const size_t SIZE = 256;
3501 char buffer[SIZE];
3502 String8 result;
3503
3504 PlaybackThread::dumpInternals(fd, args);
3505
3506 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3507 result.append(buffer);
3508 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003509
3510 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3511 FastMixerDumpState copy = mFastMixerDumpState;
3512 copy.dump(fd);
3513
Glenn Kasten39993082012-05-31 13:40:27 -07003514#ifdef STATE_QUEUE_DUMP
3515 // Similar for state queue
3516 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3517 observerCopy.dump(fd);
3518 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3519 mutatorCopy.dump(fd);
3520#endif
3521
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003522 // Write the tee output to a .wav file
3523 NBAIO_Source *teeSource = mTeeSource.get();
3524 if (teeSource != NULL) {
3525 char teePath[64];
3526 struct timeval tv;
3527 gettimeofday(&tv, NULL);
3528 struct tm tm;
3529 localtime_r(&tv.tv_sec, &tm);
3530 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3531 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3532 if (teeFd >= 0) {
3533 char wavHeader[44];
3534 memcpy(wavHeader,
3535 "RIFF\0\0\0\0WAVEfmt \20\0\0\0\1\0\2\0\104\254\0\0\0\0\0\0\4\0\20\0data\0\0\0\0",
3536 sizeof(wavHeader));
3537 NBAIO_Format format = teeSource->format();
3538 unsigned channelCount = Format_channelCount(format);
3539 ALOG_ASSERT(channelCount <= FCC_2);
3540 unsigned sampleRate = Format_sampleRate(format);
3541 wavHeader[22] = channelCount; // number of channels
3542 wavHeader[24] = sampleRate; // sample rate
3543 wavHeader[25] = sampleRate >> 8;
3544 wavHeader[32] = channelCount * 2; // block alignment
3545 write(teeFd, wavHeader, sizeof(wavHeader));
3546 size_t total = 0;
3547 bool firstRead = true;
3548 for (;;) {
3549#define TEE_SINK_READ 1024
3550 short buffer[TEE_SINK_READ * FCC_2];
3551 size_t count = TEE_SINK_READ;
3552 ssize_t actual = teeSource->read(buffer, count);
3553 bool wasFirstRead = firstRead;
3554 firstRead = false;
3555 if (actual <= 0) {
3556 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3557 continue;
3558 }
3559 break;
3560 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003561 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003562 write(teeFd, buffer, actual * channelCount * sizeof(short));
3563 total += actual;
3564 }
3565 lseek(teeFd, (off_t) 4, SEEK_SET);
3566 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3567 write(teeFd, &temp, sizeof(temp));
3568 lseek(teeFd, (off_t) 40, SEEK_SET);
3569 temp = total * channelCount * sizeof(short);
3570 write(teeFd, &temp, sizeof(temp));
3571 close(teeFd);
3572 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3573 } else {
3574 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3575 }
3576 }
3577
Glenn Kastenc15d6652012-05-30 14:52:57 -07003578 if (mAudioWatchdog != 0) {
3579 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3580 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3581 wdCopy.dump(fd);
3582 }
3583
Mathias Agopian65ab4712010-07-14 17:59:35 -07003584 return NO_ERROR;
3585}
3586
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003587uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003588{
Glenn Kasten58912562012-04-03 10:45:00 -07003589 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003590}
3591
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003592uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003593{
Glenn Kasten58912562012-04-03 10:45:00 -07003594 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003595}
3596
Glenn Kasten66fcab92012-02-24 14:59:21 -08003597void AudioFlinger::MixerThread::cacheParameters_l()
3598{
3599 PlaybackThread::cacheParameters_l();
3600
3601 // FIXME: Relaxed timing because of a certain device that can't meet latency
3602 // Should be reduced to 2x after the vendor fixes the driver issue
3603 // increase threshold again due to low power audio mode. The way this warning
3604 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003605 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003606}
3607
Mathias Agopian65ab4712010-07-14 17:59:35 -07003608// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003609AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3610 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003611 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003612 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003613{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003614}
3615
3616AudioFlinger::DirectOutputThread::~DirectOutputThread()
3617{
3618}
3619
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003620AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3621 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003622)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003623{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003624 sp<Track> trackToRemove;
3625
Glenn Kastenfec279f2012-03-08 07:47:15 -08003626 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003627
Glenn Kasten952eeb22012-03-06 11:30:57 -08003628 // find out which tracks need to be processed
3629 if (mActiveTracks.size() != 0) {
3630 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003631 // The track died recently
3632 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003633
Glenn Kasten952eeb22012-03-06 11:30:57 -08003634 Track* const track = t.get();
3635 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003636
Glenn Kasten952eeb22012-03-06 11:30:57 -08003637 // The first time a track is added we wait
3638 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003639 uint32_t minFrames;
3640 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3641 minFrames = mNormalFrameCount;
3642 } else {
3643 minFrames = 1;
3644 }
3645 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003646 !track->isPaused() && !track->isTerminated())
3647 {
3648 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003649
Glenn Kasten952eeb22012-03-06 11:30:57 -08003650 if (track->mFillingUpStatus == Track::FS_FILLED) {
3651 track->mFillingUpStatus = Track::FS_ACTIVE;
3652 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003653 if (track->mState == TrackBase::RESUMING) {
3654 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003655 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003656 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003657
Glenn Kasten952eeb22012-03-06 11:30:57 -08003658 // compute volume for this track
3659 float left, right;
3660 if (track->isMuted() || mMasterMute || track->isPausing() ||
3661 mStreamTypes[track->streamType()].mute) {
3662 left = right = 0;
3663 if (track->isPausing()) {
3664 track->setPaused();
3665 }
3666 } else {
3667 float typeVolume = mStreamTypes[track->streamType()].volume;
3668 float v = mMasterVolume * typeVolume;
3669 uint32_t vlr = cblk->getVolumeLR();
3670 float v_clamped = v * (vlr & 0xFFFF);
3671 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3672 left = v_clamped/MAX_GAIN;
3673 v_clamped = v * (vlr >> 16);
3674 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3675 right = v_clamped/MAX_GAIN;
3676 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003677
Glenn Kasten952eeb22012-03-06 11:30:57 -08003678 if (left != mLeftVolFloat || right != mRightVolFloat) {
3679 mLeftVolFloat = left;
3680 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003681
Glenn Kasten952eeb22012-03-06 11:30:57 -08003682 // Convert volumes from float to 8.24
3683 uint32_t vl = (uint32_t)(left * (1 << 24));
3684 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003685
Glenn Kasten952eeb22012-03-06 11:30:57 -08003686 // Delegate volume control to effect in track effect chain if needed
3687 // only one effect chain can be present on DirectOutputThread, so if
3688 // there is one, the track is connected to it
3689 if (!mEffectChains.isEmpty()) {
3690 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003691 mEffectChains[0]->setVolume_l(&vl, &vr);
3692 left = (float)vl / (1 << 24);
3693 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003694 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003695 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003696 }
3697
3698 // reset retry count
3699 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003700 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003701 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003702 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003703 // clear effect chain input buffer if an active track underruns to avoid sending
3704 // previous audio buffer again to effects
3705 if (!mEffectChains.isEmpty()) {
3706 mEffectChains[0]->clearInputBuffer();
3707 }
3708
Glenn Kasten952eeb22012-03-06 11:30:57 -08003709 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurent67c0a582012-05-01 19:31:12 -07003710 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3711 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003712 // We have consumed all the buffers of this track.
3713 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003714 // TODO: implement behavior for compressed audio
3715 size_t audioHALFrames =
3716 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3717 size_t framesWritten =
3718 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3719 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003720 if (track->isStopped()) {
3721 track->reset();
3722 }
Eric Laurenta011e352012-03-29 15:51:43 -07003723 trackToRemove = track;
3724 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003725 } else {
3726 // No buffers for this track. Give it a few chances to
3727 // fill a buffer, then remove it from active list.
3728 if (--(track->mRetryCount) <= 0) {
3729 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3730 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003731 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003732 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003733 }
3734 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003735 }
3736 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003737
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003738 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003739 // remove all the tracks that need to be...
3740 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003741 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003742 mActiveTracks.remove(trackToRemove);
3743 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003744 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003745 trackToRemove->sessionId());
3746 mEffectChains[0]->decActiveTrackCnt();
3747 }
3748 if (trackToRemove->isTerminated()) {
3749 removeTrack_l(trackToRemove);
3750 }
3751 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003752
Glenn Kastenfec279f2012-03-08 07:47:15 -08003753 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003754}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003755
Glenn Kasten000f0e32012-03-01 17:10:56 -08003756void AudioFlinger::DirectOutputThread::threadLoop_mix()
3757{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003758 AudioBufferProvider::Buffer buffer;
3759 size_t frameCount = mFrameCount;
3760 int8_t *curBuf = (int8_t *)mMixBuffer;
3761 // output audio to hardware
3762 while (frameCount) {
3763 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003764 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003765 if (CC_UNLIKELY(buffer.raw == NULL)) {
3766 memset(curBuf, 0, frameCount * mFrameSize);
3767 break;
3768 }
3769 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3770 frameCount -= buffer.frameCount;
3771 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003772 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003773 }
3774 sleepTime = 0;
3775 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003776 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003777
Glenn Kasten000f0e32012-03-01 17:10:56 -08003778}
3779
3780void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3781{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003782 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003783 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003784 sleepTime = activeSleepTime;
3785 } else {
3786 sleepTime = idleSleepTime;
3787 }
3788 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003789 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003790 sleepTime = 0;
3791 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003792}
3793
3794// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003795int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003796{
3797 return 0;
3798}
3799
3800// deleteTrackName_l() must be called with ThreadBase::mLock held
3801void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3802{
3803}
3804
3805// checkForNewParameters_l() must be called with ThreadBase::mLock held
3806bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3807{
3808 bool reconfig = false;
3809
3810 while (!mNewParameters.isEmpty()) {
3811 status_t status = NO_ERROR;
3812 String8 keyValuePair = mNewParameters[0];
3813 AudioParameter param = AudioParameter(keyValuePair);
3814 int value;
3815
3816 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3817 // do not accept frame count changes if tracks are open as the track buffer
3818 // size depends on frame count and correct behavior would not be garantied
3819 // if frame count is changed after track creation
3820 if (!mTracks.isEmpty()) {
3821 status = INVALID_OPERATION;
3822 } else {
3823 reconfig = true;
3824 }
3825 }
3826 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003827 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003828 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003829 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003830 mOutput->stream->common.standby(&mOutput->stream->common);
3831 mStandby = true;
3832 mBytesWritten = 0;
3833 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003834 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003835 }
3836 if (status == NO_ERROR && reconfig) {
3837 readOutputParameters();
3838 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3839 }
3840 }
3841
3842 mNewParameters.removeAt(0);
3843
3844 mParamStatus = status;
3845 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003846 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3847 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003848 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003849 }
3850 return reconfig;
3851}
3852
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003853uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003854{
3855 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003856 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003857 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003858 } else {
3859 time = 10000;
3860 }
3861 return time;
3862}
3863
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003864uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003865{
3866 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003867 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003868 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003869 } else {
3870 time = 10000;
3871 }
3872 return time;
3873}
3874
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003875uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003876{
3877 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003878 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003879 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3880 } else {
3881 time = 10000;
3882 }
3883 return time;
3884}
3885
Glenn Kasten66fcab92012-02-24 14:59:21 -08003886void AudioFlinger::DirectOutputThread::cacheParameters_l()
3887{
3888 PlaybackThread::cacheParameters_l();
3889
3890 // use shorter standby delay as on normal output to release
3891 // hardware resources as soon as possible
3892 standbyDelay = microseconds(activeSleepTime*2);
3893}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003894
Mathias Agopian65ab4712010-07-14 17:59:35 -07003895// ----------------------------------------------------------------------------
3896
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003897AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003898 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003899 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3900 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003901{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003902 addOutputTrack(mainThread);
3903}
3904
3905AudioFlinger::DuplicatingThread::~DuplicatingThread()
3906{
3907 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3908 mOutputTracks[i]->destroy();
3909 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003910}
3911
Glenn Kasten000f0e32012-03-01 17:10:56 -08003912void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003913{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003914 // mix buffers...
3915 if (outputsReady(outputTracks)) {
3916 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3917 } else {
3918 memset(mMixBuffer, 0, mixBufferSize);
3919 }
3920 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003921 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003922 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003923}
3924
3925void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3926{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003927 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003928 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003929 sleepTime = activeSleepTime;
3930 } else {
3931 sleepTime = idleSleepTime;
3932 }
3933 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003934 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3935 writeFrames = mNormalFrameCount;
3936 memset(mMixBuffer, 0, mixBufferSize);
3937 } else {
3938 // flush remaining overflow buffers in output tracks
3939 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003940 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003941 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003942 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003943}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003944
Glenn Kasten000f0e32012-03-01 17:10:56 -08003945void AudioFlinger::DuplicatingThread::threadLoop_write()
3946{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003947 for (size_t i = 0; i < outputTracks.size(); i++) {
3948 outputTracks[i]->write(mMixBuffer, writeFrames);
3949 }
3950 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003951}
Glenn Kasten688a6402012-02-29 07:57:06 -08003952
Glenn Kasten000f0e32012-03-01 17:10:56 -08003953void AudioFlinger::DuplicatingThread::threadLoop_standby()
3954{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003955 // DuplicatingThread implements standby by stopping all tracks
3956 for (size_t i = 0; i < outputTracks.size(); i++) {
3957 outputTracks[i]->stop();
3958 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003959}
3960
Glenn Kastenfa26a852012-03-06 11:28:04 -08003961void AudioFlinger::DuplicatingThread::saveOutputTracks()
3962{
3963 outputTracks = mOutputTracks;
3964}
3965
3966void AudioFlinger::DuplicatingThread::clearOutputTracks()
3967{
3968 outputTracks.clear();
3969}
3970
Mathias Agopian65ab4712010-07-14 17:59:35 -07003971void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3972{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003973 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003974 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07003975 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003976 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003977 this,
3978 mSampleRate,
3979 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003980 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003981 frameCount);
3982 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003983 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003984 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003985 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003986 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003987 }
3988}
3989
3990void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3991{
3992 Mutex::Autolock _l(mLock);
3993 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003994 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003995 mOutputTracks[i]->destroy();
3996 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003997 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003998 return;
3999 }
4000 }
Steve Block3856b092011-10-20 11:56:00 +01004001 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004002}
4003
Glenn Kasten438b0362012-03-06 11:24:48 -08004004// caller must hold mLock
4005void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004006{
4007 mWaitTimeMs = UINT_MAX;
4008 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4009 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004010 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004011 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4012 if (waitTimeMs < mWaitTimeMs) {
4013 mWaitTimeMs = waitTimeMs;
4014 }
4015 }
4016 }
4017}
4018
4019
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004020bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004021{
4022 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004023 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004024 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004025 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004026 return false;
4027 }
4028 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004029 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004030 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004031 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004032 return false;
4033 }
4034 }
4035 return true;
4036}
4037
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004038uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004039{
4040 return (mWaitTimeMs * 1000) / 2;
4041}
4042
Glenn Kasten66fcab92012-02-24 14:59:21 -08004043void AudioFlinger::DuplicatingThread::cacheParameters_l()
4044{
4045 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4046 updateWaitTime_l();
4047
4048 MixerThread::cacheParameters_l();
4049}
4050
Mathias Agopian65ab4712010-07-14 17:59:35 -07004051// ----------------------------------------------------------------------------
4052
4053// TrackBase constructor must be called with AudioFlinger::mLock held
4054AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004055 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004056 const sp<Client>& client,
4057 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004058 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004059 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004060 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004061 const sp<IMemory>& sharedBuffer,
4062 int sessionId)
4063 : RefBase(),
4064 mThread(thread),
4065 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004066 mCblk(NULL),
4067 // mBuffer
4068 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004069 mFrameCount(0),
4070 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004071 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004072 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004073 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004074 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004075 // mChannelCount
4076 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004077{
Steve Block3856b092011-10-20 11:56:00 +01004078 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004079
Steve Blockb8a80522011-12-20 16:23:08 +00004080 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004081 size_t size = sizeof(audio_track_cblk_t);
4082 uint8_t channelCount = popcount(channelMask);
4083 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4084 if (sharedBuffer == 0) {
4085 size += bufferSize;
4086 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004087
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004088 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004089 mCblkMemory = client->heap()->allocate(size);
4090 if (mCblkMemory != 0) {
4091 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004092 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004093 new(mCblk) audio_track_cblk_t();
4094 // clear all buffers
4095 mCblk->frameCount = frameCount;
4096 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004097// uncomment the following lines to quickly test 32-bit wraparound
4098// mCblk->user = 0xffff0000;
4099// mCblk->server = 0xffff0000;
4100// mCblk->userBase = 0xffff0000;
4101// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004102 mChannelCount = channelCount;
4103 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004104 if (sharedBuffer == 0) {
4105 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4106 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4107 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004108 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004109 mCblk->flags = CBLK_UNDERRUN_ON;
4110 } else {
4111 mBuffer = sharedBuffer->pointer();
4112 }
4113 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4114 }
4115 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004116 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004117 client->heap()->dump("AudioTrack");
4118 return;
4119 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004120 } else {
4121 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004122 // construct the shared structure in-place.
4123 new(mCblk) audio_track_cblk_t();
4124 // clear all buffers
4125 mCblk->frameCount = frameCount;
4126 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004127// uncomment the following lines to quickly test 32-bit wraparound
4128// mCblk->user = 0xffff0000;
4129// mCblk->server = 0xffff0000;
4130// mCblk->userBase = 0xffff0000;
4131// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004132 mChannelCount = channelCount;
4133 mChannelMask = channelMask;
4134 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4135 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4136 // Force underrun condition to avoid false underrun callback until first data is
4137 // written to buffer (other flags are cleared)
4138 mCblk->flags = CBLK_UNDERRUN_ON;
4139 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004140 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004141}
4142
4143AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4144{
Glenn Kastena0d68332012-01-27 16:47:15 -08004145 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004146 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004147 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004148 } else {
4149 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004150 }
4151 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004152 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004153 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004154 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004155 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004156 // If the client's reference count drops to zero, the associated destructor
4157 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4158 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004159 mClient.clear();
4160 }
4161}
4162
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004163// AudioBufferProvider interface
4164// getNextBuffer() = 0;
4165// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004166void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4167{
Glenn Kastene0feee32011-12-13 11:53:26 -08004168 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004169 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004170 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004171 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004172 buffer->frameCount = 0;
4173}
4174
4175bool AudioFlinger::ThreadBase::TrackBase::step() {
4176 bool result;
4177 audio_track_cblk_t* cblk = this->cblk();
4178
4179 result = cblk->stepServer(mFrameCount);
4180 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004181 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004182 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004183 }
4184 return result;
4185}
4186
4187void AudioFlinger::ThreadBase::TrackBase::reset() {
4188 audio_track_cblk_t* cblk = this->cblk();
4189
4190 cblk->user = 0;
4191 cblk->server = 0;
4192 cblk->userBase = 0;
4193 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004194 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004195 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004196}
4197
Mathias Agopian65ab4712010-07-14 17:59:35 -07004198int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4199 return (int)mCblk->sampleRate;
4200}
4201
Mathias Agopian65ab4712010-07-14 17:59:35 -07004202void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4203 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004204 size_t frameSize = cblk->frameSize;
4205 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4206 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004207
4208 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004209 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4210 "TrackBase::getBuffer buffer out of range:\n"
4211 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4212 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004213 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004214 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004215
4216 return bufferStart;
4217}
4218
Eric Laurenta011e352012-03-29 15:51:43 -07004219status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4220{
4221 mSyncEvents.add(event);
4222 return NO_ERROR;
4223}
4224
Mathias Agopian65ab4712010-07-14 17:59:35 -07004225// ----------------------------------------------------------------------------
4226
4227// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4228AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004229 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004230 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004231 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004232 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004233 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004234 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004235 int frameCount,
4236 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004237 int sessionId,
4238 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004239 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004240 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004241 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004242 // mRetryCount initialized later when needed
4243 mSharedBuffer(sharedBuffer),
4244 mStreamType(streamType),
4245 mName(-1), // see note below
4246 mMainBuffer(thread->mixBuffer()),
4247 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004248 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004249 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004250 mFlags(flags),
4251 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004252 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004253 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004254{
4255 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004256 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4257 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004258 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004259 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Glenn Kasten254af182012-07-03 14:59:05 -07004260 mName = thread->getTrackName_l(channelMask);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004261 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004262 if (mName < 0) {
4263 ALOGE("no more track names available");
4264 return;
4265 }
4266 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004267 if (flags & IAudioFlinger::TRACK_FAST) {
4268 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4269 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4270 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004271 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004272 // FIXME This is too eager. We allocate a fast track index before the
4273 // fast track becomes active. Since fast tracks are a scarce resource,
4274 // this means we are potentially denying other more important fast tracks from
4275 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004276 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004277 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004278 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004279 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004280 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004281 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004282 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004283 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004284}
4285
4286AudioFlinger::PlaybackThread::Track::~Track()
4287{
Steve Block3856b092011-10-20 11:56:00 +01004288 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004289 sp<ThreadBase> thread = mThread.promote();
4290 if (thread != 0) {
4291 Mutex::Autolock _l(thread->mLock);
4292 mState = TERMINATED;
4293 }
4294}
4295
4296void AudioFlinger::PlaybackThread::Track::destroy()
4297{
4298 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4299 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004300 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004301 // we must acquire a strong reference on this Track before locking mLock
4302 // here so that the destructor is called only when exiting this function.
4303 // On the other hand, as long as Track::destroy() is only called by
4304 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4305 // this Track with its member mTrack.
4306 sp<Track> keep(this);
4307 { // scope for mLock
4308 sp<ThreadBase> thread = mThread.promote();
4309 if (thread != 0) {
4310 if (!isOutputTrack()) {
4311 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004312 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004313
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004314#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004315 // to track the speaker usage
4316 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004317#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004318 }
4319 AudioSystem::releaseOutput(thread->id());
4320 }
4321 Mutex::Autolock _l(thread->mLock);
4322 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4323 playbackThread->destroyTrack_l(this);
4324 }
4325 }
4326}
4327
Glenn Kasten288ed212012-04-25 17:52:27 -07004328/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4329{
Glenn Kastene213c862012-04-25 13:46:15 -07004330 result.append(" Name Client Type Fmt Chn mask Session mFrCnt fCount S M F SRate L dB R dB "
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07004331 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004332}
4333
Mathias Agopian65ab4712010-07-14 17:59:35 -07004334void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4335{
Glenn Kasten83d86532012-01-17 14:39:34 -08004336 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004337 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004338 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004339 } else {
4340 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4341 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004342 track_state state = mState;
4343 char stateChar;
4344 switch (state) {
4345 case IDLE:
4346 stateChar = 'I';
4347 break;
4348 case TERMINATED:
4349 stateChar = 'T';
4350 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004351 case STOPPING_1:
4352 stateChar = 's';
4353 break;
4354 case STOPPING_2:
4355 stateChar = '5';
4356 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004357 case STOPPED:
4358 stateChar = 'S';
4359 break;
4360 case RESUMING:
4361 stateChar = 'R';
4362 break;
4363 case ACTIVE:
4364 stateChar = 'A';
4365 break;
4366 case PAUSING:
4367 stateChar = 'p';
4368 break;
4369 case PAUSED:
4370 stateChar = 'P';
4371 break;
Eric Laurent29864602012-05-08 18:57:51 -07004372 case FLUSHED:
4373 stateChar = 'F';
4374 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004375 default:
4376 stateChar = '?';
4377 break;
4378 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004379 char nowInUnderrun;
4380 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4381 case UNDERRUN_FULL:
4382 nowInUnderrun = ' ';
4383 break;
4384 case UNDERRUN_PARTIAL:
4385 nowInUnderrun = '<';
4386 break;
4387 case UNDERRUN_EMPTY:
4388 nowInUnderrun = '*';
4389 break;
4390 default:
4391 nowInUnderrun = '?';
4392 break;
4393 }
Glenn Kastene213c862012-04-25 13:46:15 -07004394 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4395 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004396 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004397 mStreamType,
4398 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004399 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004400 mSessionId,
4401 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004402 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004403 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004404 mMute,
4405 mFillingUpStatus,
4406 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004407 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4408 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004409 mCblk->server,
4410 mCblk->user,
4411 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004412 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004413 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004414 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004415 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004416}
4417
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004418// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004419status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004420 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004421{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004422 audio_track_cblk_t* cblk = this->cblk();
4423 uint32_t framesReady;
4424 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004425
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004426 // Check if last stepServer failed, try to step now
4427 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004428 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4429 // Since the fast mixer is higher priority than client callback thread,
4430 // it does not result in priority inversion for client.
4431 // But a non-blocking solution would be preferable to avoid
4432 // fast mixer being unable to tryLock(), and
4433 // to avoid the extra context switches if the client wakes up,
4434 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004435 if (!step()) goto getNextBuffer_exit;
4436 ALOGV("stepServer recovered");
4437 mStepServerFailed = false;
4438 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004439
Glenn Kasten288ed212012-04-25 17:52:27 -07004440 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004441 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004442
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004443 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004444 uint32_t s = cblk->server;
4445 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4446
4447 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4448 if (framesReq > framesReady) {
4449 framesReq = framesReady;
4450 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004451 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004452 framesReq = bufferEnd - s;
4453 }
4454
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004455 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004456 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004457 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004458 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004459
4460getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004461 buffer->raw = NULL;
4462 buffer->frameCount = 0;
4463 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4464 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004465}
4466
Glenn Kasten288ed212012-04-25 17:52:27 -07004467// Note that framesReady() takes a mutex on the control block using tryLock().
4468// This could result in priority inversion if framesReady() is called by the normal mixer,
4469// as the normal mixer thread runs at lower
4470// priority than the client's callback thread: there is a short window within framesReady()
4471// during which the normal mixer could be preempted, and the client callback would block.
4472// Another problem can occur if framesReady() is called by the fast mixer:
4473// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4474// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4475size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004476 return mCblk->framesReady();
4477}
4478
Glenn Kasten288ed212012-04-25 17:52:27 -07004479// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004480bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004481 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004482
John Grossman4ff14ba2012-02-08 16:37:41 -08004483 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004484 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4485 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004486 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004487 return true;
4488 }
4489 return false;
4490}
4491
Glenn Kasten3acbd052012-02-28 10:39:56 -08004492status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004493 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004494{
4495 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004496 ALOGV("start(%d), calling pid %d session %d",
4497 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004498
Mathias Agopian65ab4712010-07-14 17:59:35 -07004499 sp<ThreadBase> thread = mThread.promote();
4500 if (thread != 0) {
4501 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004502 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004503 // here the track could be either new, or restarted
4504 // in both cases "unstop" the track
4505 if (mState == PAUSED) {
4506 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004507 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004508 } else {
4509 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004510 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004511 }
4512
4513 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4514 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004515 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004516 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004517
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004518#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004519 // to track the speaker usage
4520 if (status == NO_ERROR) {
4521 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4522 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004523#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004524 }
4525 if (status == NO_ERROR) {
4526 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4527 playbackThread->addTrack_l(this);
4528 } else {
4529 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004530 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004531 }
4532 } else {
4533 status = BAD_VALUE;
4534 }
4535 return status;
4536}
4537
4538void AudioFlinger::PlaybackThread::Track::stop()
4539{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004540 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004541 sp<ThreadBase> thread = mThread.promote();
4542 if (thread != 0) {
4543 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004544 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004545 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004546 // If the track is not active (PAUSED and buffers full), flush buffers
4547 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4548 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4549 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004550 mState = STOPPED;
4551 } else if (!isFastTrack()) {
4552 mState = STOPPED;
4553 } else {
4554 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4555 // and then to STOPPED and reset() when presentation is complete
4556 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004557 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004558 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004559 }
4560 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4561 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004562 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004563 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004564
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004565#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004566 // to track the speaker usage
4567 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004568#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004569 }
4570 }
4571}
4572
4573void AudioFlinger::PlaybackThread::Track::pause()
4574{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004575 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004576 sp<ThreadBase> thread = mThread.promote();
4577 if (thread != 0) {
4578 Mutex::Autolock _l(thread->mLock);
4579 if (mState == ACTIVE || mState == RESUMING) {
4580 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004581 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004582 if (!isOutputTrack()) {
4583 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004584 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004585 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004586
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004587#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004588 // to track the speaker usage
4589 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004590#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004591 }
4592 }
4593 }
4594}
4595
4596void AudioFlinger::PlaybackThread::Track::flush()
4597{
Steve Block3856b092011-10-20 11:56:00 +01004598 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004599 sp<ThreadBase> thread = mThread.promote();
4600 if (thread != 0) {
4601 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004602 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4603 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004604 return;
4605 }
4606 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004607 // FLUSHED state
4608 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004609 // do not reset the track if it is still in the process of being stopped or paused.
4610 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004611 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004612 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004613 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4614 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4615 reset();
4616 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004617 }
4618}
4619
4620void AudioFlinger::PlaybackThread::Track::reset()
4621{
4622 // Do not reset twice to avoid discarding data written just after a flush and before
4623 // the audioflinger thread detects the track is stopped.
4624 if (!mResetDone) {
4625 TrackBase::reset();
4626 // Force underrun condition to avoid false underrun callback until first data is
4627 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004628 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4629 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004630 mFillingUpStatus = FS_FILLING;
4631 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004632 if (mState == FLUSHED) {
4633 mState = IDLE;
4634 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004635 }
4636}
4637
4638void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4639{
4640 mMute = muted;
4641}
4642
Mathias Agopian65ab4712010-07-14 17:59:35 -07004643status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4644{
4645 status_t status = DEAD_OBJECT;
4646 sp<ThreadBase> thread = mThread.promote();
4647 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004648 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004649 sp<AudioFlinger> af = mClient->audioFlinger();
4650
4651 Mutex::Autolock _l(af->mLock);
4652
4653 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004654
Eric Laurent109347d2012-07-02 12:31:03 -07004655 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004656 Mutex::Autolock _dl(playbackThread->mLock);
4657 Mutex::Autolock _sl(srcThread->mLock);
4658 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4659 if (chain == 0) {
4660 return INVALID_OPERATION;
4661 }
4662
4663 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4664 if (effect == 0) {
4665 return INVALID_OPERATION;
4666 }
4667 srcThread->removeEffect_l(effect);
4668 playbackThread->addEffect_l(effect);
4669 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4670 if (effect->state() == EffectModule::ACTIVE ||
4671 effect->state() == EffectModule::STOPPING) {
4672 effect->start();
4673 }
4674
4675 sp<EffectChain> dstChain = effect->chain().promote();
4676 if (dstChain == 0) {
4677 srcThread->addEffect_l(effect);
4678 return INVALID_OPERATION;
4679 }
4680 AudioSystem::unregisterEffect(effect->id());
4681 AudioSystem::registerEffect(&effect->desc(),
4682 srcThread->id(),
4683 dstChain->strategy(),
4684 AUDIO_SESSION_OUTPUT_MIX,
4685 effect->id());
4686 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004687 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004688 }
4689 return status;
4690}
4691
4692void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4693{
4694 mAuxEffectId = EffectId;
4695 mAuxBuffer = buffer;
4696}
4697
Eric Laurenta011e352012-03-29 15:51:43 -07004698bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4699 size_t audioHalFrames)
4700{
4701 // a track is considered presented when the total number of frames written to audio HAL
4702 // corresponds to the number of frames written when presentationComplete() is called for the
4703 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4704 if (mPresentationCompleteFrames == 0) {
4705 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4706 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4707 mPresentationCompleteFrames, audioHalFrames);
4708 }
4709 if (framesWritten >= mPresentationCompleteFrames) {
4710 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4711 mSessionId, framesWritten);
4712 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004713 return true;
4714 }
4715 return false;
4716}
4717
4718void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4719{
4720 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4721 if (mSyncEvents[i]->type() == type) {
4722 mSyncEvents[i]->trigger();
4723 mSyncEvents.removeAt(i);
4724 i--;
4725 }
4726 }
4727}
4728
Glenn Kasten58912562012-04-03 10:45:00 -07004729// implement VolumeBufferProvider interface
4730
4731uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4732{
4733 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4734 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4735 uint32_t vlr = mCblk->getVolumeLR();
4736 uint32_t vl = vlr & 0xFFFF;
4737 uint32_t vr = vlr >> 16;
4738 // track volumes come from shared memory, so can't be trusted and must be clamped
4739 if (vl > MAX_GAIN_INT) {
4740 vl = MAX_GAIN_INT;
4741 }
4742 if (vr > MAX_GAIN_INT) {
4743 vr = MAX_GAIN_INT;
4744 }
4745 // now apply the cached master volume and stream type volume;
4746 // this is trusted but lacks any synchronization or barrier so may be stale
4747 float v = mCachedVolume;
4748 vl *= v;
4749 vr *= v;
4750 // re-combine into U4.16
4751 vlr = (vr << 16) | (vl & 0xFFFF);
4752 // FIXME look at mute, pause, and stop flags
4753 return vlr;
4754}
Eric Laurenta011e352012-03-29 15:51:43 -07004755
Eric Laurent29864602012-05-08 18:57:51 -07004756status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4757{
4758 if (mState == TERMINATED || mState == PAUSED ||
4759 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4760 (mState == STOPPED)))) {
4761 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4762 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4763 event->cancel();
4764 return INVALID_OPERATION;
4765 }
4766 TrackBase::setSyncEvent(event);
4767 return NO_ERROR;
4768}
4769
John Grossman4ff14ba2012-02-08 16:37:41 -08004770// timed audio tracks
4771
4772sp<AudioFlinger::PlaybackThread::TimedTrack>
4773AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004774 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004775 const sp<Client>& client,
4776 audio_stream_type_t streamType,
4777 uint32_t sampleRate,
4778 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004779 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004780 int frameCount,
4781 const sp<IMemory>& sharedBuffer,
4782 int sessionId) {
4783 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004784 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004785
Glenn Kastena0356762012-03-19 10:38:51 -07004786 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004787 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4788 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004789}
4790
4791AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004792 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004793 const sp<Client>& client,
4794 audio_stream_type_t streamType,
4795 uint32_t sampleRate,
4796 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004797 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004798 int frameCount,
4799 const sp<IMemory>& sharedBuffer,
4800 int sessionId)
4801 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004802 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004803 mQueueHeadInFlight(false),
4804 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004805 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004806 mTimedSilenceBuffer(NULL),
4807 mTimedSilenceBufferSize(0),
4808 mTimedAudioOutputOnTime(false),
4809 mMediaTimeTransformValid(false)
4810{
4811 LocalClock lc;
4812 mLocalTimeFreq = lc.getLocalFreq();
4813
4814 mLocalTimeToSampleTransform.a_zero = 0;
4815 mLocalTimeToSampleTransform.b_zero = 0;
4816 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4817 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4818 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4819 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004820
4821 mMediaTimeToSampleTransform.a_zero = 0;
4822 mMediaTimeToSampleTransform.b_zero = 0;
4823 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4824 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4825 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4826 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004827}
4828
4829AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4830 mClient->releaseTimedTrack();
4831 delete [] mTimedSilenceBuffer;
4832}
4833
4834status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4835 size_t size, sp<IMemory>* buffer) {
4836
4837 Mutex::Autolock _l(mTimedBufferQueueLock);
4838
4839 trimTimedBufferQueue_l();
4840
4841 // lazily initialize the shared memory heap for timed buffers
4842 if (mTimedMemoryDealer == NULL) {
4843 const int kTimedBufferHeapSize = 512 << 10;
4844
4845 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4846 "AudioFlingerTimed");
4847 if (mTimedMemoryDealer == NULL)
4848 return NO_MEMORY;
4849 }
4850
4851 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4852 if (newBuffer == NULL) {
4853 newBuffer = mTimedMemoryDealer->allocate(size);
4854 if (newBuffer == NULL)
4855 return NO_MEMORY;
4856 }
4857
4858 *buffer = newBuffer;
4859 return NO_ERROR;
4860}
4861
4862// caller must hold mTimedBufferQueueLock
4863void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4864 int64_t mediaTimeNow;
4865 {
4866 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4867 if (!mMediaTimeTransformValid)
4868 return;
4869
4870 int64_t targetTimeNow;
4871 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4872 ? mCCHelper.getCommonTime(&targetTimeNow)
4873 : mCCHelper.getLocalTime(&targetTimeNow);
4874
4875 if (OK != res)
4876 return;
4877
4878 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4879 &mediaTimeNow)) {
4880 return;
4881 }
4882 }
4883
John Grossman1c345192012-03-27 14:00:17 -07004884 size_t trimEnd;
4885 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004886 int64_t bufEnd;
4887
John Grossmanc95cfbb2012-04-12 11:53:11 -07004888 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4889 // We have a next buffer. Just use its PTS as the PTS of the frame
4890 // following the last frame in this buffer. If the stream is sparse
4891 // (ie, there are deliberate gaps left in the stream which should be
4892 // filled with silence by the TimedAudioTrack), then this can result
4893 // in one extra buffer being left un-trimmed when it could have
4894 // been. In general, this is not typical, and we would rather
4895 // optimized away the TS calculation below for the more common case
4896 // where PTSes are contiguous.
4897 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4898 } else {
4899 // We have no next buffer. Compute the PTS of the frame following
4900 // the last frame in this buffer by computing the duration of of
4901 // this frame in media time units and adding it to the PTS of the
4902 // buffer.
4903 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4904 / mCblk->frameSize;
4905
4906 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4907 &bufEnd)) {
4908 ALOGE("Failed to convert frame count of %lld to media time"
4909 " duration" " (scale factor %d/%u) in %s",
4910 frameCount,
4911 mMediaTimeToSampleTransform.a_to_b_numer,
4912 mMediaTimeToSampleTransform.a_to_b_denom,
4913 __PRETTY_FUNCTION__);
4914 break;
4915 }
4916 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004917 }
John Grossman9fbdee12012-03-26 17:51:46 -07004918
4919 if (bufEnd > mediaTimeNow)
4920 break;
4921
4922 // Is the buffer we want to use in the middle of a mix operation right
4923 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4924 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004925 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004926 mTrimQueueHeadOnRelease = true;
4927 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004928 }
4929
John Grossman9fbdee12012-03-26 17:51:46 -07004930 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004931 if (trimStart < trimEnd) {
4932 // Update the bookkeeping for framesReady()
4933 for (size_t i = trimStart; i < trimEnd; ++i) {
4934 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4935 }
4936
4937 // Now actually remove the buffers from the queue.
4938 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004939 }
4940}
4941
John Grossman1c345192012-03-27 14:00:17 -07004942void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4943 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004944 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4945 "%s called (reason \"%s\"), but timed buffer queue has no"
4946 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004947
4948 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4949 mTimedBufferQueue.removeAt(0);
4950}
4951
4952void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4953 const TimedBuffer& buf,
4954 const char* logTag) {
4955 uint32_t bufBytes = buf.buffer()->size();
4956 uint32_t consumedAlready = buf.position();
4957
Eric Laurentb388e532012-04-14 13:32:48 -07004958 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004959 "Bad bookkeeping while updating frames pending. Timed buffer is"
4960 " only %u bytes long, but claims to have consumed %u"
4961 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004962 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004963
4964 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004965 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4966 "Bad bookkeeping while updating frames pending. Should have at"
4967 " least %u queued frames, but we think we have only %u. (update"
4968 " reason: \"%s\")",
4969 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004970
4971 mFramesPendingInQueue -= bufFrames;
4972}
4973
John Grossman4ff14ba2012-02-08 16:37:41 -08004974status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4975 const sp<IMemory>& buffer, int64_t pts) {
4976
4977 {
4978 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4979 if (!mMediaTimeTransformValid)
4980 return INVALID_OPERATION;
4981 }
4982
4983 Mutex::Autolock _l(mTimedBufferQueueLock);
4984
John Grossman1c345192012-03-27 14:00:17 -07004985 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4986 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004987 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4988
4989 return NO_ERROR;
4990}
4991
4992status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4993 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4994
John Grossman1c345192012-03-27 14:00:17 -07004995 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4996 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4997 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08004998
4999 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5000 target == TimedAudioTrack::COMMON_TIME)) {
5001 return BAD_VALUE;
5002 }
5003
5004 Mutex::Autolock lock(mMediaTimeTransformLock);
5005 mMediaTimeTransform = xform;
5006 mMediaTimeTransformTarget = target;
5007 mMediaTimeTransformValid = true;
5008
5009 return NO_ERROR;
5010}
5011
5012#define min(a, b) ((a) < (b) ? (a) : (b))
5013
5014// implementation of getNextBuffer for tracks whose buffers have timestamps
5015status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5016 AudioBufferProvider::Buffer* buffer, int64_t pts)
5017{
5018 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005019 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005020 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005021 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005022 return INVALID_OPERATION;
5023 }
5024
John Grossman4ff14ba2012-02-08 16:37:41 -08005025 Mutex::Autolock _l(mTimedBufferQueueLock);
5026
John Grossman9fbdee12012-03-26 17:51:46 -07005027 ALOG_ASSERT(!mQueueHeadInFlight,
5028 "getNextBuffer called without releaseBuffer!");
5029
John Grossman4ff14ba2012-02-08 16:37:41 -08005030 while (true) {
5031
5032 // if we have no timed buffers, then fail
5033 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005034 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005035 buffer->frameCount = 0;
5036 return NOT_ENOUGH_DATA;
5037 }
5038
5039 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5040
5041 // calculate the PTS of the head of the timed buffer queue expressed in
5042 // local time
5043 int64_t headLocalPTS;
5044 {
5045 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5046
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005047 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005048
5049 if (mMediaTimeTransform.a_to_b_denom == 0) {
5050 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005051 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005052 return NO_ERROR;
5053 }
5054
5055 int64_t transformedPTS;
5056 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5057 &transformedPTS)) {
5058 // the transform failed. this shouldn't happen, but if it does
5059 // then just drop this buffer
5060 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005061 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005062 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005063 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005064 return NO_ERROR;
5065 }
5066
5067 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5068 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5069 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005070 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005071 buffer->frameCount = 0;
5072 return INVALID_OPERATION;
5073 }
5074 } else {
5075 headLocalPTS = transformedPTS;
5076 }
5077 }
5078
5079 // adjust the head buffer's PTS to reflect the portion of the head buffer
5080 // that has already been consumed
5081 int64_t effectivePTS = headLocalPTS +
5082 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5083
5084 // Calculate the delta in samples between the head of the input buffer
5085 // queue and the start of the next output buffer that will be written.
5086 // If the transformation fails because of over or underflow, it means
5087 // that the sample's position in the output stream is so far out of
5088 // whack that it should just be dropped.
5089 int64_t sampleDelta;
5090 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5091 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005092 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5093 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005094 continue;
5095 }
5096 if (!mLocalTimeToSampleTransform.doForwardTransform(
5097 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005098 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005099 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005100 continue;
5101 }
5102
John Grossman1c345192012-03-27 14:00:17 -07005103 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5104 " sampleDelta=[%d.%08x]",
5105 head.pts(), head.position(), pts,
5106 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5107 + (sampleDelta >> 32)),
5108 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005109
5110 // if the delta between the ideal placement for the next input sample and
5111 // the current output position is within this threshold, then we will
5112 // concatenate the next input samples to the previous output
5113 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005114 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005115
5116 // if this is the first buffer of audio that we're emitting from this track
5117 // then it should be almost exactly on time.
5118 const int64_t kSampleStartupThreshold = 1LL << 32;
5119
5120 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005121 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005122 // the next input is close enough to being on time, so concatenate it
5123 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005124 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005125
John Grossman1c345192012-03-27 14:00:17 -07005126 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5127 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005128 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005129 }
5130
5131 // Looks like our output is not on time. Reset our on timed status.
5132 // Next time we mix samples from our input queue, then should be within
5133 // the StartupThreshold.
5134 mTimedAudioOutputOnTime = false;
5135 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005136 // the gap between the current output position and the proper start of
5137 // the next input sample is too big, so fill it with silence
5138 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5139
John Grossman9fbdee12012-03-26 17:51:46 -07005140 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005141 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5142 return NO_ERROR;
5143 } else {
5144 // the next input sample is late
5145 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5146 size_t onTimeSamplePosition =
5147 head.position() + lateFrames * mCblk->frameSize;
5148
5149 if (onTimeSamplePosition > head.buffer()->size()) {
5150 // all the remaining samples in the head are too late, so
5151 // drop it and move on
5152 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005153 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005154 continue;
5155 } else {
5156 // skip over the late samples
5157 head.setPosition(onTimeSamplePosition);
5158
5159 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005160 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005161
5162 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5163 return NO_ERROR;
5164 }
5165 }
5166 }
5167}
5168
5169// Yield samples from the timed buffer queue head up to the given output
5170// buffer's capacity.
5171//
5172// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005173void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005174 AudioBufferProvider::Buffer* buffer) {
5175
5176 const TimedBuffer& head = mTimedBufferQueue[0];
5177
5178 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5179 head.position());
5180
5181 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5182 mCblk->frameSize);
5183 size_t framesRequested = buffer->frameCount;
5184 buffer->frameCount = min(framesLeftInHead, framesRequested);
5185
John Grossman9fbdee12012-03-26 17:51:46 -07005186 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005187 mTimedAudioOutputOnTime = true;
5188}
5189
5190// Yield samples of silence up to the given output buffer's capacity
5191//
5192// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005193void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005194 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5195
5196 // lazily allocate a buffer filled with silence
5197 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5198 delete [] mTimedSilenceBuffer;
5199 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5200 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5201 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5202 }
5203
5204 buffer->raw = mTimedSilenceBuffer;
5205 size_t framesRequested = buffer->frameCount;
5206 buffer->frameCount = min(numFrames, framesRequested);
5207
5208 mTimedAudioOutputOnTime = false;
5209}
5210
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005211// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005212void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5213 AudioBufferProvider::Buffer* buffer) {
5214
5215 Mutex::Autolock _l(mTimedBufferQueueLock);
5216
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005217 // If the buffer which was just released is part of the buffer at the head
5218 // of the queue, be sure to update the amt of the buffer which has been
5219 // consumed. If the buffer being returned is not part of the head of the
5220 // queue, its either because the buffer is part of the silence buffer, or
5221 // because the head of the timed queue was trimmed after the mixer called
5222 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005223 if (buffer->raw == mTimedSilenceBuffer) {
5224 ALOG_ASSERT(!mQueueHeadInFlight,
5225 "Queue head in flight during release of silence buffer!");
5226 goto done;
5227 }
5228
5229 ALOG_ASSERT(mQueueHeadInFlight,
5230 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5231 " head in flight.");
5232
5233 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005234 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005235
5236 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005237 void* end = reinterpret_cast<void*>(
5238 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5239 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005240
John Grossman9fbdee12012-03-26 17:51:46 -07005241 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5242 "released buffer not within the head of the timed buffer"
5243 " queue; qHead = [%p, %p], released buffer = %p",
5244 start, end, buffer->raw);
5245
5246 head.setPosition(head.position() +
5247 (buffer->frameCount * mCblk->frameSize));
5248 mQueueHeadInFlight = false;
5249
John Grossman1c345192012-03-27 14:00:17 -07005250 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5251 "Bad bookkeeping during releaseBuffer! Should have at"
5252 " least %u queued frames, but we think we have only %u",
5253 buffer->frameCount, mFramesPendingInQueue);
5254
5255 mFramesPendingInQueue -= buffer->frameCount;
5256
John Grossman9fbdee12012-03-26 17:51:46 -07005257 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5258 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005259 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005260 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005261 }
John Grossman9fbdee12012-03-26 17:51:46 -07005262 } else {
5263 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5264 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005265 }
5266
John Grossman9fbdee12012-03-26 17:51:46 -07005267done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005268 buffer->raw = 0;
5269 buffer->frameCount = 0;
5270}
5271
Glenn Kasten288ed212012-04-25 17:52:27 -07005272size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005273 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005274 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005275}
5276
5277AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5278 : mPTS(0), mPosition(0) {}
5279
5280AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5281 const sp<IMemory>& buffer, int64_t pts)
5282 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5283
Mathias Agopian65ab4712010-07-14 17:59:35 -07005284// ----------------------------------------------------------------------------
5285
5286// RecordTrack constructor must be called with AudioFlinger::mLock held
5287AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005288 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005289 const sp<Client>& client,
5290 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005291 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005292 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005293 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005294 int sessionId)
5295 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005296 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005297 mOverflow(false)
5298{
5299 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005300 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5301 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5302 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5303 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5304 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5305 } else {
5306 mCblk->frameSize = sizeof(int8_t);
5307 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005308 }
5309}
5310
5311AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5312{
5313 sp<ThreadBase> thread = mThread.promote();
5314 if (thread != 0) {
5315 AudioSystem::releaseInput(thread->id());
5316 }
5317}
5318
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005319// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005320status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005321{
5322 audio_track_cblk_t* cblk = this->cblk();
5323 uint32_t framesAvail;
5324 uint32_t framesReq = buffer->frameCount;
5325
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005326 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005327 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005328 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005329 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005330 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005331 }
5332
5333 framesAvail = cblk->framesAvailable_l();
5334
Glenn Kastenf6b16782011-12-15 09:51:17 -08005335 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005336 uint32_t s = cblk->server;
5337 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5338
5339 if (framesReq > framesAvail) {
5340 framesReq = framesAvail;
5341 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005342 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005343 framesReq = bufferEnd - s;
5344 }
5345
5346 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005347 buffer->frameCount = framesReq;
5348 return NO_ERROR;
5349 }
5350
5351getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005352 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005353 buffer->frameCount = 0;
5354 return NOT_ENOUGH_DATA;
5355}
5356
Glenn Kasten3acbd052012-02-28 10:39:56 -08005357status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005358 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005359{
5360 sp<ThreadBase> thread = mThread.promote();
5361 if (thread != 0) {
5362 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005363 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005364 } else {
5365 return BAD_VALUE;
5366 }
5367}
5368
5369void AudioFlinger::RecordThread::RecordTrack::stop()
5370{
5371 sp<ThreadBase> thread = mThread.promote();
5372 if (thread != 0) {
5373 RecordThread *recordThread = (RecordThread *)thread.get();
5374 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005375 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005376 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005377 // read from buffer
5378 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005379 }
5380}
5381
5382void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5383{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005384 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005385 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005386 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005387 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005388 mSessionId,
5389 mFrameCount,
5390 mState,
5391 mCblk->sampleRate,
5392 mCblk->server,
5393 mCblk->user);
5394}
5395
5396
5397// ----------------------------------------------------------------------------
5398
5399AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005400 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005401 DuplicatingThread *sourceThread,
5402 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005403 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005404 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005405 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005406 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5407 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005408 mActive(false), mSourceThread(sourceThread)
5409{
5410
Mathias Agopian65ab4712010-07-14 17:59:35 -07005411 if (mCblk != NULL) {
5412 mCblk->flags |= CBLK_DIRECTION_OUT;
5413 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005414 mOutBuffer.frameCount = 0;
5415 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005416 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005417 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5418 mCblk, mBuffer, mCblk->buffers,
5419 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005420 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005421 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005422 }
5423}
5424
5425AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5426{
5427 clearBufferQueue();
5428}
5429
Glenn Kasten3acbd052012-02-28 10:39:56 -08005430status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005431 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005432{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005433 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005434 if (status != NO_ERROR) {
5435 return status;
5436 }
5437
5438 mActive = true;
5439 mRetryCount = 127;
5440 return status;
5441}
5442
5443void AudioFlinger::PlaybackThread::OutputTrack::stop()
5444{
5445 Track::stop();
5446 clearBufferQueue();
5447 mOutBuffer.frameCount = 0;
5448 mActive = false;
5449}
5450
5451bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5452{
5453 Buffer *pInBuffer;
5454 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005455 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005456 bool outputBufferFull = false;
5457 inBuffer.frameCount = frames;
5458 inBuffer.i16 = data;
5459
5460 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5461
5462 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005463 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005464 sp<ThreadBase> thread = mThread.promote();
5465 if (thread != 0) {
5466 MixerThread *mixerThread = (MixerThread *)thread.get();
5467 if (mCblk->frameCount > frames){
5468 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5469 uint32_t startFrames = (mCblk->frameCount - frames);
5470 pInBuffer = new Buffer;
5471 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5472 pInBuffer->frameCount = startFrames;
5473 pInBuffer->i16 = pInBuffer->mBuffer;
5474 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5475 mBufferQueue.add(pInBuffer);
5476 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005477 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005478 }
5479 }
5480 }
5481 }
5482
5483 while (waitTimeLeftMs) {
5484 // First write pending buffers, then new data
5485 if (mBufferQueue.size()) {
5486 pInBuffer = mBufferQueue.itemAt(0);
5487 } else {
5488 pInBuffer = &inBuffer;
5489 }
5490
5491 if (pInBuffer->frameCount == 0) {
5492 break;
5493 }
5494
5495 if (mOutBuffer.frameCount == 0) {
5496 mOutBuffer.frameCount = pInBuffer->frameCount;
5497 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005498 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005499 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005500 outputBufferFull = true;
5501 break;
5502 }
5503 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5504 if (waitTimeLeftMs >= waitTimeMs) {
5505 waitTimeLeftMs -= waitTimeMs;
5506 } else {
5507 waitTimeLeftMs = 0;
5508 }
5509 }
5510
5511 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5512 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5513 mCblk->stepUser(outFrames);
5514 pInBuffer->frameCount -= outFrames;
5515 pInBuffer->i16 += outFrames * channelCount;
5516 mOutBuffer.frameCount -= outFrames;
5517 mOutBuffer.i16 += outFrames * channelCount;
5518
5519 if (pInBuffer->frameCount == 0) {
5520 if (mBufferQueue.size()) {
5521 mBufferQueue.removeAt(0);
5522 delete [] pInBuffer->mBuffer;
5523 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005524 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005525 } else {
5526 break;
5527 }
5528 }
5529 }
5530
5531 // If we could not write all frames, allocate a buffer and queue it for next time.
5532 if (inBuffer.frameCount) {
5533 sp<ThreadBase> thread = mThread.promote();
5534 if (thread != 0 && !thread->standby()) {
5535 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5536 pInBuffer = new Buffer;
5537 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5538 pInBuffer->frameCount = inBuffer.frameCount;
5539 pInBuffer->i16 = pInBuffer->mBuffer;
5540 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5541 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005542 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005543 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005544 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005545 }
5546 }
5547 }
5548
5549 // Calling write() with a 0 length buffer, means that no more data will be written:
5550 // If no more buffers are pending, fill output track buffer to make sure it is started
5551 // by output mixer.
5552 if (frames == 0 && mBufferQueue.size() == 0) {
5553 if (mCblk->user < mCblk->frameCount) {
5554 frames = mCblk->frameCount - mCblk->user;
5555 pInBuffer = new Buffer;
5556 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5557 pInBuffer->frameCount = frames;
5558 pInBuffer->i16 = pInBuffer->mBuffer;
5559 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5560 mBufferQueue.add(pInBuffer);
5561 } else if (mActive) {
5562 stop();
5563 }
5564 }
5565
5566 return outputBufferFull;
5567}
5568
5569status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5570{
5571 int active;
5572 status_t result;
5573 audio_track_cblk_t* cblk = mCblk;
5574 uint32_t framesReq = buffer->frameCount;
5575
Steve Block3856b092011-10-20 11:56:00 +01005576// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005577 buffer->frameCount = 0;
5578
5579 uint32_t framesAvail = cblk->framesAvailable();
5580
5581
5582 if (framesAvail == 0) {
5583 Mutex::Autolock _l(cblk->lock);
5584 goto start_loop_here;
5585 while (framesAvail == 0) {
5586 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005587 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005588 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005589 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005590 }
5591 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5592 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005593 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005594 }
5595 // read the server count again
5596 start_loop_here:
5597 framesAvail = cblk->framesAvailable_l();
5598 }
5599 }
5600
5601// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005602// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005603// }
5604
5605 if (framesReq > framesAvail) {
5606 framesReq = framesAvail;
5607 }
5608
5609 uint32_t u = cblk->user;
5610 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5611
Marco Nelissena1472d92012-03-30 14:36:54 -07005612 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005613 framesReq = bufferEnd - u;
5614 }
5615
5616 buffer->frameCount = framesReq;
5617 buffer->raw = (void *)cblk->buffer(u);
5618 return NO_ERROR;
5619}
5620
5621
5622void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5623{
5624 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005625
5626 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005627 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005628 delete [] pBuffer->mBuffer;
5629 delete pBuffer;
5630 }
5631 mBufferQueue.clear();
5632}
5633
5634// ----------------------------------------------------------------------------
5635
5636AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5637 : RefBase(),
5638 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005639 // 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 -07005640 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005641 mPid(pid),
5642 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005643{
5644 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5645}
5646
5647// Client destructor must be called with AudioFlinger::mLock held
5648AudioFlinger::Client::~Client()
5649{
5650 mAudioFlinger->removeClient_l(mPid);
5651}
5652
Glenn Kasten435dbe62012-01-30 10:15:48 -08005653sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005654{
5655 return mMemoryDealer;
5656}
5657
John Grossman4ff14ba2012-02-08 16:37:41 -08005658// Reserve one of the limited slots for a timed audio track associated
5659// with this client
5660bool AudioFlinger::Client::reserveTimedTrack()
5661{
5662 const int kMaxTimedTracksPerClient = 4;
5663
5664 Mutex::Autolock _l(mTimedTrackLock);
5665
5666 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5667 ALOGW("can not create timed track - pid %d has exceeded the limit",
5668 mPid);
5669 return false;
5670 }
5671
5672 mTimedTrackCount++;
5673 return true;
5674}
5675
5676// Release a slot for a timed audio track
5677void AudioFlinger::Client::releaseTimedTrack()
5678{
5679 Mutex::Autolock _l(mTimedTrackLock);
5680 mTimedTrackCount--;
5681}
5682
Mathias Agopian65ab4712010-07-14 17:59:35 -07005683// ----------------------------------------------------------------------------
5684
5685AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5686 const sp<IAudioFlingerClient>& client,
5687 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005688 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005689{
5690}
5691
5692AudioFlinger::NotificationClient::~NotificationClient()
5693{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005694}
5695
5696void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5697{
5698 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005699 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005700}
5701
5702// ----------------------------------------------------------------------------
5703
5704AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5705 : BnAudioTrack(),
5706 mTrack(track)
5707{
5708}
5709
5710AudioFlinger::TrackHandle::~TrackHandle() {
5711 // just stop the track on deletion, associated resources
5712 // will be freed from the main thread once all pending buffers have
5713 // been played. Unless it's not in the active track list, in which
5714 // case we free everything now...
5715 mTrack->destroy();
5716}
5717
Glenn Kasten90716c52012-01-26 13:40:12 -08005718sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5719 return mTrack->getCblk();
5720}
5721
Glenn Kasten3acbd052012-02-28 10:39:56 -08005722status_t AudioFlinger::TrackHandle::start() {
5723 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005724}
5725
5726void AudioFlinger::TrackHandle::stop() {
5727 mTrack->stop();
5728}
5729
5730void AudioFlinger::TrackHandle::flush() {
5731 mTrack->flush();
5732}
5733
5734void AudioFlinger::TrackHandle::mute(bool e) {
5735 mTrack->mute(e);
5736}
5737
5738void AudioFlinger::TrackHandle::pause() {
5739 mTrack->pause();
5740}
5741
Mathias Agopian65ab4712010-07-14 17:59:35 -07005742status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5743{
5744 return mTrack->attachAuxEffect(EffectId);
5745}
5746
John Grossman4ff14ba2012-02-08 16:37:41 -08005747status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5748 sp<IMemory>* buffer) {
5749 if (!mTrack->isTimedTrack())
5750 return INVALID_OPERATION;
5751
5752 PlaybackThread::TimedTrack* tt =
5753 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5754 return tt->allocateTimedBuffer(size, buffer);
5755}
5756
5757status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5758 int64_t pts) {
5759 if (!mTrack->isTimedTrack())
5760 return INVALID_OPERATION;
5761
5762 PlaybackThread::TimedTrack* tt =
5763 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5764 return tt->queueTimedBuffer(buffer, pts);
5765}
5766
5767status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5768 const LinearTransform& xform, int target) {
5769
5770 if (!mTrack->isTimedTrack())
5771 return INVALID_OPERATION;
5772
5773 PlaybackThread::TimedTrack* tt =
5774 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5775 return tt->setMediaTimeTransform(
5776 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5777}
5778
Mathias Agopian65ab4712010-07-14 17:59:35 -07005779status_t AudioFlinger::TrackHandle::onTransact(
5780 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5781{
5782 return BnAudioTrack::onTransact(code, data, reply, flags);
5783}
5784
5785// ----------------------------------------------------------------------------
5786
5787sp<IAudioRecord> AudioFlinger::openRecord(
5788 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005789 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005790 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005791 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005792 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005793 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005794 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07005795 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005796 int *sessionId,
5797 status_t *status)
5798{
5799 sp<RecordThread::RecordTrack> recordTrack;
5800 sp<RecordHandle> recordHandle;
5801 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005802 status_t lStatus;
5803 RecordThread *thread;
5804 size_t inFrameCount;
5805 int lSessionId;
5806
5807 // check calling permissions
5808 if (!recordingAllowed()) {
5809 lStatus = PERMISSION_DENIED;
5810 goto Exit;
5811 }
5812
5813 // add client to list
5814 { // scope for mLock
5815 Mutex::Autolock _l(mLock);
5816 thread = checkRecordThread_l(input);
5817 if (thread == NULL) {
5818 lStatus = BAD_VALUE;
5819 goto Exit;
5820 }
5821
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005822 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005823
5824 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005825 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005826 lSessionId = *sessionId;
5827 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005828 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005829 if (sessionId != NULL) {
5830 *sessionId = lSessionId;
5831 }
5832 }
5833 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07005834 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
5835 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005836 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005837 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005838 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5839 // destructor is called by the TrackBase destructor with mLock held
5840 client.clear();
5841 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005842 goto Exit;
5843 }
5844
5845 // return to handle to client
5846 recordHandle = new RecordHandle(recordTrack);
5847 lStatus = NO_ERROR;
5848
5849Exit:
5850 if (status) {
5851 *status = lStatus;
5852 }
5853 return recordHandle;
5854}
5855
5856// ----------------------------------------------------------------------------
5857
5858AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5859 : BnAudioRecord(),
5860 mRecordTrack(recordTrack)
5861{
5862}
5863
5864AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005865 stop_nonvirtual();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005866}
5867
Glenn Kasten90716c52012-01-26 13:40:12 -08005868sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5869 return mRecordTrack->getCblk();
5870}
5871
Glenn Kasten3acbd052012-02-28 10:39:56 -08005872status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005873 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005874 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005875}
5876
5877void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005878 stop_nonvirtual();
5879}
5880
5881void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01005882 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005883 mRecordTrack->stop();
5884}
5885
Mathias Agopian65ab4712010-07-14 17:59:35 -07005886status_t AudioFlinger::RecordHandle::onTransact(
5887 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5888{
5889 return BnAudioRecord::onTransact(code, data, reply, flags);
5890}
5891
5892// ----------------------------------------------------------------------------
5893
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005894AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5895 AudioStreamIn *input,
5896 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07005897 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005898 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005899 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005900 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005901 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5902 // mRsmpInIndex and mInputBytes set by readInputParameters()
Glenn Kasten254af182012-07-03 14:59:05 -07005903 mReqChannelCount(popcount(channelMask)),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005904 mReqSampleRate(sampleRate)
5905 // mBytesRead is only meaningful while active, and so is cleared in start()
5906 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005907{
Glenn Kasten480b4682012-02-28 12:30:08 -08005908 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005909
Mathias Agopian65ab4712010-07-14 17:59:35 -07005910 readInputParameters();
5911}
5912
5913
5914AudioFlinger::RecordThread::~RecordThread()
5915{
5916 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005917 delete mResampler;
5918 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005919}
5920
5921void AudioFlinger::RecordThread::onFirstRef()
5922{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005923 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005924}
5925
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005926status_t AudioFlinger::RecordThread::readyToRun()
5927{
5928 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005929 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005930 return status;
5931}
5932
Mathias Agopian65ab4712010-07-14 17:59:35 -07005933bool AudioFlinger::RecordThread::threadLoop()
5934{
5935 AudioBufferProvider::Buffer buffer;
5936 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005937 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005938
Eric Laurent44d98482010-09-30 16:12:31 -07005939 nsecs_t lastWarning = 0;
5940
Eric Laurentfeb0db62011-07-22 09:04:31 -07005941 acquireWakeLock();
5942
Mathias Agopian65ab4712010-07-14 17:59:35 -07005943 // start recording
5944 while (!exitPending()) {
5945
5946 processConfigEvents();
5947
5948 { // scope for mLock
5949 Mutex::Autolock _l(mLock);
5950 checkForNewParameters_l();
5951 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5952 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005953 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005954 mStandby = true;
5955 }
5956
5957 if (exitPending()) break;
5958
Eric Laurentfeb0db62011-07-22 09:04:31 -07005959 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005960 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005961 // go to sleep
5962 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005963 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005964 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005965 continue;
5966 }
5967 if (mActiveTrack != 0) {
5968 if (mActiveTrack->mState == TrackBase::PAUSING) {
5969 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005970 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005971 mStandby = true;
5972 }
5973 mActiveTrack.clear();
5974 mStartStopCond.broadcast();
5975 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5976 if (mReqChannelCount != mActiveTrack->channelCount()) {
5977 mActiveTrack.clear();
5978 mStartStopCond.broadcast();
5979 } else if (mBytesRead != 0) {
5980 // record start succeeds only if first read from audio input
5981 // succeeds
5982 if (mBytesRead > 0) {
5983 mActiveTrack->mState = TrackBase::ACTIVE;
5984 } else {
5985 mActiveTrack.clear();
5986 }
5987 mStartStopCond.broadcast();
5988 }
5989 mStandby = false;
5990 }
5991 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005992 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005993 }
5994
5995 if (mActiveTrack != 0) {
5996 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5997 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005998 unlockEffectChains(effectChains);
5999 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006000 continue;
6001 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006002 for (size_t i = 0; i < effectChains.size(); i ++) {
6003 effectChains[i]->process_l();
6004 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006005
Mathias Agopian65ab4712010-07-14 17:59:35 -07006006 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006007 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006008 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006009 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006010 // no resampling
6011 while (framesOut) {
6012 size_t framesIn = mFrameCount - mRsmpInIndex;
6013 if (framesIn) {
6014 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6015 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6016 if (framesIn > framesOut)
6017 framesIn = framesOut;
6018 mRsmpInIndex += framesIn;
6019 framesOut -= framesIn;
6020 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006021 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006022 memcpy(dst, src, framesIn * mFrameSize);
6023 } else {
6024 int16_t *src16 = (int16_t *)src;
6025 int16_t *dst16 = (int16_t *)dst;
6026 if (mChannelCount == 1) {
6027 while (framesIn--) {
6028 *dst16++ = *src16;
6029 *dst16++ = *src16++;
6030 }
6031 } else {
6032 while (framesIn--) {
6033 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
6034 src16 += 2;
6035 }
6036 }
6037 }
6038 }
6039 if (framesOut && mFrameCount == mRsmpInIndex) {
6040 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006041 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006042 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006043 framesOut = 0;
6044 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006045 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006046 mRsmpInIndex = 0;
6047 }
6048 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006049 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006050 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6051 // Force input into standby so that it tries to
6052 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006053 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006054 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006055 }
6056 mRsmpInIndex = mFrameCount;
6057 framesOut = 0;
6058 buffer.frameCount = 0;
6059 }
6060 }
6061 }
6062 } else {
6063 // resampling
6064
6065 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6066 // alter output frame count as if we were expecting stereo samples
6067 if (mChannelCount == 1 && mReqChannelCount == 1) {
6068 framesOut >>= 1;
6069 }
6070 mResampler->resample(mRsmpOutBuffer, framesOut, this);
6071 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6072 // are 32 bit aligned which should be always true.
6073 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006074 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006075 // the resampler always outputs stereo samples: do post stereo to mono conversion
6076 int16_t *src = (int16_t *)mRsmpOutBuffer;
6077 int16_t *dst = buffer.i16;
6078 while (framesOut--) {
6079 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
6080 src += 2;
6081 }
6082 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006083 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006084 }
6085
6086 }
Eric Laurenta011e352012-03-29 15:51:43 -07006087 if (mFramestoDrop == 0) {
6088 mActiveTrack->releaseBuffer(&buffer);
6089 } else {
6090 if (mFramestoDrop > 0) {
6091 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006092 if (mFramestoDrop <= 0) {
6093 clearSyncStartEvent();
6094 }
6095 } else {
6096 mFramestoDrop += buffer.frameCount;
6097 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6098 mSyncStartEvent->isCancelled()) {
6099 ALOGW("Synced record %s, session %d, trigger session %d",
6100 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6101 mActiveTrack->sessionId(),
6102 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6103 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006104 }
6105 }
6106 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006107 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006108 }
6109 // client isn't retrieving buffers fast enough
6110 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006111 if (!mActiveTrack->setOverflow()) {
6112 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006113 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006114 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006115 lastWarning = now;
6116 }
6117 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006118 // Release the processor for a while before asking for a new buffer.
6119 // This will give the application more chance to read from the buffer and
6120 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006121 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006122 }
6123 }
Eric Laurentec437d82011-07-26 20:54:46 -07006124 // enable changes in effect chain
6125 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006126 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006127 }
6128
6129 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006130 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006131 }
6132 mActiveTrack.clear();
6133
6134 mStartStopCond.broadcast();
6135
Eric Laurentfeb0db62011-07-22 09:04:31 -07006136 releaseWakeLock();
6137
Steve Block3856b092011-10-20 11:56:00 +01006138 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006139 return false;
6140}
6141
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006142
6143sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6144 const sp<AudioFlinger::Client>& client,
6145 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006146 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006147 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006148 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006149 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006150 IAudioFlinger::track_flags_t flags,
6151 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006152 status_t *status)
6153{
6154 sp<RecordTrack> track;
6155 status_t lStatus;
6156
6157 lStatus = initCheck();
6158 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006159 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006160 goto Exit;
6161 }
6162
Glenn Kasten1879fff2012-07-11 15:36:59 -07006163 // FIXME use flags and tid similar to createTrack_l()
6164
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006165 { // scope for mLock
6166 Mutex::Autolock _l(mLock);
6167
6168 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006169 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006170
Glenn Kasten7378ca52012-01-20 13:44:40 -08006171 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006172 lStatus = NO_MEMORY;
6173 goto Exit;
6174 }
6175
6176 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006177 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6178 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006179 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006180 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6181 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006182 }
6183 lStatus = NO_ERROR;
6184
6185Exit:
6186 if (status) {
6187 *status = lStatus;
6188 }
6189 return track;
6190}
6191
Eric Laurenta011e352012-03-29 15:51:43 -07006192status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006193 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006194 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006195{
Glenn Kasten58912562012-04-03 10:45:00 -07006196 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006197 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006198 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006199
6200 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006201 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006202 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6203 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6204 triggerSession,
6205 recordTrack->sessionId(),
6206 syncStartEventCallback,
6207 this);
Eric Laurent29864602012-05-08 18:57:51 -07006208 // Sync event can be cancelled by the trigger session if the track is not in a
6209 // compatible state in which case we start record immediately
6210 if (mSyncStartEvent->isCancelled()) {
6211 clearSyncStartEvent();
6212 } else {
6213 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6214 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6215 }
Eric Laurenta011e352012-03-29 15:51:43 -07006216 }
6217
Mathias Agopian65ab4712010-07-14 17:59:35 -07006218 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006219 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006220 if (mActiveTrack != 0) {
6221 if (recordTrack != mActiveTrack.get()) {
6222 status = -EBUSY;
6223 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6224 mActiveTrack->mState = TrackBase::ACTIVE;
6225 }
6226 return status;
6227 }
6228
6229 recordTrack->mState = TrackBase::IDLE;
6230 mActiveTrack = recordTrack;
6231 mLock.unlock();
6232 status_t status = AudioSystem::startInput(mId);
6233 mLock.lock();
6234 if (status != NO_ERROR) {
6235 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006236 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006237 return status;
6238 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006239 mRsmpInIndex = mFrameCount;
6240 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006241 if (mResampler != NULL) {
6242 mResampler->reset();
6243 }
6244 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006245 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006246 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006247 mWaitWorkCV.signal();
6248 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006249 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006250 mActiveTrack.clear();
6251 status = INVALID_OPERATION;
6252 goto startError;
6253 }
6254 mStartStopCond.wait(mLock);
6255 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006256 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006257 status = BAD_VALUE;
6258 goto startError;
6259 }
Steve Block3856b092011-10-20 11:56:00 +01006260 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006261 return status;
6262 }
6263startError:
6264 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006265 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006266 return status;
6267}
6268
Eric Laurenta011e352012-03-29 15:51:43 -07006269void AudioFlinger::RecordThread::clearSyncStartEvent()
6270{
6271 if (mSyncStartEvent != 0) {
6272 mSyncStartEvent->cancel();
6273 }
6274 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006275 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006276}
6277
6278void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6279{
6280 sp<SyncEvent> strongEvent = event.promote();
6281
6282 if (strongEvent != 0) {
6283 RecordThread *me = (RecordThread *)strongEvent->cookie();
6284 me->handleSyncStartEvent(strongEvent);
6285 }
6286}
6287
6288void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6289{
Eric Laurent29864602012-05-08 18:57:51 -07006290 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006291 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6292 // from audio HAL
6293 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006294 }
6295}
6296
Mathias Agopian65ab4712010-07-14 17:59:35 -07006297void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006298 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006299 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006300 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006301 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006302 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6303 mActiveTrack->mState = TrackBase::PAUSING;
6304 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006305 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006306 return;
6307 }
6308 mStartStopCond.wait(mLock);
6309 // if we have been restarted, recordTrack == mActiveTrack.get() here
6310 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6311 mLock.unlock();
6312 AudioSystem::stopInput(mId);
6313 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006314 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006315 }
6316 }
6317 }
6318}
6319
Eric Laurenta011e352012-03-29 15:51:43 -07006320bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6321{
6322 return false;
6323}
6324
6325status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6326{
6327 if (!isValidSyncEvent(event)) {
6328 return BAD_VALUE;
6329 }
6330
6331 Mutex::Autolock _l(mLock);
6332
6333 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6334 mTrack->setSyncEvent(event);
6335 return NO_ERROR;
6336 }
6337 return NAME_NOT_FOUND;
6338}
6339
Mathias Agopian65ab4712010-07-14 17:59:35 -07006340status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6341{
6342 const size_t SIZE = 256;
6343 char buffer[SIZE];
6344 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006345
6346 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6347 result.append(buffer);
6348
6349 if (mActiveTrack != 0) {
6350 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006351 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006352 mActiveTrack->dump(buffer, SIZE);
6353 result.append(buffer);
6354
6355 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6356 result.append(buffer);
6357 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6358 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006359 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006360 result.append(buffer);
6361 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6362 result.append(buffer);
6363 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6364 result.append(buffer);
6365
6366
6367 } else {
6368 result.append("No record client\n");
6369 }
6370 write(fd, result.string(), result.size());
6371
6372 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006373 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006374
6375 return NO_ERROR;
6376}
6377
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006378// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006379status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006380{
6381 size_t framesReq = buffer->frameCount;
6382 size_t framesReady = mFrameCount - mRsmpInIndex;
6383 int channelCount;
6384
6385 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006386 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006387 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006388 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006389 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6390 // Force input into standby so that it tries to
6391 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006392 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006393 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006394 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006395 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006396 buffer->frameCount = 0;
6397 return NOT_ENOUGH_DATA;
6398 }
6399 mRsmpInIndex = 0;
6400 framesReady = mFrameCount;
6401 }
6402
6403 if (framesReq > framesReady) {
6404 framesReq = framesReady;
6405 }
6406
6407 if (mChannelCount == 1 && mReqChannelCount == 2) {
6408 channelCount = 1;
6409 } else {
6410 channelCount = 2;
6411 }
6412 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6413 buffer->frameCount = framesReq;
6414 return NO_ERROR;
6415}
6416
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006417// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006418void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6419{
6420 mRsmpInIndex += buffer->frameCount;
6421 buffer->frameCount = 0;
6422}
6423
6424bool AudioFlinger::RecordThread::checkForNewParameters_l()
6425{
6426 bool reconfig = false;
6427
6428 while (!mNewParameters.isEmpty()) {
6429 status_t status = NO_ERROR;
6430 String8 keyValuePair = mNewParameters[0];
6431 AudioParameter param = AudioParameter(keyValuePair);
6432 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006433 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006434 int reqSamplingRate = mReqSampleRate;
6435 int reqChannelCount = mReqChannelCount;
6436
6437 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6438 reqSamplingRate = value;
6439 reconfig = true;
6440 }
6441 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006442 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006443 reconfig = true;
6444 }
6445 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006446 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006447 reconfig = true;
6448 }
6449 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6450 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006451 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006452 // if frame count is changed after track creation
6453 if (mActiveTrack != 0) {
6454 status = INVALID_OPERATION;
6455 } else {
6456 reconfig = true;
6457 }
6458 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006459 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6460 // forward device change to effects that have requested to be
6461 // aware of attached audio device.
6462 for (size_t i = 0; i < mEffectChains.size(); i++) {
6463 mEffectChains[i]->setDevice_l(value);
6464 }
6465 // store input device and output device but do not forward output device to audio HAL.
6466 // Note that status is ignored by the caller for output device
6467 // (see AudioFlinger::setParameters()
Glenn Kasten94479fd2012-07-09 15:39:54 -07006468 uint32_t /*audio_devices_t*/ newDevice = mDevice;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006469 if (value & AUDIO_DEVICE_OUT_ALL) {
Glenn Kasten01542f22012-07-02 12:46:15 -07006470 newDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006471 status = BAD_VALUE;
6472 } else {
Glenn Kasten01542f22012-07-02 12:46:15 -07006473 newDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006474 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6475 if (mTrack != NULL) {
6476 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006477 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006478 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6479 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6480 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006481 }
Glenn Kasten01542f22012-07-02 12:46:15 -07006482 newDevice |= value;
Glenn Kasten94479fd2012-07-09 15:39:54 -07006483 mDevice = (audio_devices_t) newDevice; // since mDevice is read by other threads, only write to it once
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006484 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006485 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006486 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006487 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006488 mInput->stream->common.standby(&mInput->stream->common);
6489 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6490 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006491 }
6492 if (reconfig) {
6493 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006494 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006495 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006496 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006497 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6498 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006499 status = NO_ERROR;
6500 }
6501 if (status == NO_ERROR) {
6502 readInputParameters();
6503 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6504 }
6505 }
6506 }
6507
6508 mNewParameters.removeAt(0);
6509
6510 mParamStatus = status;
6511 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006512 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6513 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006514 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006515 }
6516 return reconfig;
6517}
6518
6519String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6520{
Dima Zavinfce7a472011-04-19 22:30:36 -07006521 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006522 String8 out_s8 = String8();
6523
6524 Mutex::Autolock _l(mLock);
6525 if (initCheck() != NO_ERROR) {
6526 return out_s8;
6527 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006528
Dima Zavin799a70e2011-04-18 16:57:27 -07006529 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006530 out_s8 = String8(s);
6531 free(s);
6532 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006533}
6534
6535void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6536 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006537 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006538
6539 switch (event) {
6540 case AudioSystem::INPUT_OPENED:
6541 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006542 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006543 desc.samplingRate = mSampleRate;
6544 desc.format = mFormat;
6545 desc.frameCount = mFrameCount;
6546 desc.latency = 0;
6547 param2 = &desc;
6548 break;
6549
6550 case AudioSystem::INPUT_CLOSED:
6551 default:
6552 break;
6553 }
6554 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6555}
6556
6557void AudioFlinger::RecordThread::readInputParameters()
6558{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006559 delete mRsmpInBuffer;
6560 // mRsmpInBuffer is always assigned a new[] below
6561 delete mRsmpOutBuffer;
6562 mRsmpOutBuffer = NULL;
6563 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006564 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006565
Dima Zavin799a70e2011-04-18 16:57:27 -07006566 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006567 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6568 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006569 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006570 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006571 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006572 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006573 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006574 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6575
Glenn Kasten53d76db2012-03-08 12:32:47 -08006576 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006577 {
6578 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006579 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6580 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006581 if (mChannelCount == 1 && mReqChannelCount == 2) {
6582 channelCount = 1;
6583 } else {
6584 channelCount = 2;
6585 }
6586 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6587 mResampler->setSampleRate(mSampleRate);
6588 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6589 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6590
6591 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6592 if (mChannelCount == 1 && mReqChannelCount == 1) {
6593 mFrameCount >>= 1;
6594 }
6595
6596 }
6597 mRsmpInIndex = mFrameCount;
6598}
6599
6600unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6601{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006602 Mutex::Autolock _l(mLock);
6603 if (initCheck() != NO_ERROR) {
6604 return 0;
6605 }
6606
Dima Zavin799a70e2011-04-18 16:57:27 -07006607 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006608}
6609
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006610uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6611{
6612 Mutex::Autolock _l(mLock);
6613 uint32_t result = 0;
6614 if (getEffectChain_l(sessionId) != 0) {
6615 result = EFFECT_SESSION;
6616 }
6617
6618 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6619 result |= TRACK_SESSION;
6620 }
6621
6622 return result;
6623}
6624
Eric Laurent59bd0da2011-08-01 09:52:20 -07006625AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6626{
6627 Mutex::Autolock _l(mLock);
6628 return mTrack;
6629}
6630
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006631AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6632{
6633 Mutex::Autolock _l(mLock);
6634 AudioStreamIn *input = mInput;
6635 mInput = NULL;
6636 return input;
6637}
6638
6639// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006640audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006641{
6642 if (mInput == NULL) {
6643 return NULL;
6644 }
6645 return &mInput->stream->common;
6646}
6647
6648
Mathias Agopian65ab4712010-07-14 17:59:35 -07006649// ----------------------------------------------------------------------------
6650
Eric Laurenta4c5a552012-03-29 10:12:40 -07006651audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6652{
6653 if (!settingsAllowed()) {
6654 return 0;
6655 }
6656 Mutex::Autolock _l(mLock);
6657 return loadHwModule_l(name);
6658}
6659
6660// loadHwModule_l() must be called with AudioFlinger::mLock held
6661audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6662{
6663 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6664 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6665 ALOGW("loadHwModule() module %s already loaded", name);
6666 return mAudioHwDevs.keyAt(i);
6667 }
6668 }
6669
Eric Laurenta4c5a552012-03-29 10:12:40 -07006670 audio_hw_device_t *dev;
6671
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006672 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006673 if (rc) {
6674 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6675 return 0;
6676 }
6677
6678 mHardwareStatus = AUDIO_HW_INIT;
6679 rc = dev->init_check(dev);
6680 mHardwareStatus = AUDIO_HW_IDLE;
6681 if (rc) {
6682 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6683 return 0;
6684 }
6685
6686 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6687 (NULL != dev->set_master_volume)) {
6688 AutoMutex lock(mHardwareLock);
6689 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6690 dev->set_master_volume(dev, mMasterVolume);
6691 mHardwareStatus = AUDIO_HW_IDLE;
6692 }
6693
6694 audio_module_handle_t handle = nextUniqueId();
6695 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6696
6697 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006698 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006699
6700 return handle;
6701
6702}
6703
6704audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6705 audio_devices_t *pDevices,
6706 uint32_t *pSamplingRate,
6707 audio_format_t *pFormat,
6708 audio_channel_mask_t *pChannelMask,
6709 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006710 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006711{
6712 status_t status;
6713 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006714 struct audio_config config = {
6715 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6716 channel_mask: pChannelMask ? *pChannelMask : 0,
6717 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6718 };
6719 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006720 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006721
Eric Laurenta4c5a552012-03-29 10:12:40 -07006722 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6723 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006724 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006725 config.sample_rate,
6726 config.format,
6727 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006728 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006729
6730 if (pDevices == NULL || *pDevices == 0) {
6731 return 0;
6732 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006733
Mathias Agopian65ab4712010-07-14 17:59:35 -07006734 Mutex::Autolock _l(mLock);
6735
Eric Laurenta4c5a552012-03-29 10:12:40 -07006736 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006737 if (outHwDev == NULL)
6738 return 0;
6739
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006740 audio_io_handle_t id = nextUniqueId();
6741
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006742 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006743
6744 status = outHwDev->open_output_stream(outHwDev,
6745 id,
6746 *pDevices,
6747 (audio_output_flags_t)flags,
6748 &config,
6749 &outStream);
6750
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006751 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006752 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006753 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006754 config.sample_rate,
6755 config.format,
6756 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006757 status);
6758
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006759 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006760 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006761
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006762 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006763 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6764 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006765 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006766 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006767 } else {
6768 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006769 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006770 }
6771 mPlaybackThreads.add(id, thread);
6772
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006773 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6774 if (pFormat != NULL) *pFormat = config.format;
6775 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006776 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006777
6778 // notify client processes of the new output creation
6779 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006780
6781 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006782 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006783 ALOGI("Using module %d has the primary audio interface", module);
6784 mPrimaryHardwareDev = outHwDev;
6785
6786 AutoMutex lock(mHardwareLock);
6787 mHardwareStatus = AUDIO_HW_SET_MODE;
6788 outHwDev->set_mode(outHwDev, mMode);
6789
6790 // Determine the level of master volume support the primary audio HAL has,
6791 // and set the initial master volume at the same time.
6792 float initialVolume = 1.0;
6793 mMasterVolumeSupportLvl = MVS_NONE;
6794
6795 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6796 if ((NULL != outHwDev->get_master_volume) &&
6797 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6798 mMasterVolumeSupportLvl = MVS_FULL;
6799 } else {
6800 mMasterVolumeSupportLvl = MVS_SETONLY;
6801 initialVolume = 1.0;
6802 }
6803
6804 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6805 if ((NULL == outHwDev->set_master_volume) ||
6806 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6807 mMasterVolumeSupportLvl = MVS_NONE;
6808 }
6809 // now that we have a primary device, initialize master volume on other devices
6810 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6811 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6812
6813 if ((dev != mPrimaryHardwareDev) &&
6814 (NULL != dev->set_master_volume)) {
6815 dev->set_master_volume(dev, initialVolume);
6816 }
6817 }
6818 mHardwareStatus = AUDIO_HW_IDLE;
6819 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6820 ? initialVolume
6821 : 1.0;
6822 mMasterVolume = initialVolume;
6823 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006824 return id;
6825 }
6826
6827 return 0;
6828}
6829
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006830audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6831 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006832{
6833 Mutex::Autolock _l(mLock);
6834 MixerThread *thread1 = checkMixerThread_l(output1);
6835 MixerThread *thread2 = checkMixerThread_l(output2);
6836
6837 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006838 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006839 return 0;
6840 }
6841
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006842 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006843 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6844 thread->addOutputTrack(thread2);
6845 mPlaybackThreads.add(id, thread);
6846 // notify client processes of the new output creation
6847 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6848 return id;
6849}
6850
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006851status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006852{
Glenn Kastend96c5722012-04-25 13:44:49 -07006853 return closeOutput_nonvirtual(output);
6854}
6855
6856status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
6857{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006858 // keep strong reference on the playback thread so that
6859 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006860 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006861 {
6862 Mutex::Autolock _l(mLock);
6863 thread = checkPlaybackThread_l(output);
6864 if (thread == NULL) {
6865 return BAD_VALUE;
6866 }
6867
Steve Block3856b092011-10-20 11:56:00 +01006868 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006869
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006870 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006871 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006872 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006873 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6874 dupThread->removeOutputTrack((MixerThread *)thread.get());
6875 }
6876 }
6877 }
Glenn Kastena1117922012-01-26 10:53:32 -08006878 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006879 mPlaybackThreads.removeItem(output);
6880 }
6881 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006882 // The thread entity (active unit of execution) is no longer running here,
6883 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006884
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006885 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006886 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006887 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006888 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006889 out->hwDev->close_output_stream(out->hwDev, out->stream);
6890 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006891 }
6892 return NO_ERROR;
6893}
6894
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006895status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006896{
6897 Mutex::Autolock _l(mLock);
6898 PlaybackThread *thread = checkPlaybackThread_l(output);
6899
6900 if (thread == NULL) {
6901 return BAD_VALUE;
6902 }
6903
Steve Block3856b092011-10-20 11:56:00 +01006904 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006905 thread->suspend();
6906
6907 return NO_ERROR;
6908}
6909
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006910status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006911{
6912 Mutex::Autolock _l(mLock);
6913 PlaybackThread *thread = checkPlaybackThread_l(output);
6914
6915 if (thread == NULL) {
6916 return BAD_VALUE;
6917 }
6918
Steve Block3856b092011-10-20 11:56:00 +01006919 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006920
6921 thread->restore();
6922
6923 return NO_ERROR;
6924}
6925
Eric Laurenta4c5a552012-03-29 10:12:40 -07006926audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6927 audio_devices_t *pDevices,
6928 uint32_t *pSamplingRate,
6929 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07006930 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006931{
6932 status_t status;
6933 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006934 struct audio_config config = {
6935 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6936 channel_mask: pChannelMask ? *pChannelMask : 0,
6937 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6938 };
6939 uint32_t reqSamplingRate = config.sample_rate;
6940 audio_format_t reqFormat = config.format;
6941 audio_channel_mask_t reqChannels = config.channel_mask;
6942 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006943 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006944
6945 if (pDevices == NULL || *pDevices == 0) {
6946 return 0;
6947 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006948
Mathias Agopian65ab4712010-07-14 17:59:35 -07006949 Mutex::Autolock _l(mLock);
6950
Eric Laurenta4c5a552012-03-29 10:12:40 -07006951 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006952 if (inHwDev == NULL)
6953 return 0;
6954
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006955 audio_io_handle_t id = nextUniqueId();
6956
6957 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006958 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006959 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006960 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006961 config.sample_rate,
6962 config.format,
6963 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006964 status);
6965
6966 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6967 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6968 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006969 if (status == BAD_VALUE &&
6970 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6971 (config.sample_rate <= 2 * reqSamplingRate) &&
6972 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07006973 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006974 inStream = NULL;
6975 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006976 }
6977
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006978 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006979 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6980
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006981 // Start record thread
6982 // RecorThread require both input and output device indication to forward to audio
6983 // pre processing modules
6984 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6985 thread = new RecordThread(this,
6986 input,
6987 reqSamplingRate,
6988 reqChannels,
6989 id,
6990 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006991 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006992 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006993 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006994 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006995 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006996
Dima Zavin799a70e2011-04-18 16:57:27 -07006997 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006998
6999 // notify client processes of the new input creation
7000 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7001 return id;
7002 }
7003
7004 return 0;
7005}
7006
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007007status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007008{
Glenn Kastend96c5722012-04-25 13:44:49 -07007009 return closeInput_nonvirtual(input);
7010}
7011
7012status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7013{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007014 // keep strong reference on the record thread so that
7015 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007016 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007017 {
7018 Mutex::Autolock _l(mLock);
7019 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007020 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007021 return BAD_VALUE;
7022 }
7023
Steve Block3856b092011-10-20 11:56:00 +01007024 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007025 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007026 mRecordThreads.removeItem(input);
7027 }
7028 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007029 // The thread entity (active unit of execution) is no longer running here,
7030 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007031
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007032 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007033 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007034 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07007035 in->hwDev->close_input_stream(in->hwDev, in->stream);
7036 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007037
7038 return NO_ERROR;
7039}
7040
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007041status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007042{
7043 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007044 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007045
7046 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7047 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007048 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007049 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007050
7051 return NO_ERROR;
7052}
7053
7054
7055int AudioFlinger::newAudioSessionId()
7056{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007057 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007058}
7059
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007060void AudioFlinger::acquireAudioSessionId(int audioSession)
7061{
7062 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007063 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007064 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007065 size_t num = mAudioSessionRefs.size();
7066 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007067 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007068 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7069 ref->mCnt++;
7070 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007071 return;
7072 }
7073 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007074 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7075 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007076}
7077
7078void AudioFlinger::releaseAudioSessionId(int audioSession)
7079{
7080 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007081 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007082 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007083 size_t num = mAudioSessionRefs.size();
7084 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007085 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007086 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7087 ref->mCnt--;
7088 ALOGV(" decremented refcount to %d", ref->mCnt);
7089 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007090 mAudioSessionRefs.removeAt(i);
7091 delete ref;
7092 purgeStaleEffects_l();
7093 }
7094 return;
7095 }
7096 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007097 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007098}
7099
7100void AudioFlinger::purgeStaleEffects_l() {
7101
Steve Block3856b092011-10-20 11:56:00 +01007102 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007103
7104 Vector< sp<EffectChain> > chains;
7105
7106 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7107 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7108 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7109 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007110 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7111 chains.push(ec);
7112 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007113 }
7114 }
7115 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7116 sp<RecordThread> t = mRecordThreads.valueAt(i);
7117 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7118 sp<EffectChain> ec = t->mEffectChains[j];
7119 chains.push(ec);
7120 }
7121 }
7122
7123 for (size_t i = 0; i < chains.size(); i++) {
7124 sp<EffectChain> ec = chains[i];
7125 int sessionid = ec->sessionId();
7126 sp<ThreadBase> t = ec->mThread.promote();
7127 if (t == 0) {
7128 continue;
7129 }
7130 size_t numsessionrefs = mAudioSessionRefs.size();
7131 bool found = false;
7132 for (size_t k = 0; k < numsessionrefs; k++) {
7133 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007134 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007135 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007136 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007137 found = true;
7138 break;
7139 }
7140 }
7141 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007142 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007143 // remove all effects from the chain
7144 while (ec->mEffects.size()) {
7145 sp<EffectModule> effect = ec->mEffects[0];
7146 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007147 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007148 if (effect->purgeHandles()) {
7149 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007150 }
7151 AudioSystem::unregisterEffect(effect->id());
7152 }
7153 }
7154 }
7155 return;
7156}
7157
Mathias Agopian65ab4712010-07-14 17:59:35 -07007158// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007159AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007160{
Glenn Kastena1117922012-01-26 10:53:32 -08007161 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007162}
7163
7164// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007165AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007166{
7167 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007168 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007169}
7170
7171// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007172AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007173{
Glenn Kastena1117922012-01-26 10:53:32 -08007174 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007175}
7176
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007177uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007178{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007179 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007180}
7181
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007182AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007183{
7184 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7185 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007186 AudioStreamOut *output = thread->getOutput();
7187 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007188 return thread;
7189 }
7190 }
7191 return NULL;
7192}
7193
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007194uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007195{
7196 PlaybackThread *thread = primaryPlaybackThread_l();
7197
7198 if (thread == NULL) {
7199 return 0;
7200 }
7201
7202 return thread->device();
7203}
7204
Eric Laurenta011e352012-03-29 15:51:43 -07007205sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7206 int triggerSession,
7207 int listenerSession,
7208 sync_event_callback_t callBack,
7209 void *cookie)
7210{
7211 Mutex::Autolock _l(mLock);
7212
7213 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7214 status_t playStatus = NAME_NOT_FOUND;
7215 status_t recStatus = NAME_NOT_FOUND;
7216 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7217 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7218 if (playStatus == NO_ERROR) {
7219 return event;
7220 }
7221 }
7222 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7223 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7224 if (recStatus == NO_ERROR) {
7225 return event;
7226 }
7227 }
7228 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7229 mPendingSyncEvents.add(event);
7230 } else {
7231 ALOGV("createSyncEvent() invalid event %d", event->type());
7232 event.clear();
7233 }
7234 return event;
7235}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007236
Mathias Agopian65ab4712010-07-14 17:59:35 -07007237// ----------------------------------------------------------------------------
7238// Effect management
7239// ----------------------------------------------------------------------------
7240
7241
Glenn Kastenf587ba52012-01-26 16:25:10 -08007242status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007243{
7244 Mutex::Autolock _l(mLock);
7245 return EffectQueryNumberEffects(numEffects);
7246}
7247
Glenn Kastenf587ba52012-01-26 16:25:10 -08007248status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007249{
7250 Mutex::Autolock _l(mLock);
7251 return EffectQueryEffect(index, descriptor);
7252}
7253
Glenn Kasten5e92a782012-01-30 07:40:52 -08007254status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007255 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007256{
7257 Mutex::Autolock _l(mLock);
7258 return EffectGetDescriptor(pUuid, descriptor);
7259}
7260
7261
Mathias Agopian65ab4712010-07-14 17:59:35 -07007262sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7263 effect_descriptor_t *pDesc,
7264 const sp<IEffectClient>& effectClient,
7265 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007266 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007267 int sessionId,
7268 status_t *status,
7269 int *id,
7270 int *enabled)
7271{
7272 status_t lStatus = NO_ERROR;
7273 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007274 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007275
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007276 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007277 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007278
7279 if (pDesc == NULL) {
7280 lStatus = BAD_VALUE;
7281 goto Exit;
7282 }
7283
Eric Laurent84e9a102010-09-23 16:10:16 -07007284 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007285 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007286 lStatus = PERMISSION_DENIED;
7287 goto Exit;
7288 }
7289
Dima Zavinfce7a472011-04-19 22:30:36 -07007290 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007291 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007292 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007293 lStatus = PERMISSION_DENIED;
7294 goto Exit;
7295 }
7296
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007297 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007298 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007299 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007300 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007301 lStatus = BAD_VALUE;
7302 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007303 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007304 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007305 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007306 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007307 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007308 }
7309 }
7310
Mathias Agopian65ab4712010-07-14 17:59:35 -07007311 {
7312 Mutex::Autolock _l(mLock);
7313
Mathias Agopian65ab4712010-07-14 17:59:35 -07007314
7315 if (!EffectIsNullUuid(&pDesc->uuid)) {
7316 // if uuid is specified, request effect descriptor
7317 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7318 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007319 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007320 goto Exit;
7321 }
7322 } else {
7323 // if uuid is not specified, look for an available implementation
7324 // of the required type in effect factory
7325 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007326 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007327 lStatus = BAD_VALUE;
7328 goto Exit;
7329 }
7330 uint32_t numEffects = 0;
7331 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007332 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007333 bool found = false;
7334
7335 lStatus = EffectQueryNumberEffects(&numEffects);
7336 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007337 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007338 goto Exit;
7339 }
7340 for (uint32_t i = 0; i < numEffects; i++) {
7341 lStatus = EffectQueryEffect(i, &desc);
7342 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007343 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007344 continue;
7345 }
7346 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7347 // If matching type found save effect descriptor. If the session is
7348 // 0 and the effect is not auxiliary, continue enumeration in case
7349 // an auxiliary version of this effect type is available
7350 found = true;
7351 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07007352 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007353 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7354 break;
7355 }
7356 }
7357 }
7358 if (!found) {
7359 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007360 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007361 goto Exit;
7362 }
7363 // For same effect type, chose auxiliary version over insert version if
7364 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007365 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007366 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7367 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7368 }
7369 }
7370
7371 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007372 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007373 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7374 lStatus = INVALID_OPERATION;
7375 goto Exit;
7376 }
7377
Eric Laurent59255e42011-07-27 19:49:51 -07007378 // check recording permission for visualizer
7379 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7380 !recordingAllowed()) {
7381 lStatus = PERMISSION_DENIED;
7382 goto Exit;
7383 }
7384
Mathias Agopian65ab4712010-07-14 17:59:35 -07007385 // return effect descriptor
7386 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7387
7388 // If output is not specified try to find a matching audio session ID in one of the
7389 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007390 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7391 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007392 // Note: io is never 0 when creating an effect on an input
7393 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007394 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007395 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7396 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007397 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007398 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007399 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007400 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007401 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007402 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7403 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7404 io = mRecordThreads.keyAt(i);
7405 break;
7406 }
7407 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007408 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007409 // If no output thread contains the requested session ID, default to
7410 // first output. The effect chain will be moved to the correct output
7411 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007412 if (io == 0 && mPlaybackThreads.size()) {
7413 io = mPlaybackThreads.keyAt(0);
7414 }
Steve Block3856b092011-10-20 11:56:00 +01007415 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007416 }
7417 ThreadBase *thread = checkRecordThread_l(io);
7418 if (thread == NULL) {
7419 thread = checkPlaybackThread_l(io);
7420 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007421 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007422 lStatus = BAD_VALUE;
7423 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007424 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007425 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007426
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007427 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007428
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007429 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007430 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7431 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007432 if (handle != 0 && id != NULL) {
7433 *id = handle->id();
7434 }
7435 }
7436
7437Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007438 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007439 *status = lStatus;
7440 }
7441 return handle;
7442}
7443
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007444status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7445 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007446{
Steve Block3856b092011-10-20 11:56:00 +01007447 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007448 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007449 Mutex::Autolock _l(mLock);
7450 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007451 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007452 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007453 }
Eric Laurentde070132010-07-13 04:45:46 -07007454 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7455 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007456 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007457 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007458 }
Eric Laurentde070132010-07-13 04:45:46 -07007459 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7460 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007461 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007462 return BAD_VALUE;
7463 }
7464
7465 Mutex::Autolock _dl(dstThread->mLock);
7466 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007467 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007468
Mathias Agopian65ab4712010-07-14 17:59:35 -07007469 return NO_ERROR;
7470}
7471
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007472// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007473status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007474 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007475 AudioFlinger::PlaybackThread *dstThread,
7476 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007477{
Steve Block3856b092011-10-20 11:56:00 +01007478 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007479 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007480
Eric Laurent59255e42011-07-27 19:49:51 -07007481 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007482 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007483 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007484 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007485 return INVALID_OPERATION;
7486 }
7487
Eric Laurent39e94f82010-07-28 01:32:47 -07007488 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007489 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007490 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007491 // removed.
7492 srcThread->removeEffectChain_l(chain);
7493
7494 // transfer all effects one by one so that new effect chain is created on new thread with
7495 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007496 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007497 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007498 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007499 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7500 while (effect != 0) {
7501 srcThread->removeEffect_l(effect);
7502 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007503 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7504 if (effect->state() == EffectModule::ACTIVE ||
7505 effect->state() == EffectModule::STOPPING) {
7506 effect->start();
7507 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007508 // if the move request is not received from audio policy manager, the effect must be
7509 // re-registered with the new strategy and output
7510 if (dstChain == 0) {
7511 dstChain = effect->chain().promote();
7512 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007513 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007514 srcThread->addEffect_l(effect);
7515 return NO_INIT;
7516 }
7517 strategy = dstChain->strategy();
7518 }
7519 if (reRegister) {
7520 AudioSystem::unregisterEffect(effect->id());
7521 AudioSystem::registerEffect(&effect->desc(),
7522 dstOutput,
7523 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007524 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007525 effect->id());
7526 }
Eric Laurentde070132010-07-13 04:45:46 -07007527 effect = chain->getEffectFromId_l(0);
7528 }
7529
7530 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007531}
7532
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007533
Mathias Agopian65ab4712010-07-14 17:59:35 -07007534// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007535sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007536 const sp<AudioFlinger::Client>& client,
7537 const sp<IEffectClient>& effectClient,
7538 int32_t priority,
7539 int sessionId,
7540 effect_descriptor_t *desc,
7541 int *enabled,
7542 status_t *status
7543 )
7544{
7545 sp<EffectModule> effect;
7546 sp<EffectHandle> handle;
7547 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007548 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007549 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007550 bool effectCreated = false;
7551 bool effectRegistered = false;
7552
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007553 lStatus = initCheck();
7554 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007555 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007556 goto Exit;
7557 }
7558
7559 // Do not allow effects with session ID 0 on direct output or duplicating threads
7560 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007561 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007562 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007563 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007564 lStatus = BAD_VALUE;
7565 goto Exit;
7566 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007567 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007568 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007569 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007570 desc->name, desc->flags, mType);
7571 lStatus = BAD_VALUE;
7572 goto Exit;
7573 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007574
Steve Block3856b092011-10-20 11:56:00 +01007575 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007576
7577 { // scope for mLock
7578 Mutex::Autolock _l(mLock);
7579
7580 // check for existing effect chain with the requested audio session
7581 chain = getEffectChain_l(sessionId);
7582 if (chain == 0) {
7583 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007584 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007585 chain = new EffectChain(this, sessionId);
7586 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007587 chain->setStrategy(getStrategyForSession_l(sessionId));
7588 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007589 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007590 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007591 }
7592
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007593 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007594
7595 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007596 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007597 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007598 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007599 if (lStatus != NO_ERROR) {
7600 goto Exit;
7601 }
7602 effectRegistered = true;
7603 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007604 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007605 lStatus = effect->status();
7606 if (lStatus != NO_ERROR) {
7607 goto Exit;
7608 }
Eric Laurentcab11242010-07-15 12:50:15 -07007609 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007610 if (lStatus != NO_ERROR) {
7611 goto Exit;
7612 }
7613 effectCreated = true;
7614
7615 effect->setDevice(mDevice);
7616 effect->setMode(mAudioFlinger->getMode());
7617 }
7618 // create effect handle and connect it to effect module
7619 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007620 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007621 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007622 *enabled = (int)effect->isEnabled();
7623 }
7624 }
7625
7626Exit:
7627 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007628 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007629 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007630 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007631 }
7632 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007633 AudioSystem::unregisterEffect(effect->id());
7634 }
7635 if (chainCreated) {
7636 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007637 }
7638 handle.clear();
7639 }
7640
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007641 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007642 *status = lStatus;
7643 }
7644 return handle;
7645}
7646
Eric Laurent717e1282012-06-29 16:36:52 -07007647sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7648{
7649 Mutex::Autolock _l(mLock);
7650 return getEffect_l(sessionId, effectId);
7651}
7652
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007653sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7654{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007655 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007656 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007657}
7658
Eric Laurentde070132010-07-13 04:45:46 -07007659// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7660// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007661status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007662{
7663 // check for existing effect chain with the requested audio session
7664 int sessionId = effect->sessionId();
7665 sp<EffectChain> chain = getEffectChain_l(sessionId);
7666 bool chainCreated = false;
7667
7668 if (chain == 0) {
7669 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007670 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007671 chain = new EffectChain(this, sessionId);
7672 addEffectChain_l(chain);
7673 chain->setStrategy(getStrategyForSession_l(sessionId));
7674 chainCreated = true;
7675 }
Steve Block3856b092011-10-20 11:56:00 +01007676 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007677
7678 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007679 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007680 this, effect->desc().name, chain.get());
7681 return BAD_VALUE;
7682 }
7683
7684 status_t status = chain->addEffect_l(effect);
7685 if (status != NO_ERROR) {
7686 if (chainCreated) {
7687 removeEffectChain_l(chain);
7688 }
7689 return status;
7690 }
7691
7692 effect->setDevice(mDevice);
7693 effect->setMode(mAudioFlinger->getMode());
7694 return NO_ERROR;
7695}
7696
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007697void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007698
Steve Block3856b092011-10-20 11:56:00 +01007699 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007700 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007701 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7702 detachAuxEffect_l(effect->id());
7703 }
7704
7705 sp<EffectChain> chain = effect->chain().promote();
7706 if (chain != 0) {
7707 // remove effect chain if removing last effect
7708 if (chain->removeEffect_l(effect) == 0) {
7709 removeEffectChain_l(chain);
7710 }
7711 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007712 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007713 }
7714}
7715
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007716void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007717 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007718{
7719 effectChains = mEffectChains;
7720 for (size_t i = 0; i < mEffectChains.size(); i++) {
7721 mEffectChains[i]->lock();
7722 }
7723}
7724
7725void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007726 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007727{
7728 for (size_t i = 0; i < effectChains.size(); i++) {
7729 effectChains[i]->unlock();
7730 }
7731}
7732
7733sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7734{
7735 Mutex::Autolock _l(mLock);
7736 return getEffectChain_l(sessionId);
7737}
7738
7739sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7740{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007741 size_t size = mEffectChains.size();
7742 for (size_t i = 0; i < size; i++) {
7743 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007744 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007745 }
7746 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007747 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007748}
7749
Glenn Kastenf78aee72012-01-04 11:00:47 -08007750void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007751{
7752 Mutex::Autolock _l(mLock);
7753 size_t size = mEffectChains.size();
7754 for (size_t i = 0; i < size; i++) {
7755 mEffectChains[i]->setMode_l(mode);
7756 }
7757}
7758
7759void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007760 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007761 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007762
Mathias Agopian65ab4712010-07-14 17:59:35 -07007763 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007764 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007765 // delete the effect module if removing last handle on it
7766 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007767 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007768 removeEffect_l(effect);
7769 AudioSystem::unregisterEffect(effect->id());
7770 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007771 }
7772}
7773
7774status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7775{
7776 int session = chain->sessionId();
7777 int16_t *buffer = mMixBuffer;
7778 bool ownsBuffer = false;
7779
Steve Block3856b092011-10-20 11:56:00 +01007780 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007781 if (session > 0) {
7782 // Only one effect chain can be present in direct output thread and it uses
7783 // the mix buffer as input
7784 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007785 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007786 buffer = new int16_t[numSamples];
7787 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007788 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007789 ownsBuffer = true;
7790 }
7791
7792 // Attach all tracks with same session ID to this chain.
7793 for (size_t i = 0; i < mTracks.size(); ++i) {
7794 sp<Track> track = mTracks[i];
7795 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007796 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007797 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007798 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007799 }
7800 }
7801
7802 // indicate all active tracks in the chain
7803 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7804 sp<Track> track = mActiveTracks[i].promote();
7805 if (track == 0) continue;
7806 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007807 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007808 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007809 }
7810 }
7811 }
7812
7813 chain->setInBuffer(buffer, ownsBuffer);
7814 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007815 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007816 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007817 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7818 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007819 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007820 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7821 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007822 // Effect chain for other sessions are inserted at beginning of effect
7823 // chains list to be processed before output mix effects. Relative order between other
7824 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007825 size_t size = mEffectChains.size();
7826 size_t i = 0;
7827 for (i = 0; i < size; i++) {
7828 if (mEffectChains[i]->sessionId() < session) break;
7829 }
7830 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007831 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007832
7833 return NO_ERROR;
7834}
7835
7836size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7837{
7838 int session = chain->sessionId();
7839
Steve Block3856b092011-10-20 11:56:00 +01007840 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007841
7842 for (size_t i = 0; i < mEffectChains.size(); i++) {
7843 if (chain == mEffectChains[i]) {
7844 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007845 // detach all active tracks from the chain
7846 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7847 sp<Track> track = mActiveTracks[i].promote();
7848 if (track == 0) continue;
7849 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007850 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007851 chain.get(), session);
7852 chain->decActiveTrackCnt();
7853 }
7854 }
7855
Mathias Agopian65ab4712010-07-14 17:59:35 -07007856 // detach all tracks with same session ID from this chain
7857 for (size_t i = 0; i < mTracks.size(); ++i) {
7858 sp<Track> track = mTracks[i];
7859 if (session == track->sessionId()) {
7860 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007861 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007862 }
7863 }
Eric Laurentde070132010-07-13 04:45:46 -07007864 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007865 }
7866 }
7867 return mEffectChains.size();
7868}
7869
Eric Laurentde070132010-07-13 04:45:46 -07007870status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7871 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007872{
7873 Mutex::Autolock _l(mLock);
7874 return attachAuxEffect_l(track, EffectId);
7875}
7876
Eric Laurentde070132010-07-13 04:45:46 -07007877status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7878 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007879{
7880 status_t status = NO_ERROR;
7881
7882 if (EffectId == 0) {
7883 track->setAuxBuffer(0, NULL);
7884 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007885 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7886 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007887 if (effect != 0) {
7888 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7889 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7890 } else {
7891 status = INVALID_OPERATION;
7892 }
7893 } else {
7894 status = BAD_VALUE;
7895 }
7896 }
7897 return status;
7898}
7899
7900void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7901{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007902 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007903 sp<Track> track = mTracks[i];
7904 if (track->auxEffectId() == effectId) {
7905 attachAuxEffect_l(track, 0);
7906 }
7907 }
7908}
7909
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007910status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7911{
7912 // only one chain per input thread
7913 if (mEffectChains.size() != 0) {
7914 return INVALID_OPERATION;
7915 }
Steve Block3856b092011-10-20 11:56:00 +01007916 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007917
7918 chain->setInBuffer(NULL);
7919 chain->setOutBuffer(NULL);
7920
Eric Laurent59255e42011-07-27 19:49:51 -07007921 checkSuspendOnAddEffectChain_l(chain);
7922
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007923 mEffectChains.add(chain);
7924
7925 return NO_ERROR;
7926}
7927
7928size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7929{
Steve Block3856b092011-10-20 11:56:00 +01007930 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007931 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007932 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7933 chain.get(), mEffectChains.size(), this);
7934 if (mEffectChains.size() == 1) {
7935 mEffectChains.removeAt(0);
7936 }
7937 return 0;
7938}
7939
Mathias Agopian65ab4712010-07-14 17:59:35 -07007940// ----------------------------------------------------------------------------
7941// EffectModule implementation
7942// ----------------------------------------------------------------------------
7943
7944#undef LOG_TAG
7945#define LOG_TAG "AudioFlinger::EffectModule"
7946
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007947AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007948 const wp<AudioFlinger::EffectChain>& chain,
7949 effect_descriptor_t *desc,
7950 int id,
7951 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07007952 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
7953 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
7954 // mDescriptor is set below
7955 // mConfig is set by configure() and not used before then
7956 mEffectInterface(NULL),
7957 mStatus(NO_INIT), mState(IDLE),
7958 // mMaxDisableWaitCnt is set by configure() and not used before then
7959 // mDisableWaitCnt is set by process() and updateState() and not used before then
7960 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007961{
Steve Block3856b092011-10-20 11:56:00 +01007962 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007963 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007964 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007965 return;
7966 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007967
7968 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7969
7970 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007971 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007972
7973 if (mStatus != NO_ERROR) {
7974 return;
7975 }
7976 lStatus = init();
7977 if (lStatus < 0) {
7978 mStatus = lStatus;
7979 goto Error;
7980 }
7981
Steve Block3856b092011-10-20 11:56:00 +01007982 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007983 return;
7984Error:
7985 EffectRelease(mEffectInterface);
7986 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007987 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007988}
7989
7990AudioFlinger::EffectModule::~EffectModule()
7991{
Steve Block3856b092011-10-20 11:56:00 +01007992 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007993 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007994 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7995 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7996 sp<ThreadBase> thread = mThread.promote();
7997 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007998 audio_stream_t *stream = thread->stream();
7999 if (stream != NULL) {
8000 stream->remove_audio_effect(stream, mEffectInterface);
8001 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008002 }
8003 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008004 // release effect engine
8005 EffectRelease(mEffectInterface);
8006 }
8007}
8008
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008009status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008010{
8011 status_t status;
8012
8013 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008014 int priority = handle->priority();
8015 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008016 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008017 size_t i;
8018 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008019 EffectHandle *h = mHandles[i];
8020 if (h == NULL || h->destroyed_l()) continue;
8021 // first non destroyed handle is considered in control
8022 if (controlHandle == NULL)
8023 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008024 if (h->priority() <= priority) break;
8025 }
8026 // if inserted in first place, move effect control from previous owner to this handle
8027 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008028 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008029 if (controlHandle != NULL) {
8030 enabled = controlHandle->enabled();
8031 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008032 }
Eric Laurent59255e42011-07-27 19:49:51 -07008033 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008034 status = NO_ERROR;
8035 } else {
8036 status = ALREADY_EXISTS;
8037 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008038 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008039 mHandles.insertAt(handle, i);
8040 return status;
8041}
8042
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008043size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008044{
8045 Mutex::Autolock _l(mLock);
8046 size_t size = mHandles.size();
8047 size_t i;
8048 for (i = 0; i < size; i++) {
8049 if (mHandles[i] == handle) break;
8050 }
8051 if (i == size) {
8052 return size;
8053 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008054 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008055
Mathias Agopian65ab4712010-07-14 17:59:35 -07008056 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008057 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008058 if (i == 0) {
8059 EffectHandle *h = controlHandle_l();
8060 if (h != NULL) {
8061 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008062 }
8063 }
8064
Eric Laurentec437d82011-07-26 20:54:46 -07008065 // Prevent calls to process() and other functions on effect interface from now on.
8066 // The effect engine will be released by the destructor when the last strong reference on
8067 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008068 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008069 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008070 }
8071
Mathias Agopian65ab4712010-07-14 17:59:35 -07008072 return size;
8073}
8074
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008075// must be called with EffectModule::mLock held
8076AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008077{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008078 // the first valid handle in the list has control over the module
8079 for (size_t i = 0; i < mHandles.size(); i++) {
8080 EffectHandle *h = mHandles[i];
8081 if (h != NULL && !h->destroyed_l()) {
8082 return h;
8083 }
8084 }
8085
8086 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008087}
8088
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008089size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008090{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008091 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008092 // keep a strong reference on this EffectModule to avoid calling the
8093 // destructor before we exit
8094 sp<EffectModule> keep(this);
8095 {
8096 sp<ThreadBase> thread = mThread.promote();
8097 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008098 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008099 }
8100 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008101 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008102}
8103
8104void AudioFlinger::EffectModule::updateState() {
8105 Mutex::Autolock _l(mLock);
8106
8107 switch (mState) {
8108 case RESTART:
8109 reset_l();
8110 // FALL THROUGH
8111
8112 case STARTING:
8113 // clear auxiliary effect input buffer for next accumulation
8114 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8115 memset(mConfig.inputCfg.buffer.raw,
8116 0,
8117 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8118 }
8119 start_l();
8120 mState = ACTIVE;
8121 break;
8122 case STOPPING:
8123 stop_l();
8124 mDisableWaitCnt = mMaxDisableWaitCnt;
8125 mState = STOPPED;
8126 break;
8127 case STOPPED:
8128 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8129 // turn off sequence.
8130 if (--mDisableWaitCnt == 0) {
8131 reset_l();
8132 mState = IDLE;
8133 }
8134 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008135 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008136 break;
8137 }
8138}
8139
8140void AudioFlinger::EffectModule::process()
8141{
8142 Mutex::Autolock _l(mLock);
8143
Eric Laurentec437d82011-07-26 20:54:46 -07008144 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008145 mConfig.inputCfg.buffer.raw == NULL ||
8146 mConfig.outputCfg.buffer.raw == NULL) {
8147 return;
8148 }
8149
Eric Laurent8f45bd72010-08-31 13:50:07 -07008150 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008151 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8152 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008153 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008154 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008155 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008156 }
8157
8158 // do the actual processing in the effect engine
8159 int ret = (*mEffectInterface)->process(mEffectInterface,
8160 &mConfig.inputCfg.buffer,
8161 &mConfig.outputCfg.buffer);
8162
8163 // force transition to IDLE state when engine is ready
8164 if (mState == STOPPED && ret == -ENODATA) {
8165 mDisableWaitCnt = 1;
8166 }
8167
8168 // clear auxiliary effect input buffer for next accumulation
8169 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008170 memset(mConfig.inputCfg.buffer.raw, 0,
8171 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008172 }
8173 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008174 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8175 // If an insert effect is idle and input buffer is different from output buffer,
8176 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008177 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008178 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008179 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8180 int16_t *in = mConfig.inputCfg.buffer.s16;
8181 int16_t *out = mConfig.outputCfg.buffer.s16;
8182 for (size_t i = 0; i < frameCnt; i++) {
8183 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008184 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008185 }
8186 }
8187}
8188
8189void AudioFlinger::EffectModule::reset_l()
8190{
8191 if (mEffectInterface == NULL) {
8192 return;
8193 }
8194 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8195}
8196
8197status_t AudioFlinger::EffectModule::configure()
8198{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008199 if (mEffectInterface == NULL) {
8200 return NO_INIT;
8201 }
8202
8203 sp<ThreadBase> thread = mThread.promote();
8204 if (thread == 0) {
8205 return DEAD_OBJECT;
8206 }
8207
8208 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07008209 audio_channel_mask_t channelMask = thread->channelMask();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008210
8211 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008212 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008213 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07008214 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008215 }
Glenn Kasten254af182012-07-03 14:59:05 -07008216 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07008217 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8218 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008219 mConfig.inputCfg.samplingRate = thread->sampleRate();
8220 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8221 mConfig.inputCfg.bufferProvider.cookie = NULL;
8222 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8223 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8224 mConfig.outputCfg.bufferProvider.cookie = NULL;
8225 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8226 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8227 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8228 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008229 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008230 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008231 // - in other sessions:
8232 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8233 // other effect: overwrites output buffer: input buffer == output buffer
8234 // Auxiliary effect:
8235 // accumulates in output buffer: input buffer != output buffer
8236 // Therefore: accumulate <=> input buffer != output buffer
8237 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8238 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8239 } else {
8240 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8241 }
8242 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8243 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8244 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8245 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8246
Steve Block3856b092011-10-20 11:56:00 +01008247 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008248 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8249
Mathias Agopian65ab4712010-07-14 17:59:35 -07008250 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008251 uint32_t size = sizeof(int);
8252 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008253 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008254 sizeof(effect_config_t),
8255 &mConfig,
8256 &size,
8257 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008258 if (status == 0) {
8259 status = cmdStatus;
8260 }
8261
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008262 if (status == 0 &&
8263 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8264 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8265 effect_param_t *p = (effect_param_t *)buf32;
8266
8267 p->psize = sizeof(uint32_t);
8268 p->vsize = sizeof(uint32_t);
8269 size = sizeof(int);
8270 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8271
8272 uint32_t latency = 0;
8273 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8274 if (pbt != NULL) {
8275 latency = pbt->latency_l();
8276 }
8277
8278 *((int32_t *)p->data + 1)= latency;
8279 (*mEffectInterface)->command(mEffectInterface,
8280 EFFECT_CMD_SET_PARAM,
8281 sizeof(effect_param_t) + 8,
8282 &buf32,
8283 &size,
8284 &cmdStatus);
8285 }
8286
Mathias Agopian65ab4712010-07-14 17:59:35 -07008287 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8288 (1000 * mConfig.outputCfg.buffer.frameCount);
8289
8290 return status;
8291}
8292
8293status_t AudioFlinger::EffectModule::init()
8294{
8295 Mutex::Autolock _l(mLock);
8296 if (mEffectInterface == NULL) {
8297 return NO_INIT;
8298 }
8299 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008300 uint32_t size = sizeof(status_t);
8301 status_t status = (*mEffectInterface)->command(mEffectInterface,
8302 EFFECT_CMD_INIT,
8303 0,
8304 NULL,
8305 &size,
8306 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008307 if (status == 0) {
8308 status = cmdStatus;
8309 }
8310 return status;
8311}
8312
Eric Laurentec35a142011-10-05 17:42:25 -07008313status_t AudioFlinger::EffectModule::start()
8314{
8315 Mutex::Autolock _l(mLock);
8316 return start_l();
8317}
8318
Mathias Agopian65ab4712010-07-14 17:59:35 -07008319status_t AudioFlinger::EffectModule::start_l()
8320{
8321 if (mEffectInterface == NULL) {
8322 return NO_INIT;
8323 }
8324 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008325 uint32_t size = sizeof(status_t);
8326 status_t status = (*mEffectInterface)->command(mEffectInterface,
8327 EFFECT_CMD_ENABLE,
8328 0,
8329 NULL,
8330 &size,
8331 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008332 if (status == 0) {
8333 status = cmdStatus;
8334 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008335 if (status == 0 &&
8336 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8337 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8338 sp<ThreadBase> thread = mThread.promote();
8339 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008340 audio_stream_t *stream = thread->stream();
8341 if (stream != NULL) {
8342 stream->add_audio_effect(stream, mEffectInterface);
8343 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008344 }
8345 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008346 return status;
8347}
8348
Eric Laurentec437d82011-07-26 20:54:46 -07008349status_t AudioFlinger::EffectModule::stop()
8350{
8351 Mutex::Autolock _l(mLock);
8352 return stop_l();
8353}
8354
Mathias Agopian65ab4712010-07-14 17:59:35 -07008355status_t AudioFlinger::EffectModule::stop_l()
8356{
8357 if (mEffectInterface == NULL) {
8358 return NO_INIT;
8359 }
8360 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008361 uint32_t size = sizeof(status_t);
8362 status_t status = (*mEffectInterface)->command(mEffectInterface,
8363 EFFECT_CMD_DISABLE,
8364 0,
8365 NULL,
8366 &size,
8367 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008368 if (status == 0) {
8369 status = cmdStatus;
8370 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008371 if (status == 0 &&
8372 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8373 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8374 sp<ThreadBase> thread = mThread.promote();
8375 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008376 audio_stream_t *stream = thread->stream();
8377 if (stream != NULL) {
8378 stream->remove_audio_effect(stream, mEffectInterface);
8379 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008380 }
8381 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008382 return status;
8383}
8384
Eric Laurent25f43952010-07-28 05:40:18 -07008385status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8386 uint32_t cmdSize,
8387 void *pCmdData,
8388 uint32_t *replySize,
8389 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008390{
8391 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008392// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008393
Eric Laurentec437d82011-07-26 20:54:46 -07008394 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008395 return NO_INIT;
8396 }
Eric Laurent25f43952010-07-28 05:40:18 -07008397 status_t status = (*mEffectInterface)->command(mEffectInterface,
8398 cmdCode,
8399 cmdSize,
8400 pCmdData,
8401 replySize,
8402 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008403 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008404 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008405 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008406 EffectHandle *h = mHandles[i];
8407 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008408 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8409 }
8410 }
8411 }
8412 return status;
8413}
8414
8415status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8416{
8417 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008418 return setEnabled_l(enabled);
8419}
8420
8421// must be called with EffectModule::mLock held
8422status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8423{
8424
Steve Block3856b092011-10-20 11:56:00 +01008425 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008426
8427 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008428 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8429 if (enabled && status != NO_ERROR) {
8430 return status;
8431 }
8432
Mathias Agopian65ab4712010-07-14 17:59:35 -07008433 switch (mState) {
8434 // going from disabled to enabled
8435 case IDLE:
8436 mState = STARTING;
8437 break;
8438 case STOPPED:
8439 mState = RESTART;
8440 break;
8441 case STOPPING:
8442 mState = ACTIVE;
8443 break;
8444
8445 // going from enabled to disabled
8446 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008447 mState = STOPPED;
8448 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008449 case STARTING:
8450 mState = IDLE;
8451 break;
8452 case ACTIVE:
8453 mState = STOPPING;
8454 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008455 case DESTROYED:
8456 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008457 }
8458 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008459 EffectHandle *h = mHandles[i];
8460 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008461 h->setEnabled(enabled);
8462 }
8463 }
8464 }
8465 return NO_ERROR;
8466}
8467
Glenn Kastenc59c0042012-02-02 14:06:11 -08008468bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008469{
8470 switch (mState) {
8471 case RESTART:
8472 case STARTING:
8473 case ACTIVE:
8474 return true;
8475 case IDLE:
8476 case STOPPING:
8477 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008478 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008479 default:
8480 return false;
8481 }
8482}
8483
Glenn Kastenc59c0042012-02-02 14:06:11 -08008484bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008485{
8486 switch (mState) {
8487 case RESTART:
8488 case ACTIVE:
8489 case STOPPING:
8490 case STOPPED:
8491 return true;
8492 case IDLE:
8493 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008494 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008495 default:
8496 return false;
8497 }
8498}
8499
Mathias Agopian65ab4712010-07-14 17:59:35 -07008500status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8501{
8502 Mutex::Autolock _l(mLock);
8503 status_t status = NO_ERROR;
8504
8505 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8506 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008507 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008508 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8509 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008510 status_t cmdStatus;
8511 uint32_t volume[2];
8512 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008513 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008514 volume[0] = *left;
8515 volume[1] = *right;
8516 if (controller) {
8517 pVolume = volume;
8518 }
Eric Laurent25f43952010-07-28 05:40:18 -07008519 status = (*mEffectInterface)->command(mEffectInterface,
8520 EFFECT_CMD_SET_VOLUME,
8521 size,
8522 volume,
8523 &size,
8524 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008525 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8526 *left = volume[0];
8527 *right = volume[1];
8528 }
8529 }
8530 return status;
8531}
8532
8533status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8534{
8535 Mutex::Autolock _l(mLock);
8536 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008537 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8538 // audio pre processing modules on RecordThread can receive both output and
8539 // input device indication in the same call
8540 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8541 if (dev) {
8542 status_t cmdStatus;
8543 uint32_t size = sizeof(status_t);
8544
8545 status = (*mEffectInterface)->command(mEffectInterface,
8546 EFFECT_CMD_SET_DEVICE,
8547 sizeof(uint32_t),
8548 &dev,
8549 &size,
8550 &cmdStatus);
8551 if (status == NO_ERROR) {
8552 status = cmdStatus;
8553 }
8554 }
8555 dev = device & AUDIO_DEVICE_IN_ALL;
8556 if (dev) {
8557 status_t cmdStatus;
8558 uint32_t size = sizeof(status_t);
8559
8560 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8561 EFFECT_CMD_SET_INPUT_DEVICE,
8562 sizeof(uint32_t),
8563 &dev,
8564 &size,
8565 &cmdStatus);
8566 if (status2 == NO_ERROR) {
8567 status2 = cmdStatus;
8568 }
8569 if (status == NO_ERROR) {
8570 status = status2;
8571 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008572 }
8573 }
8574 return status;
8575}
8576
Glenn Kastenf78aee72012-01-04 11:00:47 -08008577status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008578{
8579 Mutex::Autolock _l(mLock);
8580 status_t status = NO_ERROR;
8581 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008582 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008583 uint32_t size = sizeof(status_t);
8584 status = (*mEffectInterface)->command(mEffectInterface,
8585 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008586 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008587 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008588 &size,
8589 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008590 if (status == NO_ERROR) {
8591 status = cmdStatus;
8592 }
8593 }
8594 return status;
8595}
8596
Eric Laurent59255e42011-07-27 19:49:51 -07008597void AudioFlinger::EffectModule::setSuspended(bool suspended)
8598{
8599 Mutex::Autolock _l(mLock);
8600 mSuspended = suspended;
8601}
Glenn Kastena3a85482012-01-04 11:01:11 -08008602
8603bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008604{
8605 Mutex::Autolock _l(mLock);
8606 return mSuspended;
8607}
8608
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008609bool AudioFlinger::EffectModule::purgeHandles()
8610{
8611 bool enabled = false;
8612 Mutex::Autolock _l(mLock);
8613 for (size_t i = 0; i < mHandles.size(); i++) {
8614 EffectHandle *handle = mHandles[i];
8615 if (handle != NULL && !handle->destroyed_l()) {
8616 handle->effect().clear();
8617 if (handle->hasControl()) {
8618 enabled = handle->enabled();
8619 }
8620 }
8621 }
8622 return enabled;
8623}
8624
Mathias Agopian65ab4712010-07-14 17:59:35 -07008625status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8626{
8627 const size_t SIZE = 256;
8628 char buffer[SIZE];
8629 String8 result;
8630
8631 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8632 result.append(buffer);
8633
8634 bool locked = tryLock(mLock);
8635 // failed to lock - AudioFlinger is probably deadlocked
8636 if (!locked) {
8637 result.append("\t\tCould not lock Fx mutex:\n");
8638 }
8639
8640 result.append("\t\tSession Status State Engine:\n");
8641 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8642 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8643 result.append(buffer);
8644
8645 result.append("\t\tDescriptor:\n");
8646 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8647 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8648 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8649 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8650 result.append(buffer);
8651 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8652 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8653 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8654 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8655 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008656 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008657 mDescriptor.apiVersion,
8658 mDescriptor.flags);
8659 result.append(buffer);
8660 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8661 mDescriptor.name);
8662 result.append(buffer);
8663 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8664 mDescriptor.implementor);
8665 result.append(buffer);
8666
8667 result.append("\t\t- Input configuration:\n");
8668 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8669 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8670 (uint32_t)mConfig.inputCfg.buffer.raw,
8671 mConfig.inputCfg.buffer.frameCount,
8672 mConfig.inputCfg.samplingRate,
8673 mConfig.inputCfg.channels,
8674 mConfig.inputCfg.format);
8675 result.append(buffer);
8676
8677 result.append("\t\t- Output configuration:\n");
8678 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8679 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8680 (uint32_t)mConfig.outputCfg.buffer.raw,
8681 mConfig.outputCfg.buffer.frameCount,
8682 mConfig.outputCfg.samplingRate,
8683 mConfig.outputCfg.channels,
8684 mConfig.outputCfg.format);
8685 result.append(buffer);
8686
8687 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8688 result.append(buffer);
8689 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8690 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008691 EffectHandle *handle = mHandles[i];
8692 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008693 handle->dump(buffer, SIZE);
8694 result.append(buffer);
8695 }
8696 }
8697
8698 result.append("\n");
8699
8700 write(fd, result.string(), result.length());
8701
8702 if (locked) {
8703 mLock.unlock();
8704 }
8705
8706 return NO_ERROR;
8707}
8708
8709// ----------------------------------------------------------------------------
8710// EffectHandle implementation
8711// ----------------------------------------------------------------------------
8712
8713#undef LOG_TAG
8714#define LOG_TAG "AudioFlinger::EffectHandle"
8715
8716AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8717 const sp<AudioFlinger::Client>& client,
8718 const sp<IEffectClient>& effectClient,
8719 int32_t priority)
8720 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008721 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008722 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008723{
Steve Block3856b092011-10-20 11:56:00 +01008724 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008725
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008726 if (client == 0) {
8727 return;
8728 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008729 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8730 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8731 if (mCblkMemory != 0) {
8732 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8733
Glenn Kastena0d68332012-01-27 16:47:15 -08008734 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008735 new(mCblk) effect_param_cblk_t();
8736 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008737 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008738 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008739 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008740 return;
8741 }
8742}
8743
8744AudioFlinger::EffectHandle::~EffectHandle()
8745{
Steve Block3856b092011-10-20 11:56:00 +01008746 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008747
8748 if (mEffect == 0) {
8749 mDestroyed = true;
8750 return;
8751 }
8752 mEffect->lock();
8753 mDestroyed = true;
8754 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008755 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008756}
8757
8758status_t AudioFlinger::EffectHandle::enable()
8759{
Steve Block3856b092011-10-20 11:56:00 +01008760 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008761 if (!mHasControl) return INVALID_OPERATION;
8762 if (mEffect == 0) return DEAD_OBJECT;
8763
Eric Laurentdb7c0792011-08-10 10:37:50 -07008764 if (mEnabled) {
8765 return NO_ERROR;
8766 }
8767
Eric Laurent59255e42011-07-27 19:49:51 -07008768 mEnabled = true;
8769
8770 sp<ThreadBase> thread = mEffect->thread().promote();
8771 if (thread != 0) {
8772 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8773 }
8774
8775 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8776 if (mEffect->suspended()) {
8777 return NO_ERROR;
8778 }
8779
Eric Laurentdb7c0792011-08-10 10:37:50 -07008780 status_t status = mEffect->setEnabled(true);
8781 if (status != NO_ERROR) {
8782 if (thread != 0) {
8783 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8784 }
8785 mEnabled = false;
8786 }
8787 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008788}
8789
8790status_t AudioFlinger::EffectHandle::disable()
8791{
Steve Block3856b092011-10-20 11:56:00 +01008792 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008793 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008794 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008795
Eric Laurentdb7c0792011-08-10 10:37:50 -07008796 if (!mEnabled) {
8797 return NO_ERROR;
8798 }
Eric Laurent59255e42011-07-27 19:49:51 -07008799 mEnabled = false;
8800
8801 if (mEffect->suspended()) {
8802 return NO_ERROR;
8803 }
8804
8805 status_t status = mEffect->setEnabled(false);
8806
8807 sp<ThreadBase> thread = mEffect->thread().promote();
8808 if (thread != 0) {
8809 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8810 }
8811
8812 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008813}
8814
8815void AudioFlinger::EffectHandle::disconnect()
8816{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008817 disconnect(true);
8818}
8819
Glenn Kasten58123c32012-02-03 10:32:24 -08008820void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008821{
Glenn Kasten58123c32012-02-03 10:32:24 -08008822 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008823 if (mEffect == 0) {
8824 return;
8825 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008826 // restore suspended effects if the disconnected handle was enabled and the last one.
8827 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008828 sp<ThreadBase> thread = mEffect->thread().promote();
8829 if (thread != 0) {
8830 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8831 }
Eric Laurent59255e42011-07-27 19:49:51 -07008832 }
8833
Mathias Agopian65ab4712010-07-14 17:59:35 -07008834 // release sp on module => module destructor can be called now
8835 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008836 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008837 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008838 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008839 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8840 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008841 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008842 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008843 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8844 mClient.clear();
8845 }
8846}
8847
Eric Laurent25f43952010-07-28 05:40:18 -07008848status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8849 uint32_t cmdSize,
8850 void *pCmdData,
8851 uint32_t *replySize,
8852 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008853{
Steve Block3856b092011-10-20 11:56:00 +01008854// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008855// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008856
8857 // only get parameter command is permitted for applications not controlling the effect
8858 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8859 return INVALID_OPERATION;
8860 }
8861 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008862 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008863
8864 // handle commands that are not forwarded transparently to effect engine
8865 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8866 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8867 // no risk to block the whole media server process or mixer threads is we are stuck here
8868 Mutex::Autolock _l(mCblk->lock);
8869 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8870 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8871 mCblk->serverIndex = 0;
8872 mCblk->clientIndex = 0;
8873 return BAD_VALUE;
8874 }
8875 status_t status = NO_ERROR;
8876 while (mCblk->serverIndex < mCblk->clientIndex) {
8877 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008878 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008879 int *p = (int *)(mBuffer + mCblk->serverIndex);
8880 int size = *p++;
8881 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008882 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008883 break;
8884 }
8885 effect_param_t *param = (effect_param_t *)p;
8886 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008887 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008888 mCblk->serverIndex += size;
8889 continue;
8890 }
Eric Laurent25f43952010-07-28 05:40:18 -07008891 uint32_t psize = sizeof(effect_param_t) +
8892 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8893 param->vsize;
8894 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8895 psize,
8896 p,
8897 &rsize,
8898 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008899 // stop at first error encountered
8900 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008901 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008902 *(int *)pReplyData = reply;
8903 break;
8904 } else if (reply != NO_ERROR) {
8905 *(int *)pReplyData = reply;
8906 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008907 }
8908 mCblk->serverIndex += size;
8909 }
8910 mCblk->serverIndex = 0;
8911 mCblk->clientIndex = 0;
8912 return status;
8913 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008914 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008915 return enable();
8916 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008917 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008918 return disable();
8919 }
8920
8921 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8922}
8923
Eric Laurent59255e42011-07-27 19:49:51 -07008924void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008925{
Steve Block3856b092011-10-20 11:56:00 +01008926 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008927
8928 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008929 mEnabled = enabled;
8930
Mathias Agopian65ab4712010-07-14 17:59:35 -07008931 if (signal && mEffectClient != 0) {
8932 mEffectClient->controlStatusChanged(hasControl);
8933 }
8934}
8935
Eric Laurent25f43952010-07-28 05:40:18 -07008936void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8937 uint32_t cmdSize,
8938 void *pCmdData,
8939 uint32_t replySize,
8940 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008941{
8942 if (mEffectClient != 0) {
8943 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8944 }
8945}
8946
8947
8948
8949void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8950{
8951 if (mEffectClient != 0) {
8952 mEffectClient->enableStatusChanged(enabled);
8953 }
8954}
8955
8956status_t AudioFlinger::EffectHandle::onTransact(
8957 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8958{
8959 return BnEffect::onTransact(code, data, reply, flags);
8960}
8961
8962
8963void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8964{
Glenn Kastena0d68332012-01-27 16:47:15 -08008965 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008966
8967 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008968 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008969 mPriority,
8970 mHasControl,
8971 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008972 mCblk ? mCblk->clientIndex : 0,
8973 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008974 );
8975
8976 if (locked) {
8977 mCblk->lock.unlock();
8978 }
8979}
8980
8981#undef LOG_TAG
8982#define LOG_TAG "AudioFlinger::EffectChain"
8983
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008984AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008985 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008986 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008987 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8988 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008989{
Dima Zavinfce7a472011-04-19 22:30:36 -07008990 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008991 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008992 return;
8993 }
8994 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8995 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008996}
8997
8998AudioFlinger::EffectChain::~EffectChain()
8999{
9000 if (mOwnInBuffer) {
9001 delete mInBuffer;
9002 }
9003
9004}
9005
Eric Laurent59255e42011-07-27 19:49:51 -07009006// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009007sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009008{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009009 size_t size = mEffects.size();
9010
9011 for (size_t i = 0; i < size; i++) {
9012 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009013 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009014 }
9015 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009016 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009017}
9018
Eric Laurent59255e42011-07-27 19:49:51 -07009019// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009020sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009021{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009022 size_t size = mEffects.size();
9023
9024 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009025 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9026 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009027 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009028 }
9029 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009030 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009031}
9032
Eric Laurent59255e42011-07-27 19:49:51 -07009033// getEffectFromType_l() must be called with ThreadBase::mLock held
9034sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9035 const effect_uuid_t *type)
9036{
Eric Laurent59255e42011-07-27 19:49:51 -07009037 size_t size = mEffects.size();
9038
9039 for (size_t i = 0; i < size; i++) {
9040 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009041 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009042 }
9043 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009044 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009045}
9046
Eric Laurent91b14c42012-05-30 12:30:29 -07009047void AudioFlinger::EffectChain::clearInputBuffer()
9048{
9049 Mutex::Autolock _l(mLock);
9050 sp<ThreadBase> thread = mThread.promote();
9051 if (thread == 0) {
9052 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9053 return;
9054 }
9055 clearInputBuffer_l(thread);
9056}
9057
9058// Must be called with EffectChain::mLock locked
9059void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9060{
9061 size_t numSamples = thread->frameCount() * thread->channelCount();
9062 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9063
9064}
9065
Mathias Agopian65ab4712010-07-14 17:59:35 -07009066// Must be called with EffectChain::mLock locked
9067void AudioFlinger::EffectChain::process_l()
9068{
Eric Laurentdac69112010-09-28 14:09:57 -07009069 sp<ThreadBase> thread = mThread.promote();
9070 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009071 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009072 return;
9073 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009074 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9075 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009076 // always process effects unless no more tracks are on the session and the effect tail
9077 // has been rendered
9078 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009079 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009080 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009081
Eric Laurent544fe9b2011-11-11 15:42:52 -08009082 if (!tracksOnSession && mTailBufferCount == 0) {
9083 doProcess = false;
9084 }
9085
9086 if (activeTrackCnt() == 0) {
9087 // if no track is active and the effect tail has not been rendered,
9088 // the input buffer must be cleared here as the mixer process will not do it
9089 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009090 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009091 if (mTailBufferCount > 0) {
9092 mTailBufferCount--;
9093 }
9094 }
9095 }
Eric Laurentdac69112010-09-28 14:09:57 -07009096 }
9097
Mathias Agopian65ab4712010-07-14 17:59:35 -07009098 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009099 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009100 for (size_t i = 0; i < size; i++) {
9101 mEffects[i]->process();
9102 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009103 }
9104 for (size_t i = 0; i < size; i++) {
9105 mEffects[i]->updateState();
9106 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009107}
9108
Eric Laurentcab11242010-07-15 12:50:15 -07009109// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009110status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009111{
9112 effect_descriptor_t desc = effect->desc();
9113 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9114
9115 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009116 effect->setChain(this);
9117 sp<ThreadBase> thread = mThread.promote();
9118 if (thread == 0) {
9119 return NO_INIT;
9120 }
9121 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009122
9123 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9124 // Auxiliary effects are inserted at the beginning of mEffects vector as
9125 // they are processed first and accumulated in chain input buffer
9126 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009127
Mathias Agopian65ab4712010-07-14 17:59:35 -07009128 // the input buffer for auxiliary effect contains mono samples in
9129 // 32 bit format. This is to avoid saturation in AudoMixer
9130 // accumulation stage. Saturation is done in EffectModule::process() before
9131 // calling the process in effect engine
9132 size_t numSamples = thread->frameCount();
9133 int32_t *buffer = new int32_t[numSamples];
9134 memset(buffer, 0, numSamples * sizeof(int32_t));
9135 effect->setInBuffer((int16_t *)buffer);
9136 // auxiliary effects output samples to chain input buffer for further processing
9137 // by insert effects
9138 effect->setOutBuffer(mInBuffer);
9139 } else {
9140 // Insert effects are inserted at the end of mEffects vector as they are processed
9141 // after track and auxiliary effects.
9142 // Insert effect order as a function of indicated preference:
9143 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9144 // another effect is present
9145 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9146 // last effect claiming first position
9147 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9148 // first effect claiming last position
9149 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9150 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9151 // already present
9152
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009153 size_t size = mEffects.size();
9154 size_t idx_insert = size;
9155 ssize_t idx_insert_first = -1;
9156 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009157
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009158 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009159 effect_descriptor_t d = mEffects[i]->desc();
9160 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9161 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9162 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9163 // check invalid effect chaining combinations
9164 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9165 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009166 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009167 return INVALID_OPERATION;
9168 }
9169 // remember position of first insert effect and by default
9170 // select this as insert position for new effect
9171 if (idx_insert == size) {
9172 idx_insert = i;
9173 }
9174 // remember position of last insert effect claiming
9175 // first position
9176 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9177 idx_insert_first = i;
9178 }
9179 // remember position of first insert effect claiming
9180 // last position
9181 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9182 idx_insert_last == -1) {
9183 idx_insert_last = i;
9184 }
9185 }
9186 }
9187
9188 // modify idx_insert from first position if needed
9189 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9190 if (idx_insert_last != -1) {
9191 idx_insert = idx_insert_last;
9192 } else {
9193 idx_insert = size;
9194 }
9195 } else {
9196 if (idx_insert_first != -1) {
9197 idx_insert = idx_insert_first + 1;
9198 }
9199 }
9200
9201 // always read samples from chain input buffer
9202 effect->setInBuffer(mInBuffer);
9203
9204 // if last effect in the chain, output samples to chain
9205 // output buffer, otherwise to chain input buffer
9206 if (idx_insert == size) {
9207 if (idx_insert != 0) {
9208 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9209 mEffects[idx_insert-1]->configure();
9210 }
9211 effect->setOutBuffer(mOutBuffer);
9212 } else {
9213 effect->setOutBuffer(mInBuffer);
9214 }
9215 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009216
Steve Block3856b092011-10-20 11:56:00 +01009217 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009218 }
9219 effect->configure();
9220 return NO_ERROR;
9221}
9222
Eric Laurentcab11242010-07-15 12:50:15 -07009223// removeEffect_l() must be called with PlaybackThread::mLock held
9224size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009225{
9226 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009227 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009228 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9229
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009230 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009231 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009232 // calling stop here will remove pre-processing effect from the audio HAL.
9233 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9234 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009235 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9236 mEffects[i]->state() == EffectModule::STOPPING) {
9237 mEffects[i]->stop();
9238 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009239 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9240 delete[] effect->inBuffer();
9241 } else {
9242 if (i == size - 1 && i != 0) {
9243 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9244 mEffects[i - 1]->configure();
9245 }
9246 }
9247 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009248 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009249 break;
9250 }
9251 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009252
9253 return mEffects.size();
9254}
9255
Eric Laurentcab11242010-07-15 12:50:15 -07009256// setDevice_l() must be called with PlaybackThread::mLock held
9257void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009258{
9259 size_t size = mEffects.size();
9260 for (size_t i = 0; i < size; i++) {
9261 mEffects[i]->setDevice(device);
9262 }
9263}
9264
Eric Laurentcab11242010-07-15 12:50:15 -07009265// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009266void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009267{
9268 size_t size = mEffects.size();
9269 for (size_t i = 0; i < size; i++) {
9270 mEffects[i]->setMode(mode);
9271 }
9272}
9273
Eric Laurentcab11242010-07-15 12:50:15 -07009274// setVolume_l() must be called with PlaybackThread::mLock held
9275bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009276{
9277 uint32_t newLeft = *left;
9278 uint32_t newRight = *right;
9279 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009280 int ctrlIdx = -1;
9281 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009282
Eric Laurentcab11242010-07-15 12:50:15 -07009283 // first update volume controller
9284 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009285 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009286 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9287 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009288 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009289 break;
9290 }
9291 }
9292
9293 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009294 if (hasControl) {
9295 *left = mNewLeftVolume;
9296 *right = mNewRightVolume;
9297 }
9298 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009299 }
9300
9301 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009302 mLeftVolume = newLeft;
9303 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009304
9305 // second get volume update from volume controller
9306 if (ctrlIdx >= 0) {
9307 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009308 mNewLeftVolume = newLeft;
9309 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009310 }
9311 // then indicate volume to all other effects in chain.
9312 // Pass altered volume to effects before volume controller
9313 // and requested volume to effects after controller
9314 uint32_t lVol = newLeft;
9315 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009316
Mathias Agopian65ab4712010-07-14 17:59:35 -07009317 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009318 if ((int)i == ctrlIdx) continue;
9319 // this also works for ctrlIdx == -1 when there is no volume controller
9320 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009321 lVol = *left;
9322 rVol = *right;
9323 }
9324 mEffects[i]->setVolume(&lVol, &rVol, false);
9325 }
9326 *left = newLeft;
9327 *right = newRight;
9328
9329 return hasControl;
9330}
9331
Mathias Agopian65ab4712010-07-14 17:59:35 -07009332status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9333{
9334 const size_t SIZE = 256;
9335 char buffer[SIZE];
9336 String8 result;
9337
9338 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9339 result.append(buffer);
9340
9341 bool locked = tryLock(mLock);
9342 // failed to lock - AudioFlinger is probably deadlocked
9343 if (!locked) {
9344 result.append("\tCould not lock mutex:\n");
9345 }
9346
Eric Laurentcab11242010-07-15 12:50:15 -07009347 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9348 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009349 mEffects.size(),
9350 (uint32_t)mInBuffer,
9351 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009352 mActiveTrackCnt);
9353 result.append(buffer);
9354 write(fd, result.string(), result.size());
9355
9356 for (size_t i = 0; i < mEffects.size(); ++i) {
9357 sp<EffectModule> effect = mEffects[i];
9358 if (effect != 0) {
9359 effect->dump(fd, args);
9360 }
9361 }
9362
9363 if (locked) {
9364 mLock.unlock();
9365 }
9366
9367 return NO_ERROR;
9368}
9369
Eric Laurent59255e42011-07-27 19:49:51 -07009370// must be called with ThreadBase::mLock held
9371void AudioFlinger::EffectChain::setEffectSuspended_l(
9372 const effect_uuid_t *type, bool suspend)
9373{
9374 sp<SuspendedEffectDesc> desc;
9375 // use effect type UUID timelow as key as there is no real risk of identical
9376 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009377 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009378 if (suspend) {
9379 if (index >= 0) {
9380 desc = mSuspendedEffects.valueAt(index);
9381 } else {
9382 desc = new SuspendedEffectDesc();
9383 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9384 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009385 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009386 }
9387 if (desc->mRefCount++ == 0) {
9388 sp<EffectModule> effect = getEffectIfEnabled(type);
9389 if (effect != 0) {
9390 desc->mEffect = effect;
9391 effect->setSuspended(true);
9392 effect->setEnabled(false);
9393 }
9394 }
9395 } else {
9396 if (index < 0) {
9397 return;
9398 }
9399 desc = mSuspendedEffects.valueAt(index);
9400 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009401 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009402 desc->mRefCount = 1;
9403 }
9404 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009405 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009406 if (desc->mEffect != 0) {
9407 sp<EffectModule> effect = desc->mEffect.promote();
9408 if (effect != 0) {
9409 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009410 effect->lock();
9411 EffectHandle *handle = effect->controlHandle_l();
9412 if (handle != NULL && !handle->destroyed_l()) {
9413 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009414 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009415 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009416 }
9417 desc->mEffect.clear();
9418 }
9419 mSuspendedEffects.removeItemsAt(index);
9420 }
9421 }
9422}
9423
9424// must be called with ThreadBase::mLock held
9425void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9426{
9427 sp<SuspendedEffectDesc> desc;
9428
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009429 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009430 if (suspend) {
9431 if (index >= 0) {
9432 desc = mSuspendedEffects.valueAt(index);
9433 } else {
9434 desc = new SuspendedEffectDesc();
9435 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009436 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009437 }
9438 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009439 Vector< sp<EffectModule> > effects;
9440 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009441 for (size_t i = 0; i < effects.size(); i++) {
9442 setEffectSuspended_l(&effects[i]->desc().type, true);
9443 }
9444 }
9445 } else {
9446 if (index < 0) {
9447 return;
9448 }
9449 desc = mSuspendedEffects.valueAt(index);
9450 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009451 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009452 desc->mRefCount = 1;
9453 }
9454 if (--desc->mRefCount == 0) {
9455 Vector<const effect_uuid_t *> types;
9456 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9457 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9458 continue;
9459 }
9460 types.add(&mSuspendedEffects.valueAt(i)->mType);
9461 }
9462 for (size_t i = 0; i < types.size(); i++) {
9463 setEffectSuspended_l(types[i], false);
9464 }
Steve Block3856b092011-10-20 11:56:00 +01009465 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009466 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9467 }
9468 }
9469}
9470
Eric Laurent6bffdb82011-09-23 08:40:41 -07009471
9472// The volume effect is used for automated tests only
9473#ifndef OPENSL_ES_H_
9474static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9475 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9476const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9477#endif //OPENSL_ES_H_
9478
Eric Laurentdb7c0792011-08-10 10:37:50 -07009479bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9480{
9481 // auxiliary effects and visualizer are never suspended on output mix
9482 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9483 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009484 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9485 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009486 return false;
9487 }
9488 return true;
9489}
9490
Glenn Kastend0539712012-01-30 12:56:03 -08009491void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009492{
Glenn Kastend0539712012-01-30 12:56:03 -08009493 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009494 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009495 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9496 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009497 }
Eric Laurent59255e42011-07-27 19:49:51 -07009498 }
Eric Laurent59255e42011-07-27 19:49:51 -07009499}
9500
9501sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9502 const effect_uuid_t *type)
9503{
Glenn Kasten090f0192012-01-30 13:00:02 -08009504 sp<EffectModule> effect = getEffectFromType_l(type);
9505 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009506}
9507
9508void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9509 bool enabled)
9510{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009511 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009512 if (enabled) {
9513 if (index < 0) {
9514 // if the effect is not suspend check if all effects are suspended
9515 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9516 if (index < 0) {
9517 return;
9518 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009519 if (!isEffectEligibleForSuspend(effect->desc())) {
9520 return;
9521 }
Eric Laurent59255e42011-07-27 19:49:51 -07009522 setEffectSuspended_l(&effect->desc().type, enabled);
9523 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009524 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009525 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009526 return;
9527 }
Eric Laurent59255e42011-07-27 19:49:51 -07009528 }
Steve Block3856b092011-10-20 11:56:00 +01009529 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009530 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009531 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9532 // if effect is requested to suspended but was not yet enabled, supend it now.
9533 if (desc->mEffect == 0) {
9534 desc->mEffect = effect;
9535 effect->setEnabled(false);
9536 effect->setSuspended(true);
9537 }
9538 } else {
9539 if (index < 0) {
9540 return;
9541 }
Steve Block3856b092011-10-20 11:56:00 +01009542 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009543 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009544 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9545 desc->mEffect.clear();
9546 effect->setSuspended(false);
9547 }
9548}
9549
Mathias Agopian65ab4712010-07-14 17:59:35 -07009550#undef LOG_TAG
9551#define LOG_TAG "AudioFlinger"
9552
9553// ----------------------------------------------------------------------------
9554
9555status_t AudioFlinger::onTransact(
9556 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9557{
9558 return BnAudioFlinger::onTransact(code, data, reply, flags);
9559}
9560
Mathias Agopian65ab4712010-07-14 17:59:35 -07009561}; // namespace android