blob: 913cba0af43a423431be9fe44e16c6fccf430b94 [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{
Dima Zavin799a70e2011-04-18 16:57:27 -0700249
Mathias Agopian65ab4712010-07-14 17:59:35 -0700250 while (!mRecordThreads.isEmpty()) {
251 // closeInput() will remove first entry from mRecordThreads
252 closeInput(mRecordThreads.keyAt(0));
253 }
254 while (!mPlaybackThreads.isEmpty()) {
255 // closeOutput() will remove first entry from mPlaybackThreads
256 closeOutput(mPlaybackThreads.keyAt(0));
257 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700258
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800259 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
260 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700261 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
262 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700263 }
264}
265
Eric Laurenta4c5a552012-03-29 10:12:40 -0700266static const char * const audio_interfaces[] = {
267 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
268 AUDIO_HARDWARE_MODULE_ID_A2DP,
269 AUDIO_HARDWARE_MODULE_ID_USB,
270};
271#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
272
273audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(audio_module_handle_t module, uint32_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700274{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700275 // if module is 0, the request comes from an old policy manager and we should load
276 // well known modules
277 if (module == 0) {
278 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
279 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
280 loadHwModule_l(audio_interfaces[i]);
281 }
282 } else {
283 // check a match for the requested module handle
284 AudioHwDevice *audioHwdevice = mAudioHwDevs.valueFor(module);
285 if (audioHwdevice != NULL) {
286 return audioHwdevice->hwDevice();
287 }
288 }
289 // then try to find a module supporting the requested device.
Dima Zavin799a70e2011-04-18 16:57:27 -0700290 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700291 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700292 if ((dev->get_supported_devices(dev) & devices) == devices)
293 return dev;
294 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700295
Dima Zavin799a70e2011-04-18 16:57:27 -0700296 return NULL;
297}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700298
299status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
300{
301 const size_t SIZE = 256;
302 char buffer[SIZE];
303 String8 result;
304
305 result.append("Clients:\n");
306 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800307 sp<Client> client = mClients.valueAt(i).promote();
308 if (client != 0) {
309 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
310 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700311 }
312 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700313
314 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800315 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700316 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
317 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800318 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700319 result.append(buffer);
320 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700321 write(fd, result.string(), result.size());
322 return NO_ERROR;
323}
324
325
326status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
327{
328 const size_t SIZE = 256;
329 char buffer[SIZE];
330 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800331 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700332
John Grossman4ff14ba2012-02-08 16:37:41 -0800333 snprintf(buffer, SIZE, "Hardware status: %d\n"
334 "Standby Time mSec: %u\n",
335 hardwareStatus,
336 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700337 result.append(buffer);
338 write(fd, result.string(), result.size());
339 return NO_ERROR;
340}
341
342status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
343{
344 const size_t SIZE = 256;
345 char buffer[SIZE];
346 String8 result;
347 snprintf(buffer, SIZE, "Permission Denial: "
348 "can't dump AudioFlinger from pid=%d, uid=%d\n",
349 IPCThreadState::self()->getCallingPid(),
350 IPCThreadState::self()->getCallingUid());
351 result.append(buffer);
352 write(fd, result.string(), result.size());
353 return NO_ERROR;
354}
355
356static bool tryLock(Mutex& mutex)
357{
358 bool locked = false;
359 for (int i = 0; i < kDumpLockRetries; ++i) {
360 if (mutex.tryLock() == NO_ERROR) {
361 locked = true;
362 break;
363 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800364 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700365 }
366 return locked;
367}
368
369status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
370{
Glenn Kasten44deb052012-02-05 18:09:08 -0800371 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700372 dumpPermissionDenial(fd, args);
373 } else {
374 // get state of hardware lock
375 bool hardwareLocked = tryLock(mHardwareLock);
376 if (!hardwareLocked) {
377 String8 result(kHardwareLockedString);
378 write(fd, result.string(), result.size());
379 } else {
380 mHardwareLock.unlock();
381 }
382
383 bool locked = tryLock(mLock);
384
385 // failed to lock - AudioFlinger is probably deadlocked
386 if (!locked) {
387 String8 result(kDeadlockedString);
388 write(fd, result.string(), result.size());
389 }
390
391 dumpClients(fd, args);
392 dumpInternals(fd, args);
393
394 // dump playback threads
395 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
396 mPlaybackThreads.valueAt(i)->dump(fd, args);
397 }
398
399 // dump record threads
400 for (size_t i = 0; i < mRecordThreads.size(); i++) {
401 mRecordThreads.valueAt(i)->dump(fd, args);
402 }
403
Dima Zavin799a70e2011-04-18 16:57:27 -0700404 // dump all hardware devs
405 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700406 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700407 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700408 }
409 if (locked) mLock.unlock();
410 }
411 return NO_ERROR;
412}
413
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800414sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
415{
416 // If pid is already in the mClients wp<> map, then use that entry
417 // (for which promote() is always != 0), otherwise create a new entry and Client.
418 sp<Client> client = mClients.valueFor(pid).promote();
419 if (client == 0) {
420 client = new Client(this, pid);
421 mClients.add(pid, client);
422 }
423
424 return client;
425}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700426
427// IAudioFlinger interface
428
429
430sp<IAudioTrack> AudioFlinger::createTrack(
431 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800432 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700433 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800434 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700435 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700436 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800437 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700438 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800439 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800440 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700441 int *sessionId,
442 status_t *status)
443{
444 sp<PlaybackThread::Track> track;
445 sp<TrackHandle> trackHandle;
446 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700447 status_t lStatus;
448 int lSessionId;
449
Glenn Kasten263709e2012-01-06 08:40:01 -0800450 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
451 // but if someone uses binder directly they could bypass that and cause us to crash
452 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000453 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700454 lStatus = BAD_VALUE;
455 goto Exit;
456 }
457
458 {
459 Mutex::Autolock _l(mLock);
460 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700461 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700462 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000463 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700464 lStatus = BAD_VALUE;
465 goto Exit;
466 }
467
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800468 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700469
Steve Block3856b092011-10-20 11:56:00 +0100470 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700471 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700472 // check if an effect chain with the same session ID is present on another
473 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700474 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700475 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
476 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700477 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700478 if (sessions & PlaybackThread::EFFECT_SESSION) {
479 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700480 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700481 }
Eric Laurentde070132010-07-13 04:45:46 -0700482 }
483 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700484 lSessionId = *sessionId;
485 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700486 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700487 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700488 if (sessionId != NULL) {
489 *sessionId = lSessionId;
490 }
491 }
Steve Block3856b092011-10-20 11:56:00 +0100492 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700493
494 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800495 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700496
497 // move effect chain to this output thread if an effect on same session was waiting
498 // for a track to be created
499 if (lStatus == NO_ERROR && effectThread != NULL) {
500 Mutex::Autolock _dl(thread->mLock);
501 Mutex::Autolock _sl(effectThread->mLock);
502 moveEffectChain_l(lSessionId, effectThread, thread, true);
503 }
Eric Laurenta011e352012-03-29 15:51:43 -0700504
505 // Look for sync events awaiting for a session to be used.
506 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
507 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
508 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700509 if (lStatus == NO_ERROR) {
510 track->setSyncEvent(mPendingSyncEvents[i]);
511 } else {
512 mPendingSyncEvents[i]->cancel();
513 }
Eric Laurenta011e352012-03-29 15:51:43 -0700514 mPendingSyncEvents.removeAt(i);
515 i--;
516 }
517 }
518 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700519 }
520 if (lStatus == NO_ERROR) {
521 trackHandle = new TrackHandle(track);
522 } else {
523 // remove local strong reference to Client before deleting the Track so that the Client
524 // destructor is called by the TrackBase destructor with mLock held
525 client.clear();
526 track.clear();
527 }
528
529Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700530 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700531 *status = lStatus;
532 }
533 return trackHandle;
534}
535
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800536uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700537{
538 Mutex::Autolock _l(mLock);
539 PlaybackThread *thread = checkPlaybackThread_l(output);
540 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000541 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700542 return 0;
543 }
544 return thread->sampleRate();
545}
546
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800547int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700548{
549 Mutex::Autolock _l(mLock);
550 PlaybackThread *thread = checkPlaybackThread_l(output);
551 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000552 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700553 return 0;
554 }
555 return thread->channelCount();
556}
557
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800558audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700559{
560 Mutex::Autolock _l(mLock);
561 PlaybackThread *thread = checkPlaybackThread_l(output);
562 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000563 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800564 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700565 }
566 return thread->format();
567}
568
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800569size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700570{
571 Mutex::Autolock _l(mLock);
572 PlaybackThread *thread = checkPlaybackThread_l(output);
573 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000574 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700575 return 0;
576 }
Glenn Kasten58912562012-04-03 10:45:00 -0700577 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
578 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700579 return thread->frameCount();
580}
581
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800582uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700583{
584 Mutex::Autolock _l(mLock);
585 PlaybackThread *thread = checkPlaybackThread_l(output);
586 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000587 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700588 return 0;
589 }
590 return thread->latency();
591}
592
593status_t AudioFlinger::setMasterVolume(float value)
594{
Eric Laurenta1884f92011-08-23 08:25:03 -0700595 status_t ret = initCheck();
596 if (ret != NO_ERROR) {
597 return ret;
598 }
599
Mathias Agopian65ab4712010-07-14 17:59:35 -0700600 // check calling permissions
601 if (!settingsAllowed()) {
602 return PERMISSION_DENIED;
603 }
604
John Grossman4ff14ba2012-02-08 16:37:41 -0800605 float swmv = value;
606
Eric Laurenta4c5a552012-03-29 10:12:40 -0700607 Mutex::Autolock _l(mLock);
608
Mathias Agopian65ab4712010-07-14 17:59:35 -0700609 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800610 if (MVS_NONE != mMasterVolumeSupportLvl) {
611 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
612 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700613 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
John Grossman4ff14ba2012-02-08 16:37:41 -0800614
615 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
616 if (NULL != dev->set_master_volume) {
617 dev->set_master_volume(dev, value);
618 }
619 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800620 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800621
622 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700623 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700624
John Grossman4ff14ba2012-02-08 16:37:41 -0800625 mMasterVolume = value;
626 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800627 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700628 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700629
630 return NO_ERROR;
631}
632
Glenn Kastenf78aee72012-01-04 11:00:47 -0800633status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700634{
Eric Laurenta1884f92011-08-23 08:25:03 -0700635 status_t ret = initCheck();
636 if (ret != NO_ERROR) {
637 return ret;
638 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700639
640 // check calling permissions
641 if (!settingsAllowed()) {
642 return PERMISSION_DENIED;
643 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800644 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000645 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700646 return BAD_VALUE;
647 }
648
649 { // scope for the lock
650 AutoMutex lock(mHardwareLock);
651 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700652 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700653 mHardwareStatus = AUDIO_HW_IDLE;
654 }
655
656 if (NO_ERROR == ret) {
657 Mutex::Autolock _l(mLock);
658 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800659 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700660 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700661 }
662
663 return ret;
664}
665
666status_t AudioFlinger::setMicMute(bool state)
667{
Eric Laurenta1884f92011-08-23 08:25:03 -0700668 status_t ret = initCheck();
669 if (ret != NO_ERROR) {
670 return ret;
671 }
672
Mathias Agopian65ab4712010-07-14 17:59:35 -0700673 // check calling permissions
674 if (!settingsAllowed()) {
675 return PERMISSION_DENIED;
676 }
677
678 AutoMutex lock(mHardwareLock);
679 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700680 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700681 mHardwareStatus = AUDIO_HW_IDLE;
682 return ret;
683}
684
685bool AudioFlinger::getMicMute() const
686{
Eric Laurenta1884f92011-08-23 08:25:03 -0700687 status_t ret = initCheck();
688 if (ret != NO_ERROR) {
689 return false;
690 }
691
Dima Zavinfce7a472011-04-19 22:30:36 -0700692 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800693 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700694 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700695 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700696 mHardwareStatus = AUDIO_HW_IDLE;
697 return state;
698}
699
700status_t AudioFlinger::setMasterMute(bool muted)
701{
702 // check calling permissions
703 if (!settingsAllowed()) {
704 return PERMISSION_DENIED;
705 }
706
Eric Laurent93575202011-01-18 18:39:02 -0800707 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800708 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700709 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800710 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700711 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700712
713 return NO_ERROR;
714}
715
716float AudioFlinger::masterVolume() const
717{
Glenn Kasten98067102011-12-13 11:47:54 -0800718 Mutex::Autolock _l(mLock);
719 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700720}
721
John Grossman4ff14ba2012-02-08 16:37:41 -0800722float AudioFlinger::masterVolumeSW() const
723{
724 Mutex::Autolock _l(mLock);
725 return masterVolumeSW_l();
726}
727
Mathias Agopian65ab4712010-07-14 17:59:35 -0700728bool AudioFlinger::masterMute() const
729{
Glenn Kasten98067102011-12-13 11:47:54 -0800730 Mutex::Autolock _l(mLock);
731 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700732}
733
John Grossman4ff14ba2012-02-08 16:37:41 -0800734float AudioFlinger::masterVolume_l() const
735{
736 if (MVS_FULL == mMasterVolumeSupportLvl) {
737 float ret_val;
738 AutoMutex lock(mHardwareLock);
739
740 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800741 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
742 (NULL != mPrimaryHardwareDev->get_master_volume),
743 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800744
745 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
746 mHardwareStatus = AUDIO_HW_IDLE;
747 return ret_val;
748 }
749
750 return mMasterVolume;
751}
752
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800753status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
754 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700755{
756 // check calling permissions
757 if (!settingsAllowed()) {
758 return PERMISSION_DENIED;
759 }
760
Glenn Kasten263709e2012-01-06 08:40:01 -0800761 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000762 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700763 return BAD_VALUE;
764 }
765
766 AutoMutex lock(mLock);
767 PlaybackThread *thread = NULL;
768 if (output) {
769 thread = checkPlaybackThread_l(output);
770 if (thread == NULL) {
771 return BAD_VALUE;
772 }
773 }
774
775 mStreamTypes[stream].volume = value;
776
777 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800778 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700779 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700780 }
781 } else {
782 thread->setStreamVolume(stream, value);
783 }
784
785 return NO_ERROR;
786}
787
Glenn Kastenfff6d712012-01-12 16:38:12 -0800788status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700789{
790 // check calling permissions
791 if (!settingsAllowed()) {
792 return PERMISSION_DENIED;
793 }
794
Glenn Kasten263709e2012-01-06 08:40:01 -0800795 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700796 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000797 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700798 return BAD_VALUE;
799 }
800
Eric Laurent93575202011-01-18 18:39:02 -0800801 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700802 mStreamTypes[stream].mute = muted;
803 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700804 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805
806 return NO_ERROR;
807}
808
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800809float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700810{
Glenn Kasten263709e2012-01-06 08:40:01 -0800811 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700812 return 0.0f;
813 }
814
815 AutoMutex lock(mLock);
816 float volume;
817 if (output) {
818 PlaybackThread *thread = checkPlaybackThread_l(output);
819 if (thread == NULL) {
820 return 0.0f;
821 }
822 volume = thread->streamVolume(stream);
823 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800824 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700825 }
826
827 return volume;
828}
829
Glenn Kastenfff6d712012-01-12 16:38:12 -0800830bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700831{
Glenn Kasten263709e2012-01-06 08:40:01 -0800832 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833 return true;
834 }
835
Glenn Kasten6637baa2012-01-09 09:40:36 -0800836 AutoMutex lock(mLock);
837 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700838}
839
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800840status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700841{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800842 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700843 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
844 // check calling permissions
845 if (!settingsAllowed()) {
846 return PERMISSION_DENIED;
847 }
848
Mathias Agopian65ab4712010-07-14 17:59:35 -0700849 // ioHandle == 0 means the parameters are global to the audio hardware interface
850 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700851 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700852 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800853 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700854 AutoMutex lock(mHardwareLock);
855 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
856 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
857 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
858 status_t result = dev->set_parameters(dev, keyValuePairs.string());
859 final_result = result ?: final_result;
860 }
861 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800862 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700863 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
864 AudioParameter param = AudioParameter(keyValuePairs);
865 String8 value;
866 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700867 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
868 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700869 for (size_t i = 0; i < mRecordThreads.size(); i++) {
870 sp<RecordThread> thread = mRecordThreads.valueAt(i);
871 RecordThread::RecordTrack *track = thread->track();
872 if (track != NULL) {
873 audio_devices_t device = (audio_devices_t)(
874 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700875 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700876 thread->setEffectSuspended(FX_IID_AEC,
877 suspend,
878 track->sessionId());
879 thread->setEffectSuspended(FX_IID_NS,
880 suspend,
881 track->sessionId());
882 }
883 }
Eric Laurentbee53372011-08-29 12:42:48 -0700884 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700885 }
886 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700887 String8 screenState;
888 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
889 bool isOff = screenState == "off";
890 if (isOff != (gScreenState & 1)) {
891 gScreenState = ((gScreenState & ~1) + 2) | isOff;
892 }
893 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700894 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700895 }
896
897 // hold a strong ref on thread in case closeOutput() or closeInput() is called
898 // and the thread is exited once the lock is released
899 sp<ThreadBase> thread;
900 {
901 Mutex::Autolock _l(mLock);
902 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -0700903 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700904 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800905 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700906 // indicate output device change to all input threads for pre processing
907 AudioParameter param = AudioParameter(keyValuePairs);
908 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700909 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
910 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700911 for (size_t i = 0; i < mRecordThreads.size(); i++) {
912 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
913 }
914 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700915 }
916 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800917 if (thread != 0) {
918 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700919 }
920 return BAD_VALUE;
921}
922
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800923String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700924{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800925// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700926// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
927
Eric Laurenta4c5a552012-03-29 10:12:40 -0700928 Mutex::Autolock _l(mLock);
929
Mathias Agopian65ab4712010-07-14 17:59:35 -0700930 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700931 String8 out_s8;
932
Dima Zavin799a70e2011-04-18 16:57:27 -0700933 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800934 char *s;
935 {
936 AutoMutex lock(mHardwareLock);
937 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700938 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800939 s = dev->get_parameters(dev, keys.string());
940 mHardwareStatus = AUDIO_HW_IDLE;
941 }
John Grossmanef7740b2012-02-09 11:28:36 -0800942 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700943 free(s);
944 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700945 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700946 }
947
Mathias Agopian65ab4712010-07-14 17:59:35 -0700948 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
949 if (playbackThread != NULL) {
950 return playbackThread->getParameters(keys);
951 }
952 RecordThread *recordThread = checkRecordThread_l(ioHandle);
953 if (recordThread != NULL) {
954 return recordThread->getParameters(keys);
955 }
956 return String8("");
957}
958
Glenn Kastendd8104c2012-07-02 12:42:44 -0700959size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
960 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700961{
Eric Laurenta1884f92011-08-23 08:25:03 -0700962 status_t ret = initCheck();
963 if (ret != NO_ERROR) {
964 return 0;
965 }
966
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800967 AutoMutex lock(mHardwareLock);
968 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700969 struct audio_config config = {
970 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -0700971 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700972 format: format,
973 };
974 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800975 mHardwareStatus = AUDIO_HW_IDLE;
976 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700977}
978
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800979unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700980{
981 if (ioHandle == 0) {
982 return 0;
983 }
984
985 Mutex::Autolock _l(mLock);
986
987 RecordThread *recordThread = checkRecordThread_l(ioHandle);
988 if (recordThread != NULL) {
989 return recordThread->getInputFramesLost();
990 }
991 return 0;
992}
993
994status_t AudioFlinger::setVoiceVolume(float value)
995{
Eric Laurenta1884f92011-08-23 08:25:03 -0700996 status_t ret = initCheck();
997 if (ret != NO_ERROR) {
998 return ret;
999 }
1000
Mathias Agopian65ab4712010-07-14 17:59:35 -07001001 // check calling permissions
1002 if (!settingsAllowed()) {
1003 return PERMISSION_DENIED;
1004 }
1005
1006 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001007 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -07001008 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001009 mHardwareStatus = AUDIO_HW_IDLE;
1010
1011 return ret;
1012}
1013
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001014status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1015 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001016{
1017 status_t status;
1018
1019 Mutex::Autolock _l(mLock);
1020
1021 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1022 if (playbackThread != NULL) {
1023 return playbackThread->getRenderPosition(halFrames, dspFrames);
1024 }
1025
1026 return BAD_VALUE;
1027}
1028
1029void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1030{
1031
1032 Mutex::Autolock _l(mLock);
1033
Glenn Kastenbb001922012-02-03 11:10:26 -08001034 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001035 if (mNotificationClients.indexOfKey(pid) < 0) {
1036 sp<NotificationClient> notificationClient = new NotificationClient(this,
1037 client,
1038 pid);
Steve Block3856b092011-10-20 11:56:00 +01001039 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001040
1041 mNotificationClients.add(pid, notificationClient);
1042
1043 sp<IBinder> binder = client->asBinder();
1044 binder->linkToDeath(notificationClient);
1045
1046 // the config change is always sent from playback or record threads to avoid deadlock
1047 // with AudioSystem::gLock
1048 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1049 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1050 }
1051
1052 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1053 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1054 }
1055 }
1056}
1057
1058void AudioFlinger::removeNotificationClient(pid_t pid)
1059{
1060 Mutex::Autolock _l(mLock);
1061
Glenn Kastena3b09252012-01-20 09:19:01 -08001062 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001063
Steve Block3856b092011-10-20 11:56:00 +01001064 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001065 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001066 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001067 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001068 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001069 ALOGV(" pid %d @ %d", ref->mPid, i);
1070 if (ref->mPid == pid) {
1071 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001072 mAudioSessionRefs.removeAt(i);
1073 delete ref;
1074 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001075 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001076 } else {
1077 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001078 }
1079 }
1080 if (removed) {
1081 purgeStaleEffects_l();
1082 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001083}
1084
1085// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001086void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001087{
1088 size_t size = mNotificationClients.size();
1089 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001090 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1091 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001092 }
1093}
1094
1095// removeClient_l() must be called with AudioFlinger::mLock held
1096void AudioFlinger::removeClient_l(pid_t pid)
1097{
Steve Block3856b092011-10-20 11:56:00 +01001098 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001099 mClients.removeItem(pid);
1100}
1101
Eric Laurent717e1282012-06-29 16:36:52 -07001102// getEffectThread_l() must be called with AudioFlinger::mLock held
1103sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1104{
1105 sp<PlaybackThread> thread;
1106
1107 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1108 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1109 ALOG_ASSERT(thread == 0);
1110 thread = mPlaybackThreads.valueAt(i);
1111 }
1112 }
1113
1114 return thread;
1115}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001116
1117// ----------------------------------------------------------------------------
1118
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001119AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1120 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001121 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001122 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001123 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001124 // mChannelMask
1125 mChannelCount(0),
1126 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1127 mParamStatus(NO_ERROR),
Glenn Kasten94479fd2012-07-09 15:39:54 -07001128 mStandby(false), mDevice((audio_devices_t) device), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001129 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001130{
1131}
1132
1133AudioFlinger::ThreadBase::~ThreadBase()
1134{
1135 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001136 // do not lock the mutex in destructor
1137 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001138 if (mPowerManager != 0) {
1139 sp<IBinder> binder = mPowerManager->asBinder();
1140 binder->unlinkToDeath(mDeathRecipient);
1141 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001142}
1143
1144void AudioFlinger::ThreadBase::exit()
1145{
Steve Block3856b092011-10-20 11:56:00 +01001146 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001147 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001148 // This lock prevents the following race in thread (uniprocessor for illustration):
1149 // if (!exitPending()) {
1150 // // context switch from here to exit()
1151 // // exit() calls requestExit(), what exitPending() observes
1152 // // exit() calls signal(), which is dropped since no waiters
1153 // // context switch back from exit() to here
1154 // mWaitWorkCV.wait(...);
1155 // // now thread is hung
1156 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001157 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001158 requestExit();
1159 mWaitWorkCV.signal();
1160 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001161 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1162 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001163 requestExitAndWait();
1164}
1165
Mathias Agopian65ab4712010-07-14 17:59:35 -07001166status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1167{
1168 status_t status;
1169
Steve Block3856b092011-10-20 11:56:00 +01001170 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001171 Mutex::Autolock _l(mLock);
1172
1173 mNewParameters.add(keyValuePairs);
1174 mWaitWorkCV.signal();
1175 // wait condition with timeout in case the thread loop has exited
1176 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001177 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001178 status = mParamStatus;
1179 mWaitWorkCV.signal();
1180 } else {
1181 status = TIMED_OUT;
1182 }
1183 return status;
1184}
1185
1186void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1187{
1188 Mutex::Autolock _l(mLock);
1189 sendConfigEvent_l(event, param);
1190}
1191
1192// sendConfigEvent_l() must be called with ThreadBase::mLock held
1193void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1194{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001195 ConfigEvent configEvent;
1196 configEvent.mEvent = event;
1197 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001198 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001199 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001200 mWaitWorkCV.signal();
1201}
1202
1203void AudioFlinger::ThreadBase::processConfigEvents()
1204{
1205 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001206 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001207 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001208 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001209 mConfigEvents.removeAt(0);
1210 // release mLock before locking AudioFlinger mLock: lock order is always
1211 // AudioFlinger then ThreadBase to avoid cross deadlock
1212 mLock.unlock();
1213 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001214 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001215 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001216 mLock.lock();
1217 }
1218 mLock.unlock();
1219}
1220
1221status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1222{
1223 const size_t SIZE = 256;
1224 char buffer[SIZE];
1225 String8 result;
1226
1227 bool locked = tryLock(mLock);
1228 if (!locked) {
1229 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1230 write(fd, buffer, strlen(buffer));
1231 }
1232
Eric Laurent612bbb52012-03-14 15:03:26 -07001233 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1234 result.append(buffer);
1235 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1236 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001237 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1238 result.append(buffer);
1239 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1240 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001241 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1242 result.append(buffer);
1243 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001244 result.append(buffer);
1245 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1246 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001247 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1248 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001249 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1250 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001251 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001252 result.append(buffer);
1253
1254 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1255 result.append(buffer);
1256 result.append(" Index Command");
1257 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1258 snprintf(buffer, SIZE, "\n %02d ", i);
1259 result.append(buffer);
1260 result.append(mNewParameters[i]);
1261 }
1262
1263 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1264 result.append(buffer);
1265 snprintf(buffer, SIZE, " Index event param\n");
1266 result.append(buffer);
1267 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001268 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001269 result.append(buffer);
1270 }
1271 result.append("\n");
1272
1273 write(fd, result.string(), result.size());
1274
1275 if (locked) {
1276 mLock.unlock();
1277 }
1278 return NO_ERROR;
1279}
1280
Eric Laurent1d2bff02011-07-24 17:49:51 -07001281status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1282{
1283 const size_t SIZE = 256;
1284 char buffer[SIZE];
1285 String8 result;
1286
1287 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1288 write(fd, buffer, strlen(buffer));
1289
1290 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1291 sp<EffectChain> chain = mEffectChains[i];
1292 if (chain != 0) {
1293 chain->dump(fd, args);
1294 }
1295 }
1296 return NO_ERROR;
1297}
1298
Eric Laurentfeb0db62011-07-22 09:04:31 -07001299void AudioFlinger::ThreadBase::acquireWakeLock()
1300{
1301 Mutex::Autolock _l(mLock);
1302 acquireWakeLock_l();
1303}
1304
1305void AudioFlinger::ThreadBase::acquireWakeLock_l()
1306{
1307 if (mPowerManager == 0) {
1308 // use checkService() to avoid blocking if power service is not up yet
1309 sp<IBinder> binder =
1310 defaultServiceManager()->checkService(String16("power"));
1311 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001312 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001313 } else {
1314 mPowerManager = interface_cast<IPowerManager>(binder);
1315 binder->linkToDeath(mDeathRecipient);
1316 }
1317 }
1318 if (mPowerManager != 0) {
1319 sp<IBinder> binder = new BBinder();
1320 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1321 binder,
1322 String16(mName));
1323 if (status == NO_ERROR) {
1324 mWakeLockToken = binder;
1325 }
Steve Block3856b092011-10-20 11:56:00 +01001326 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001327 }
1328}
1329
1330void AudioFlinger::ThreadBase::releaseWakeLock()
1331{
1332 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001333 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001334}
1335
1336void AudioFlinger::ThreadBase::releaseWakeLock_l()
1337{
1338 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001339 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001340 if (mPowerManager != 0) {
1341 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1342 }
1343 mWakeLockToken.clear();
1344 }
1345}
1346
1347void AudioFlinger::ThreadBase::clearPowerManager()
1348{
1349 Mutex::Autolock _l(mLock);
1350 releaseWakeLock_l();
1351 mPowerManager.clear();
1352}
1353
1354void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1355{
1356 sp<ThreadBase> thread = mThread.promote();
1357 if (thread != 0) {
1358 thread->clearPowerManager();
1359 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001360 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001361}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001362
Eric Laurent59255e42011-07-27 19:49:51 -07001363void AudioFlinger::ThreadBase::setEffectSuspended(
1364 const effect_uuid_t *type, bool suspend, int sessionId)
1365{
1366 Mutex::Autolock _l(mLock);
1367 setEffectSuspended_l(type, suspend, sessionId);
1368}
1369
1370void AudioFlinger::ThreadBase::setEffectSuspended_l(
1371 const effect_uuid_t *type, bool suspend, int sessionId)
1372{
Glenn Kasten090f0192012-01-30 13:00:02 -08001373 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001374 if (chain != 0) {
1375 if (type != NULL) {
1376 chain->setEffectSuspended_l(type, suspend);
1377 } else {
1378 chain->setEffectSuspendedAll_l(suspend);
1379 }
1380 }
1381
1382 updateSuspendedSessions_l(type, suspend, sessionId);
1383}
1384
1385void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1386{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001387 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001388 if (index < 0) {
1389 return;
1390 }
1391
1392 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1393 mSuspendedSessions.editValueAt(index);
1394
1395 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001396 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001397 for (int j = 0; j < desc->mRefCount; j++) {
1398 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1399 chain->setEffectSuspendedAll_l(true);
1400 } else {
Steve Block3856b092011-10-20 11:56:00 +01001401 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001402 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001403 chain->setEffectSuspended_l(&desc->mType, true);
1404 }
1405 }
1406 }
1407}
1408
Eric Laurent59255e42011-07-27 19:49:51 -07001409void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1410 bool suspend,
1411 int sessionId)
1412{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001413 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001414
1415 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1416
1417 if (suspend) {
1418 if (index >= 0) {
1419 sessionEffects = mSuspendedSessions.editValueAt(index);
1420 } else {
1421 mSuspendedSessions.add(sessionId, sessionEffects);
1422 }
1423 } else {
1424 if (index < 0) {
1425 return;
1426 }
1427 sessionEffects = mSuspendedSessions.editValueAt(index);
1428 }
1429
1430
1431 int key = EffectChain::kKeyForSuspendAll;
1432 if (type != NULL) {
1433 key = type->timeLow;
1434 }
1435 index = sessionEffects.indexOfKey(key);
1436
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001437 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001438 if (suspend) {
1439 if (index >= 0) {
1440 desc = sessionEffects.valueAt(index);
1441 } else {
1442 desc = new SuspendedSessionDesc();
1443 if (type != NULL) {
1444 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1445 }
1446 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001447 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001448 }
1449 desc->mRefCount++;
1450 } else {
1451 if (index < 0) {
1452 return;
1453 }
1454 desc = sessionEffects.valueAt(index);
1455 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001456 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001457 sessionEffects.removeItemsAt(index);
1458 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001459 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001460 sessionId);
1461 mSuspendedSessions.removeItem(sessionId);
1462 }
1463 }
1464 }
1465 if (!sessionEffects.isEmpty()) {
1466 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1467 }
1468}
1469
1470void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1471 bool enabled,
1472 int sessionId)
1473{
1474 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001475 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1476}
Eric Laurent59255e42011-07-27 19:49:51 -07001477
Eric Laurenta85a74a2011-10-19 11:44:54 -07001478void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1479 bool enabled,
1480 int sessionId)
1481{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001482 if (mType != RECORD) {
1483 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1484 // another session. This gives the priority to well behaved effect control panels
1485 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001486 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1487 // global effects
1488 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001489 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1490 }
1491 }
Eric Laurent59255e42011-07-27 19:49:51 -07001492
1493 sp<EffectChain> chain = getEffectChain_l(sessionId);
1494 if (chain != 0) {
1495 chain->checkSuspendOnEffectEnabled(effect, enabled);
1496 }
1497}
1498
Mathias Agopian65ab4712010-07-14 17:59:35 -07001499// ----------------------------------------------------------------------------
1500
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001501AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1502 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001503 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001504 uint32_t device,
1505 type_t type)
1506 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001507 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1508 // Assumes constructor is called by AudioFlinger with it's mLock held,
1509 // but it would be safer to explicitly pass initial masterMute as parameter
1510 mMasterMute(audioFlinger->masterMute_l()),
1511 // mStreamTypes[] initialized in constructor body
1512 mOutput(output),
1513 // Assumes constructor is called by AudioFlinger with it's mLock held,
1514 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001515 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001516 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001517 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001518 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001519 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001520 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001521 // index 0 is reserved for normal mixer's submix
1522 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001523{
Glenn Kasten480b4682012-02-28 12:30:08 -08001524 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001525
Mathias Agopian65ab4712010-07-14 17:59:35 -07001526 readOutputParameters();
1527
Glenn Kasten263709e2012-01-06 08:40:01 -08001528 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001529 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1530 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1531 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001532 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1533 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001534 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001535 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1536 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001537}
1538
1539AudioFlinger::PlaybackThread::~PlaybackThread()
1540{
1541 delete [] mMixBuffer;
1542}
1543
1544status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1545{
1546 dumpInternals(fd, args);
1547 dumpTracks(fd, args);
1548 dumpEffectChains(fd, args);
1549 return NO_ERROR;
1550}
1551
1552status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1553{
1554 const size_t SIZE = 256;
1555 char buffer[SIZE];
1556 String8 result;
1557
Glenn Kasten58912562012-04-03 10:45:00 -07001558 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1559 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1560 const stream_type_t *st = &mStreamTypes[i];
1561 if (i > 0) {
1562 result.appendFormat(", ");
1563 }
1564 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1565 if (st->mute) {
1566 result.append("M");
1567 }
1568 }
1569 result.append("\n");
1570 write(fd, result.string(), result.length());
1571 result.clear();
1572
Mathias Agopian65ab4712010-07-14 17:59:35 -07001573 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1574 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001575 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001576 for (size_t i = 0; i < mTracks.size(); ++i) {
1577 sp<Track> track = mTracks[i];
1578 if (track != 0) {
1579 track->dump(buffer, SIZE);
1580 result.append(buffer);
1581 }
1582 }
1583
1584 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1585 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001586 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001587 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001588 sp<Track> track = mActiveTracks[i].promote();
1589 if (track != 0) {
1590 track->dump(buffer, SIZE);
1591 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001592 }
1593 }
1594 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001595
1596 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1597 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1598 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1599 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1600
Mathias Agopian65ab4712010-07-14 17:59:35 -07001601 return NO_ERROR;
1602}
1603
Mathias Agopian65ab4712010-07-14 17:59:35 -07001604status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1605{
1606 const size_t SIZE = 256;
1607 char buffer[SIZE];
1608 String8 result;
1609
1610 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1611 result.append(buffer);
1612 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1613 result.append(buffer);
1614 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1615 result.append(buffer);
1616 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1617 result.append(buffer);
1618 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1619 result.append(buffer);
1620 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1621 result.append(buffer);
1622 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1623 result.append(buffer);
1624 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001625 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001626
1627 dumpBase(fd, args);
1628
1629 return NO_ERROR;
1630}
1631
1632// Thread virtuals
1633status_t AudioFlinger::PlaybackThread::readyToRun()
1634{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001635 status_t status = initCheck();
1636 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001637 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001638 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001639 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001640 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001641 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001642}
1643
1644void AudioFlinger::PlaybackThread::onFirstRef()
1645{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001646 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001647}
1648
1649// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001650sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001651 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001652 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001653 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001654 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001655 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001656 int frameCount,
1657 const sp<IMemory>& sharedBuffer,
1658 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001659 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001660 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001661 status_t *status)
1662{
1663 sp<Track> track;
1664 status_t lStatus;
1665
Glenn Kasten73d22752012-03-19 13:38:30 -07001666 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1667
1668 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001669 if (flags & IAudioFlinger::TRACK_FAST) {
1670 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001671 // not timed
1672 (!isTimed) &&
1673 // either of these use cases:
1674 (
1675 // use case 1: shared buffer with any frame count
1676 (
1677 (sharedBuffer != 0)
1678 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001679 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001680 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001681 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001682 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001683 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001684 )
1685 ) &&
1686 // PCM data
1687 audio_is_linear_pcm(format) &&
1688 // mono or stereo
1689 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1690 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001691#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001692 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001693 (sampleRate == mSampleRate) &&
1694#endif
1695 // normal mixer has an associated fast mixer
1696 hasFastMixer() &&
1697 // there are sufficient fast track slots available
1698 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001699 // FIXME test that MixerThread for this fast track has a capable output HAL
1700 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001701 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001702 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1703 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001704 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001705 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001706 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001707 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001708 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001709 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten254af182012-07-03 14:59:05 -07001710 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001711 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1712 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1713 audio_is_linear_pcm(format),
1714 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001715 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001716 // For compatibility with AudioTrack calculation, buffer depth is forced
1717 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1718 // This is probably too conservative, but legacy application code may depend on it.
1719 // If you change this calculation, also review the start threshold which is related.
1720 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1721 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1722 if (minBufCount < 2) {
1723 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001724 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001725 int minFrameCount = mNormalFrameCount * minBufCount;
1726 if (frameCount < minFrameCount) {
1727 frameCount = minFrameCount;
1728 }
1729 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001730 }
1731
Mathias Agopian65ab4712010-07-14 17:59:35 -07001732 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001733 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1734 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001735 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001736 "for output %p with format %d",
1737 sampleRate, format, channelMask, mOutput, mFormat);
1738 lStatus = BAD_VALUE;
1739 goto Exit;
1740 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001741 }
1742 } else {
1743 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1744 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001745 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001746 lStatus = BAD_VALUE;
1747 goto Exit;
1748 }
1749 }
1750
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001751 lStatus = initCheck();
1752 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001753 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001754 goto Exit;
1755 }
1756
1757 { // scope for mLock
1758 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001759
1760 // all tracks in same audio session must share the same routing strategy otherwise
1761 // conflicts will happen when tracks are moved from one output to another by audio policy
1762 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001763 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001764 for (size_t i = 0; i < mTracks.size(); ++i) {
1765 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001766 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001767 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001768 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001769 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001770 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001771 lStatus = BAD_VALUE;
1772 goto Exit;
1773 }
1774 }
1775 }
1776
John Grossman4ff14ba2012-02-08 16:37:41 -08001777 if (!isTimed) {
1778 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001779 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001780 } else {
1781 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1782 channelMask, frameCount, sharedBuffer, sessionId);
1783 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001784 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001785 lStatus = NO_MEMORY;
1786 goto Exit;
1787 }
1788 mTracks.add(track);
1789
1790 sp<EffectChain> chain = getEffectChain_l(sessionId);
1791 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001792 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001793 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001794 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001795 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001796 }
1797 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001798
Glenn Kasten3acbd052012-02-28 10:39:56 -08001799 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1800 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1801 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1802 // so ask activity manager to do this on our behalf
1803 int err = requestPriority(callingPid, tid, 1);
1804 if (err != 0) {
1805 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1806 1, callingPid, tid, err);
1807 }
1808 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001809
Mathias Agopian65ab4712010-07-14 17:59:35 -07001810 lStatus = NO_ERROR;
1811
1812Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001813 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001814 *status = lStatus;
1815 }
1816 return track;
1817}
1818
Eric Laurente737cda2012-05-22 18:55:44 -07001819uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1820{
1821 if (mFastMixer != NULL) {
1822 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1823 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1824 }
1825 return latency;
1826}
1827
1828uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1829{
1830 return latency;
1831}
1832
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833uint32_t AudioFlinger::PlaybackThread::latency() const
1834{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001835 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001836 return latency_l();
1837}
1838uint32_t AudioFlinger::PlaybackThread::latency_l() const
1839{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001840 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001841 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001842 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001843 return 0;
1844 }
1845}
1846
Glenn Kasten6637baa2012-01-09 09:40:36 -08001847void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001848{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001849 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001850 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001851}
1852
Glenn Kasten6637baa2012-01-09 09:40:36 -08001853void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001854{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001855 Mutex::Autolock _l(mLock);
1856 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001857}
1858
Glenn Kasten6637baa2012-01-09 09:40:36 -08001859void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001860{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001861 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001862 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001863}
1864
Glenn Kasten6637baa2012-01-09 09:40:36 -08001865void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001866{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001867 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001868 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001869}
1870
Glenn Kastenfff6d712012-01-12 16:38:12 -08001871float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001872{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001873 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001874 return mStreamTypes[stream].volume;
1875}
1876
Mathias Agopian65ab4712010-07-14 17:59:35 -07001877// addTrack_l() must be called with ThreadBase::mLock held
1878status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1879{
1880 status_t status = ALREADY_EXISTS;
1881
1882 // set retry count for buffer fill
1883 track->mRetryCount = kMaxTrackStartupRetries;
1884 if (mActiveTracks.indexOf(track) < 0) {
1885 // the track is newly added, make sure it fills up all its
1886 // buffers before playing. This is to ensure the client will
1887 // effectively get the latency it requested.
1888 track->mFillingUpStatus = Track::FS_FILLING;
1889 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001890 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001891 mActiveTracks.add(track);
1892 if (track->mainBuffer() != mMixBuffer) {
1893 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1894 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001895 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001896 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001897 }
1898 }
1899
1900 status = NO_ERROR;
1901 }
1902
Steve Block3856b092011-10-20 11:56:00 +01001903 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001904 mWaitWorkCV.broadcast();
1905
1906 return status;
1907}
1908
1909// destroyTrack_l() must be called with ThreadBase::mLock held
1910void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1911{
1912 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001913 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001914 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001915 removeTrack_l(track);
1916 }
1917}
1918
1919void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1920{
Eric Laurent29864602012-05-08 18:57:51 -07001921 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001922 mTracks.remove(track);
1923 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001924 // redundant as track is about to be destroyed, for dumpsys only
1925 track->mName = -1;
1926 if (track->isFastTrack()) {
1927 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001928 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001929 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1930 mFastTrackAvailMask |= 1 << index;
1931 // redundant as track is about to be destroyed, for dumpsys only
1932 track->mFastIndex = -1;
1933 }
Eric Laurentb469b942011-05-09 12:09:06 -07001934 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1935 if (chain != 0) {
1936 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001937 }
1938}
1939
1940String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1941{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001942 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001943 char *s;
1944
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001945 Mutex::Autolock _l(mLock);
1946 if (initCheck() != NO_ERROR) {
1947 return out_s8;
1948 }
1949
Dima Zavin799a70e2011-04-18 16:57:27 -07001950 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001951 out_s8 = String8(s);
1952 free(s);
1953 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001954}
1955
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001956// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001957void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1958 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001959 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001960
Steve Block3856b092011-10-20 11:56:00 +01001961 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001962
1963 switch (event) {
1964 case AudioSystem::OUTPUT_OPENED:
1965 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001966 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001967 desc.samplingRate = mSampleRate;
1968 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001969 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001970 desc.latency = latency();
1971 param2 = &desc;
1972 break;
1973
1974 case AudioSystem::STREAM_CONFIG_CHANGED:
1975 param2 = &param;
1976 case AudioSystem::OUTPUT_CLOSED:
1977 default:
1978 break;
1979 }
1980 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1981}
1982
1983void AudioFlinger::PlaybackThread::readOutputParameters()
1984{
Dima Zavin799a70e2011-04-18 16:57:27 -07001985 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001986 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1987 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001988 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001989 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001990 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001991 if (mFrameCount & 15) {
1992 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1993 mFrameCount);
1994 }
1995
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001996 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07001997 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001998 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07001999 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002000 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2001 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2002 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2003 maxNormalFrameCount = maxNormalFrameCount & ~15;
2004 if (maxNormalFrameCount < minNormalFrameCount) {
2005 maxNormalFrameCount = minNormalFrameCount;
2006 }
2007 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2008 if (multiplier <= 1.0) {
2009 multiplier = 1.0;
2010 } else if (multiplier <= 2.0) {
2011 if (2 * mFrameCount <= maxNormalFrameCount) {
2012 multiplier = 2.0;
2013 } else {
2014 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2015 }
2016 } else {
2017 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2018 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2019 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2020 // FIXME this rounding up should not be done if no HAL SRC
2021 uint32_t truncMult = (uint32_t) multiplier;
2022 if ((truncMult & 1)) {
2023 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2024 ++truncMult;
2025 }
2026 }
2027 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002028 }
Glenn Kasten58912562012-04-03 10:45:00 -07002029 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002030 mNormalFrameCount = multiplier * mFrameCount;
2031 // round up to nearest 16 frames to satisfy AudioMixer
2032 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002033 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002034
Glenn Kastene9dd0172012-01-27 18:08:45 -08002035 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002036 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2037 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002038
Eric Laurentde070132010-07-13 04:45:46 -07002039 // force reconfiguration of effect chains and engines to take new buffer size and audio
2040 // parameters into account
2041 // Note that mLock is not held when readOutputParameters() is called from the constructor
2042 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2043 // matter.
2044 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2045 Vector< sp<EffectChain> > effectChains = mEffectChains;
2046 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002047 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002048 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002049}
2050
Eric Laurente737cda2012-05-22 18:55:44 -07002051
Mathias Agopian65ab4712010-07-14 17:59:35 -07002052status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2053{
Glenn Kastena0d68332012-01-27 16:47:15 -08002054 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002055 return BAD_VALUE;
2056 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002057 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002058 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002059 return INVALID_OPERATION;
2060 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002061 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002062
Dima Zavin799a70e2011-04-18 16:57:27 -07002063 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002064}
2065
Eric Laurent39e94f82010-07-28 01:32:47 -07002066uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002067{
2068 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002069 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002070 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002071 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002072 }
2073
2074 for (size_t i = 0; i < mTracks.size(); ++i) {
2075 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002076 if (sessionId == track->sessionId() &&
2077 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002078 result |= TRACK_SESSION;
2079 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002080 }
2081 }
2082
Eric Laurent39e94f82010-07-28 01:32:47 -07002083 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002084}
2085
Eric Laurentde070132010-07-13 04:45:46 -07002086uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2087{
Dima Zavinfce7a472011-04-19 22:30:36 -07002088 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002089 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002090 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2091 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002092 }
2093 for (size_t i = 0; i < mTracks.size(); i++) {
2094 sp<Track> track = mTracks[i];
2095 if (sessionId == track->sessionId() &&
2096 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002097 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002098 }
2099 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002100 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002101}
2102
Mathias Agopian65ab4712010-07-14 17:59:35 -07002103
Glenn Kastenaed850d2012-01-26 09:46:34 -08002104AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002105{
2106 Mutex::Autolock _l(mLock);
2107 return mOutput;
2108}
2109
2110AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2111{
2112 Mutex::Autolock _l(mLock);
2113 AudioStreamOut *output = mOutput;
2114 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002115 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2116 // must push a NULL and wait for ack
2117 mOutputSink.clear();
2118 mPipeSink.clear();
2119 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002120 return output;
2121}
2122
2123// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002124audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002125{
2126 if (mOutput == NULL) {
2127 return NULL;
2128 }
2129 return &mOutput->stream->common;
2130}
2131
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002132uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002133{
Eric Laurentab9071b2012-06-04 13:45:29 -07002134 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002135}
2136
Eric Laurenta011e352012-03-29 15:51:43 -07002137status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2138{
2139 if (!isValidSyncEvent(event)) {
2140 return BAD_VALUE;
2141 }
2142
2143 Mutex::Autolock _l(mLock);
2144
2145 for (size_t i = 0; i < mTracks.size(); ++i) {
2146 sp<Track> track = mTracks[i];
2147 if (event->triggerSession() == track->sessionId()) {
2148 track->setSyncEvent(event);
2149 return NO_ERROR;
2150 }
2151 }
2152
2153 return NAME_NOT_FOUND;
2154}
2155
2156bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2157{
2158 switch (event->type()) {
2159 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2160 return true;
2161 default:
2162 break;
2163 }
2164 return false;
2165}
2166
Eric Laurent44a957f2012-05-15 15:26:05 -07002167void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2168{
2169 size_t count = tracksToRemove.size();
2170 if (CC_UNLIKELY(count)) {
2171 for (size_t i = 0 ; i < count ; i++) {
2172 const sp<Track>& track = tracksToRemove.itemAt(i);
2173 if ((track->sharedBuffer() != 0) &&
2174 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2175 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2176 }
2177 }
2178 }
2179
2180}
2181
Mathias Agopian65ab4712010-07-14 17:59:35 -07002182// ----------------------------------------------------------------------------
2183
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002184AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002185 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002186 : PlaybackThread(audioFlinger, output, id, device, type),
2187 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002188 // mFastMixer below
2189 mFastMixerFutex(0)
2190 // mOutputSink below
2191 // mPipeSink below
2192 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002193{
Glenn Kasten58912562012-04-03 10:45:00 -07002194 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002195 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002196 "mFrameCount=%d, mNormalFrameCount=%d",
2197 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2198 mNormalFrameCount);
2199 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2200
Mathias Agopian65ab4712010-07-14 17:59:35 -07002201 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002202 if (mChannelCount != FCC_2) {
2203 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002204 }
Glenn Kasten58912562012-04-03 10:45:00 -07002205
2206 // create an NBAIO sink for the HAL output stream, and negotiate
2207 mOutputSink = new AudioStreamOutSink(output->stream);
2208 size_t numCounterOffers = 0;
2209 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2210 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2211 ALOG_ASSERT(index == 0);
2212
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002213 // initialize fast mixer depending on configuration
2214 bool initFastMixer;
2215 switch (kUseFastMixer) {
2216 case FastMixer_Never:
2217 initFastMixer = false;
2218 break;
2219 case FastMixer_Always:
2220 initFastMixer = true;
2221 break;
2222 case FastMixer_Static:
2223 case FastMixer_Dynamic:
2224 initFastMixer = mFrameCount < mNormalFrameCount;
2225 break;
2226 }
2227 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002228
2229 // create a MonoPipe to connect our submix to FastMixer
2230 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002231 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2232 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2233 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2234 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002235 const NBAIO_Format offers[1] = {format};
2236 size_t numCounterOffers = 0;
2237 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2238 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002239 monoPipe->setAvgFrames((mScreenState & 1) ?
2240 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002241 mPipeSink = monoPipe;
2242
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002243#ifdef TEE_SINK_FRAMES
2244 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2245 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2246 numCounterOffers = 0;
2247 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2248 ALOG_ASSERT(index == 0);
2249 mTeeSink = teeSink;
2250 PipeReader *teeSource = new PipeReader(*teeSink);
2251 numCounterOffers = 0;
2252 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2253 ALOG_ASSERT(index == 0);
2254 mTeeSource = teeSource;
2255#endif
2256
Glenn Kasten58912562012-04-03 10:45:00 -07002257 // create fast mixer and configure it initially with just one fast track for our submix
2258 mFastMixer = new FastMixer();
2259 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002260#ifdef STATE_QUEUE_DUMP
2261 sq->setObserverDump(&mStateQueueObserverDump);
2262 sq->setMutatorDump(&mStateQueueMutatorDump);
2263#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002264 FastMixerState *state = sq->begin();
2265 FastTrack *fastTrack = &state->mFastTracks[0];
2266 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2267 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2268 fastTrack->mVolumeProvider = NULL;
2269 fastTrack->mGeneration++;
2270 state->mFastTracksGen++;
2271 state->mTrackMask = 1;
2272 // fast mixer will use the HAL output sink
2273 state->mOutputSink = mOutputSink.get();
2274 state->mOutputSinkGen++;
2275 state->mFrameCount = mFrameCount;
2276 state->mCommand = FastMixerState::COLD_IDLE;
2277 // already done in constructor initialization list
2278 //mFastMixerFutex = 0;
2279 state->mColdFutexAddr = &mFastMixerFutex;
2280 state->mColdGen++;
2281 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002282 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002283 sq->end();
2284 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2285
2286 // start the fast mixer
2287 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002288 pid_t tid = mFastMixer->getTid();
2289 int err = requestPriority(getpid_cached, tid, 2);
2290 if (err != 0) {
2291 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2292 2, getpid_cached, tid, err);
2293 }
Glenn Kasten58912562012-04-03 10:45:00 -07002294
Glenn Kastenc15d6652012-05-30 14:52:57 -07002295#ifdef AUDIO_WATCHDOG
2296 // create and start the watchdog
2297 mAudioWatchdog = new AudioWatchdog();
2298 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2299 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2300 tid = mAudioWatchdog->getTid();
2301 err = requestPriority(getpid_cached, tid, 1);
2302 if (err != 0) {
2303 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2304 1, getpid_cached, tid, err);
2305 }
2306#endif
2307
Glenn Kasten58912562012-04-03 10:45:00 -07002308 } else {
2309 mFastMixer = NULL;
2310 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002311
2312 switch (kUseFastMixer) {
2313 case FastMixer_Never:
2314 case FastMixer_Dynamic:
2315 mNormalSink = mOutputSink;
2316 break;
2317 case FastMixer_Always:
2318 mNormalSink = mPipeSink;
2319 break;
2320 case FastMixer_Static:
2321 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2322 break;
2323 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002324}
2325
2326AudioFlinger::MixerThread::~MixerThread()
2327{
Glenn Kasten58912562012-04-03 10:45:00 -07002328 if (mFastMixer != NULL) {
2329 FastMixerStateQueue *sq = mFastMixer->sq();
2330 FastMixerState *state = sq->begin();
2331 if (state->mCommand == FastMixerState::COLD_IDLE) {
2332 int32_t old = android_atomic_inc(&mFastMixerFutex);
2333 if (old == -1) {
2334 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2335 }
2336 }
2337 state->mCommand = FastMixerState::EXIT;
2338 sq->end();
2339 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2340 mFastMixer->join();
2341 // Though the fast mixer thread has exited, it's state queue is still valid.
2342 // We'll use that extract the final state which contains one remaining fast track
2343 // corresponding to our sub-mix.
2344 state = sq->begin();
2345 ALOG_ASSERT(state->mTrackMask == 1);
2346 FastTrack *fastTrack = &state->mFastTracks[0];
2347 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2348 delete fastTrack->mBufferProvider;
2349 sq->end(false /*didModify*/);
2350 delete mFastMixer;
Glenn Kastenc15d6652012-05-30 14:52:57 -07002351 if (mAudioWatchdog != 0) {
2352 mAudioWatchdog->requestExit();
2353 mAudioWatchdog->requestExitAndWait();
2354 mAudioWatchdog.clear();
2355 }
Glenn Kasten58912562012-04-03 10:45:00 -07002356 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002357 delete mAudioMixer;
2358}
2359
Glenn Kasten83efdd02012-02-24 07:21:32 -08002360class CpuStats {
2361public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002362 CpuStats();
2363 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002364#ifdef DEBUG_CPU_USAGE
2365private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002366 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2367 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2368
2369 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2370
2371 int mCpuNum; // thread's current CPU number
2372 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002373#endif
2374};
2375
Glenn Kasten190a46f2012-03-06 11:27:10 -08002376CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002377#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002378 : mCpuNum(-1), mCpukHz(-1)
2379#endif
2380{
2381}
2382
2383void CpuStats::sample(const String8 &title) {
2384#ifdef DEBUG_CPU_USAGE
2385 // get current thread's delta CPU time in wall clock ns
2386 double wcNs;
2387 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2388
2389 // record sample for wall clock statistics
2390 if (valid) {
2391 mWcStats.sample(wcNs);
2392 }
2393
2394 // get the current CPU number
2395 int cpuNum = sched_getcpu();
2396
2397 // get the current CPU frequency in kHz
2398 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2399
2400 // check if either CPU number or frequency changed
2401 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2402 mCpuNum = cpuNum;
2403 mCpukHz = cpukHz;
2404 // ignore sample for purposes of cycles
2405 valid = false;
2406 }
2407
2408 // if no change in CPU number or frequency, then record sample for cycle statistics
2409 if (valid && mCpukHz > 0) {
2410 double cycles = wcNs * cpukHz * 0.000001;
2411 mHzStats.sample(cycles);
2412 }
2413
2414 unsigned n = mWcStats.n();
2415 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002416 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002417 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002418 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2419 double perLoop = elapsed / (double) n;
2420 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002421 double perLoop1k = perLoop * 0.001;
2422 double mean = mWcStats.mean();
2423 double stddev = mWcStats.stddev();
2424 double minimum = mWcStats.minimum();
2425 double maximum = mWcStats.maximum();
2426 double meanCycles = mHzStats.mean();
2427 double stddevCycles = mHzStats.stddev();
2428 double minCycles = mHzStats.minimum();
2429 double maxCycles = mHzStats.maximum();
2430 mCpuUsage.resetElapsed();
2431 mWcStats.reset();
2432 mHzStats.reset();
2433 ALOGD("CPU usage for %s over past %.1f secs\n"
2434 " (%u mixer loops at %.1f mean ms per loop):\n"
2435 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2436 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2437 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2438 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002439 elapsed * .000000001, n, perLoop * .000001,
2440 mean * .001,
2441 stddev * .001,
2442 minimum * .001,
2443 maximum * .001,
2444 mean / perLoop100,
2445 stddev / perLoop100,
2446 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002447 maximum / perLoop100,
2448 meanCycles / perLoop1k,
2449 stddevCycles / perLoop1k,
2450 minCycles / perLoop1k,
2451 maxCycles / perLoop1k);
2452
Glenn Kasten83efdd02012-02-24 07:21:32 -08002453 }
2454 }
2455#endif
2456};
2457
Glenn Kasten37d825e2012-02-24 07:21:48 -08002458void AudioFlinger::PlaybackThread::checkSilentMode_l()
2459{
2460 if (!mMasterMute) {
2461 char value[PROPERTY_VALUE_MAX];
2462 if (property_get("ro.audio.silent", value, "0") > 0) {
2463 char *endptr;
2464 unsigned long ul = strtoul(value, &endptr, 0);
2465 if (*endptr == '\0' && ul != 0) {
2466 ALOGD("Silence is golden");
2467 // The setprop command will not allow a property to be changed after
2468 // the first time it is set, so we don't have to worry about un-muting.
2469 setMasterMute_l(true);
2470 }
2471 }
2472 }
2473}
2474
Glenn Kasten000f0e32012-03-01 17:10:56 -08002475bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002476{
2477 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002478
Glenn Kasten000f0e32012-03-01 17:10:56 -08002479 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002480
2481 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002482 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002483
Glenn Kasten000f0e32012-03-01 17:10:56 -08002484 // DUPLICATING
2485 // FIXME could this be made local to while loop?
2486 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002487
Glenn Kasten66fcab92012-02-24 14:59:21 -08002488 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002489 sleepTime = idleSleepTime;
2490
Glenn Kasten9f34a362012-03-20 16:46:41 -07002491 if (mType == MIXER) {
2492 sleepTimeShift = 0;
2493 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002494
Glenn Kasten83efdd02012-02-24 07:21:32 -08002495 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002496 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002497
Eric Laurentfeb0db62011-07-22 09:04:31 -07002498 acquireWakeLock();
2499
Mathias Agopian65ab4712010-07-14 17:59:35 -07002500 while (!exitPending())
2501 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002502 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002503
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002504 Vector< sp<EffectChain> > effectChains;
2505
Mathias Agopian65ab4712010-07-14 17:59:35 -07002506 processConfigEvents();
2507
Mathias Agopian65ab4712010-07-14 17:59:35 -07002508 { // scope for mLock
2509
2510 Mutex::Autolock _l(mLock);
2511
2512 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002513 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002514 }
2515
Glenn Kastenfa26a852012-03-06 11:28:04 -08002516 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002517
Mathias Agopian65ab4712010-07-14 17:59:35 -07002518 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002519 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002520 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002521 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002522
2523 threadLoop_standby();
2524
Mathias Agopian65ab4712010-07-14 17:59:35 -07002525 mStandby = true;
2526 mBytesWritten = 0;
2527 }
2528
Glenn Kasten3e074702012-02-28 18:40:35 -08002529 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002530 // we're about to wait, flush the binder command buffer
2531 IPCThreadState::self()->flushCommands();
2532
Glenn Kastenfa26a852012-03-06 11:28:04 -08002533 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002534
Mathias Agopian65ab4712010-07-14 17:59:35 -07002535 if (exitPending()) break;
2536
Eric Laurentfeb0db62011-07-22 09:04:31 -07002537 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002538 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002539 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002540 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002541 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002542 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002543
Eric Laurentda747442012-04-25 18:53:13 -07002544 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002545 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002546
Glenn Kasten37d825e2012-02-24 07:21:48 -08002547 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002548
Glenn Kasten000f0e32012-03-01 17:10:56 -08002549 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002550 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002551 if (mType == MIXER) {
2552 sleepTimeShift = 0;
2553 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002554
Mathias Agopian65ab4712010-07-14 17:59:35 -07002555 continue;
2556 }
2557 }
2558
Glenn Kasten81028042012-04-30 18:15:12 -07002559 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002560 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002561
2562 // prevent any changes in effect chain list and in each effect chain
2563 // during mixing and effect process as the audio buffers could be deleted
2564 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002565 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002566 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002567
Glenn Kastenfec279f2012-03-08 07:47:15 -08002568 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002569 threadLoop_mix();
2570 } else {
2571 threadLoop_sleepTime();
2572 }
2573
2574 if (mSuspended > 0) {
2575 sleepTime = suspendSleepTimeUs();
2576 }
2577
2578 // only process effects if we're going to write
2579 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002580 for (size_t i = 0; i < effectChains.size(); i ++) {
2581 effectChains[i]->process_l();
2582 }
2583 }
2584
2585 // enable changes in effect chain
2586 unlockEffectChains(effectChains);
2587
2588 // sleepTime == 0 means we must write to audio hardware
2589 if (sleepTime == 0) {
2590
2591 threadLoop_write();
2592
2593if (mType == MIXER) {
2594 // write blocked detection
2595 nsecs_t now = systemTime();
2596 nsecs_t delta = now - mLastWriteTime;
2597 if (!mStandby && delta > maxPeriod) {
2598 mNumDelayedWrites++;
2599 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002600#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002601 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002602#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002603 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2604 ns2ms(delta), mNumDelayedWrites, this);
2605 lastWarning = now;
2606 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002607 }
2608}
2609
2610 mStandby = false;
2611 } else {
2612 usleep(sleepTime);
2613 }
2614
Glenn Kasten58912562012-04-03 10:45:00 -07002615 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002616 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002617 // same lock. This will also mutate and push a new fast mixer state.
2618 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002619 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002620
Glenn Kastenfa26a852012-03-06 11:28:04 -08002621 // FIXME I don't understand the need for this here;
2622 // it was in the original code but maybe the
2623 // assignment in saveOutputTracks() makes this unnecessary?
2624 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002625
2626 // Effect chains will be actually deleted here if they were removed from
2627 // mEffectChains list during mixing or effects processing
2628 effectChains.clear();
2629
2630 // FIXME Note that the above .clear() is no longer necessary since effectChains
2631 // is now local to this block, but will keep it for now (at least until merge done).
2632 }
2633
Glenn Kasten9f34a362012-03-20 16:46:41 -07002634 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2635 if (mType == MIXER || mType == DIRECT) {
2636 // put output stream into standby mode
2637 if (!mStandby) {
2638 mOutput->stream->common.standby(&mOutput->stream->common);
2639 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002640 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002641
2642 releaseWakeLock();
2643
2644 ALOGV("Thread %p type %d exiting", this, mType);
2645 return false;
2646}
2647
Glenn Kasten58912562012-04-03 10:45:00 -07002648void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2649{
Glenn Kasten58912562012-04-03 10:45:00 -07002650 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2651}
2652
2653void AudioFlinger::MixerThread::threadLoop_write()
2654{
2655 // FIXME we should only do one push per cycle; confirm this is true
2656 // Start the fast mixer if it's not already running
2657 if (mFastMixer != NULL) {
2658 FastMixerStateQueue *sq = mFastMixer->sq();
2659 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002660 if (state->mCommand != FastMixerState::MIX_WRITE &&
2661 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002662 if (state->mCommand == FastMixerState::COLD_IDLE) {
2663 int32_t old = android_atomic_inc(&mFastMixerFutex);
2664 if (old == -1) {
2665 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2666 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002667 if (mAudioWatchdog != 0) {
2668 mAudioWatchdog->resume();
2669 }
Glenn Kasten58912562012-04-03 10:45:00 -07002670 }
2671 state->mCommand = FastMixerState::MIX_WRITE;
2672 sq->end();
2673 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002674 if (kUseFastMixer == FastMixer_Dynamic) {
2675 mNormalSink = mPipeSink;
2676 }
Glenn Kasten58912562012-04-03 10:45:00 -07002677 } else {
2678 sq->end(false /*didModify*/);
2679 }
2680 }
2681 PlaybackThread::threadLoop_write();
2682}
2683
Glenn Kasten000f0e32012-03-01 17:10:56 -08002684// shared by MIXER and DIRECT, overridden by DUPLICATING
2685void AudioFlinger::PlaybackThread::threadLoop_write()
2686{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002687 // FIXME rewrite to reduce number of system calls
2688 mLastWriteTime = systemTime();
2689 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002690 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002691
Eric Laurent67c0a582012-05-01 19:31:12 -07002692 // If an NBAIO sink is present, use it to write the normal mixer's submix
2693 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002694#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002695 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002696#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002697 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002698#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002699 // update the setpoint when gScreenState changes
2700 uint32_t screenState = gScreenState;
2701 if (screenState != mScreenState) {
2702 mScreenState = screenState;
2703 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2704 if (pipe != NULL) {
2705 pipe->setAvgFrames((mScreenState & 1) ?
2706 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2707 }
2708 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002709 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002710#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002711 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002712#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002713 if (framesWritten > 0) {
2714 bytesWritten = framesWritten << mBitShift;
2715 } else {
2716 bytesWritten = framesWritten;
2717 }
2718 // otherwise use the HAL / AudioStreamOut directly
2719 } else {
2720 // Direct output thread.
2721 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002722 }
2723
Eric Laurent67c0a582012-05-01 19:31:12 -07002724 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002725 mNumWrites++;
2726 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002727}
2728
Glenn Kasten58912562012-04-03 10:45:00 -07002729void AudioFlinger::MixerThread::threadLoop_standby()
2730{
2731 // Idle the fast mixer if it's currently running
2732 if (mFastMixer != NULL) {
2733 FastMixerStateQueue *sq = mFastMixer->sq();
2734 FastMixerState *state = sq->begin();
2735 if (!(state->mCommand & FastMixerState::IDLE)) {
2736 state->mCommand = FastMixerState::COLD_IDLE;
2737 state->mColdFutexAddr = &mFastMixerFutex;
2738 state->mColdGen++;
2739 mFastMixerFutex = 0;
2740 sq->end();
2741 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2742 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002743 if (kUseFastMixer == FastMixer_Dynamic) {
2744 mNormalSink = mOutputSink;
2745 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002746 if (mAudioWatchdog != 0) {
2747 mAudioWatchdog->pause();
2748 }
Glenn Kasten58912562012-04-03 10:45:00 -07002749 } else {
2750 sq->end(false /*didModify*/);
2751 }
2752 }
2753 PlaybackThread::threadLoop_standby();
2754}
2755
Glenn Kasten000f0e32012-03-01 17:10:56 -08002756// shared by MIXER and DIRECT, overridden by DUPLICATING
2757void AudioFlinger::PlaybackThread::threadLoop_standby()
2758{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002759 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2760 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002761}
2762
2763void AudioFlinger::MixerThread::threadLoop_mix()
2764{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002765 // obtain the presentation timestamp of the next output buffer
2766 int64_t pts;
2767 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002768
Glenn Kasten952eeb22012-03-06 11:30:57 -08002769 if (NULL != mOutput->stream->get_next_write_timestamp) {
2770 status = mOutput->stream->get_next_write_timestamp(
2771 mOutput->stream, &pts);
2772 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002773
Glenn Kasten952eeb22012-03-06 11:30:57 -08002774 if (status != NO_ERROR) {
2775 pts = AudioBufferProvider::kInvalidPTS;
2776 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002777
Glenn Kasten952eeb22012-03-06 11:30:57 -08002778 // mix buffers...
2779 mAudioMixer->process(pts);
2780 // increase sleep time progressively when application underrun condition clears.
2781 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2782 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2783 // such that we would underrun the audio HAL.
2784 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2785 sleepTimeShift--;
2786 }
2787 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002788 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002789 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002790}
2791
2792void AudioFlinger::MixerThread::threadLoop_sleepTime()
2793{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002794 // If no tracks are ready, sleep once for the duration of an output
2795 // buffer size, then write 0s to the output
2796 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002797 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002798 sleepTime = activeSleepTime >> sleepTimeShift;
2799 if (sleepTime < kMinThreadSleepTimeUs) {
2800 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002801 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002802 // reduce sleep time in case of consecutive application underruns to avoid
2803 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2804 // duration we would end up writing less data than needed by the audio HAL if
2805 // the condition persists.
2806 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2807 sleepTimeShift++;
2808 }
2809 } else {
2810 sleepTime = idleSleepTime;
2811 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002812 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002813 memset (mMixBuffer, 0, mixBufferSize);
2814 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002815 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002816 }
2817 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002818}
2819
2820// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002821AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002822 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002823{
2824
Glenn Kasten29c23c32012-01-26 13:37:52 -08002825 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002826 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002827 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002828 size_t mixedTracks = 0;
2829 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002830 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002831 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002832 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002833
2834 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002835 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002836
Eric Laurent571d49c2010-08-11 05:20:11 -07002837 if (masterMute) {
2838 masterVolume = 0;
2839 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002840 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002841 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002842 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002843 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002844 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002845 masterVolume = (float)((v + (1 << 23)) >> 24);
2846 chain.clear();
2847 }
2848
Glenn Kasten288ed212012-04-25 17:52:27 -07002849 // prepare a new state to push
2850 FastMixerStateQueue *sq = NULL;
2851 FastMixerState *state = NULL;
2852 bool didModify = false;
2853 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2854 if (mFastMixer != NULL) {
2855 sq = mFastMixer->sq();
2856 state = sq->begin();
2857 }
2858
Mathias Agopian65ab4712010-07-14 17:59:35 -07002859 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002860 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002861 if (t == 0) continue;
2862
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002863 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002864 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002865
Glenn Kasten288ed212012-04-25 17:52:27 -07002866 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002867 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002868
2869 // It's theoretically possible (though unlikely) for a fast track to be created
2870 // and then removed within the same normal mix cycle. This is not a problem, as
2871 // the track never becomes active so it's fast mixer slot is never touched.
2872 // The converse, of removing an (active) track and then creating a new track
2873 // at the identical fast mixer slot within the same normal mix cycle,
2874 // is impossible because the slot isn't marked available until the end of each cycle.
2875 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002876 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2877 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002878 FastTrack *fastTrack = &state->mFastTracks[j];
2879
2880 // Determine whether the track is currently in underrun condition,
2881 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002882 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2883 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002884 uint32_t recentFull = (underruns.mBitFields.mFull -
2885 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2886 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2887 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2888 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2889 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2890 uint32_t recentUnderruns = recentPartial + recentEmpty;
2891 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002892 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002893 // or stopped which can occur when flush() is called while active
2894 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002895 track->mUnderrunCount += recentUnderruns;
2896 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002897
Glenn Kastend08f48c2012-05-01 18:14:02 -07002898 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002899 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002900 bool isActive = true;
2901 switch (track->mState) {
2902 case TrackBase::STOPPING_1:
2903 // track stays active in STOPPING_1 state until first underrun
2904 if (recentUnderruns > 0) {
2905 track->mState = TrackBase::STOPPING_2;
2906 }
2907 break;
2908 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002909 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002910 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002911 break;
2912 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002913 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002914 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002915 break;
2916 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002917 if (recentFull > 0 || recentPartial > 0) {
2918 // track has provided at least some frames recently: reset retry count
2919 track->mRetryCount = kMaxTrackRetries;
2920 }
2921 if (recentUnderruns == 0) {
2922 // no recent underruns: stay active
2923 break;
2924 }
2925 // there has recently been an underrun of some kind
2926 if (track->sharedBuffer() == 0) {
2927 // were any of the recent underruns "empty" (no frames available)?
2928 if (recentEmpty == 0) {
2929 // no, then ignore the partial underruns as they are allowed indefinitely
2930 break;
2931 }
2932 // there has recently been an "empty" underrun: decrement the retry counter
2933 if (--(track->mRetryCount) > 0) {
2934 break;
2935 }
2936 // indicate to client process that the track was disabled because of underrun;
2937 // it will then automatically call start() when data is available
2938 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2939 // remove from active list, but state remains ACTIVE [confusing but true]
2940 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002941 break;
2942 }
2943 // fall through
2944 case TrackBase::STOPPING_2:
2945 case TrackBase::PAUSED:
2946 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002947 case TrackBase::STOPPED:
2948 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07002949 // Check for presentation complete if track is inactive
2950 // We have consumed all the buffers of this track.
2951 // This would be incomplete if we auto-paused on underrun
2952 {
2953 size_t audioHALFrames =
2954 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2955 size_t framesWritten =
2956 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2957 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2958 // track stays in active list until presentation is complete
2959 break;
2960 }
2961 }
2962 if (track->isStopping_2()) {
2963 track->mState = TrackBase::STOPPED;
2964 }
2965 if (track->isStopped()) {
2966 // Can't reset directly, as fast mixer is still polling this track
2967 // track->reset();
2968 // So instead mark this track as needing to be reset after push with ack
2969 resetMask |= 1 << i;
2970 }
2971 isActive = false;
2972 break;
2973 case TrackBase::IDLE:
2974 default:
2975 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07002976 }
2977
2978 if (isActive) {
2979 // was it previously inactive?
2980 if (!(state->mTrackMask & (1 << j))) {
2981 ExtendedAudioBufferProvider *eabp = track;
2982 VolumeProvider *vp = track;
2983 fastTrack->mBufferProvider = eabp;
2984 fastTrack->mVolumeProvider = vp;
2985 fastTrack->mSampleRate = track->mSampleRate;
2986 fastTrack->mChannelMask = track->mChannelMask;
2987 fastTrack->mGeneration++;
2988 state->mTrackMask |= 1 << j;
2989 didModify = true;
2990 // no acknowledgement required for newly active tracks
2991 }
2992 // cache the combined master volume and stream type volume for fast mixer; this
2993 // lacks any synchronization or barrier so VolumeProvider may read a stale value
2994 track->mCachedVolume = track->isMuted() ?
2995 0 : masterVolume * mStreamTypes[track->streamType()].volume;
2996 ++fastTracks;
2997 } else {
2998 // was it previously active?
2999 if (state->mTrackMask & (1 << j)) {
3000 fastTrack->mBufferProvider = NULL;
3001 fastTrack->mGeneration++;
3002 state->mTrackMask &= ~(1 << j);
3003 didModify = true;
3004 // If any fast tracks were removed, we must wait for acknowledgement
3005 // because we're about to decrement the last sp<> on those tracks.
3006 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003007 } else {
3008 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003009 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003010 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003011 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003012 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003013 }
3014 continue;
3015 }
3016
3017 { // local variable scope to avoid goto warning
3018
Mathias Agopian65ab4712010-07-14 17:59:35 -07003019 audio_track_cblk_t* cblk = track->cblk();
3020
3021 // The first time a track is added we wait
3022 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003023 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003024 // make sure that we have enough frames to mix one full buffer.
3025 // enforce this condition only once to enable draining the buffer in case the client
3026 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003027 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003028 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003029 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003030 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003031 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003032 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003033 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003034 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003035 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003036 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003037 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003038 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003039 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3040 // the minimum track buffer size is normally twice the number of frames necessary
3041 // to fill one buffer and the resampler should not leave more than one buffer worth
3042 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003043 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003044 }
3045 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003046 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003047 !track->isPaused() && !track->isTerminated())
3048 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003049 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003050
3051 mixedTracks++;
3052
3053 // track->mainBuffer() != mMixBuffer means there is an effect chain
3054 // connected to the track
3055 chain.clear();
3056 if (track->mainBuffer() != mMixBuffer) {
3057 chain = getEffectChain_l(track->sessionId());
3058 // Delegate volume control to effect in track effect chain if needed
3059 if (chain != 0) {
3060 tracksWithEffect++;
3061 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003062 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003063 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003064 }
3065 }
3066
3067
3068 int param = AudioMixer::VOLUME;
3069 if (track->mFillingUpStatus == Track::FS_FILLED) {
3070 // no ramp for the first volume setting
3071 track->mFillingUpStatus = Track::FS_ACTIVE;
3072 if (track->mState == TrackBase::RESUMING) {
3073 track->mState = TrackBase::ACTIVE;
3074 param = AudioMixer::RAMP_VOLUME;
3075 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003076 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003077 } else if (cblk->server != 0) {
3078 // If the track is stopped before the first frame was mixed,
3079 // do not apply ramp
3080 param = AudioMixer::RAMP_VOLUME;
3081 }
3082
3083 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003084 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003085 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003086 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003087 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003088 if (track->isPausing()) {
3089 track->setPaused();
3090 }
3091 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003092
Mathias Agopian65ab4712010-07-14 17:59:35 -07003093 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003094 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003095 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003096 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003097 vl = vlr & 0xFFFF;
3098 vr = vlr >> 16;
3099 // track volumes come from shared memory, so can't be trusted and must be clamped
3100 if (vl > MAX_GAIN_INT) {
3101 ALOGV("Track left volume out of range: %04X", vl);
3102 vl = MAX_GAIN_INT;
3103 }
3104 if (vr > MAX_GAIN_INT) {
3105 ALOGV("Track right volume out of range: %04X", vr);
3106 vr = MAX_GAIN_INT;
3107 }
3108 // now apply the master volume and stream type volume
3109 vl = (uint32_t)(v * vl) << 12;
3110 vr = (uint32_t)(v * vr) << 12;
3111 // assuming master volume and stream type volume each go up to 1.0,
3112 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003113
Glenn Kasten05632a52012-01-03 14:22:33 -08003114 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3115 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003116 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003117 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003118 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003119 }
3120 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003121 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003122 // Delegate volume control to effect in track effect chain if needed
3123 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3124 // Do not ramp volume if volume is controlled by effect
3125 param = AudioMixer::VOLUME;
3126 track->mHasVolumeController = true;
3127 } else {
3128 // force no volume ramp when volume controller was just disabled or removed
3129 // from effect chain to avoid volume spike
3130 if (track->mHasVolumeController) {
3131 param = AudioMixer::VOLUME;
3132 }
3133 track->mHasVolumeController = false;
3134 }
3135
3136 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003137 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003138 vl = (vl + (1 << 11)) >> 12;
3139 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3140 vr = (vr + (1 << 11)) >> 12;
3141 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003142
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003143 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 -07003144
Mathias Agopian65ab4712010-07-14 17:59:35 -07003145 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003146 mAudioMixer->setBufferProvider(name, track);
3147 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003148
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003149 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3150 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3151 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003152 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003153 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003154 AudioMixer::TRACK,
3155 AudioMixer::FORMAT, (void *)track->format());
3156 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003157 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003158 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003159 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003160 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003161 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003162 AudioMixer::RESAMPLE,
3163 AudioMixer::SAMPLE_RATE,
3164 (void *)(cblk->sampleRate));
3165 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003166 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003167 AudioMixer::TRACK,
3168 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3169 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003170 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003171 AudioMixer::TRACK,
3172 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3173
3174 // reset retry count
3175 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003176
Eric Laurent27741442012-01-17 19:20:12 -08003177 // If one track is ready, set the mixer ready if:
3178 // - the mixer was not ready during previous round OR
3179 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003180 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003181 mixerStatus != MIXER_TRACKS_ENABLED) {
3182 mixerStatus = MIXER_TRACKS_READY;
3183 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003185 // clear effect chain input buffer if an active track underruns to avoid sending
3186 // previous audio buffer again to effects
3187 chain = getEffectChain_l(track->sessionId());
3188 if (chain != 0) {
3189 chain->clearInputBuffer();
3190 }
3191
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003192 //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 -07003193 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3194 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003195 // We have consumed all the buffers of this track.
3196 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003197 // TODO: use actual buffer filling status instead of latency when available from
3198 // audio HAL
3199 size_t audioHALFrames =
3200 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3201 size_t framesWritten =
3202 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3203 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003204 if (track->isStopped()) {
3205 track->reset();
3206 }
Eric Laurenta011e352012-03-29 15:51:43 -07003207 tracksToRemove->add(track);
3208 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003209 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003210 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003211 // No buffers for this track. Give it a few chances to
3212 // fill a buffer, then remove it from active list.
3213 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003214 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003215 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003216 // indicate to client process that the track was disabled because of underrun;
3217 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003218 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003219 // If one track is not ready, mark the mixer also not ready if:
3220 // - the mixer was ready during previous round OR
3221 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003222 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003223 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003224 mixerStatus = MIXER_TRACKS_ENABLED;
3225 }
3226 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003227 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003228 }
Glenn Kasten58912562012-04-03 10:45:00 -07003229
3230 } // local variable scope to avoid goto warning
3231track_is_ready: ;
3232
Mathias Agopian65ab4712010-07-14 17:59:35 -07003233 }
3234
Glenn Kasten288ed212012-04-25 17:52:27 -07003235 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003236 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003237 if (didModify) {
3238 state->mFastTracksGen++;
3239 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3240 if (kUseFastMixer == FastMixer_Dynamic &&
3241 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3242 state->mCommand = FastMixerState::COLD_IDLE;
3243 state->mColdFutexAddr = &mFastMixerFutex;
3244 state->mColdGen++;
3245 mFastMixerFutex = 0;
3246 if (kUseFastMixer == FastMixer_Dynamic) {
3247 mNormalSink = mOutputSink;
3248 }
3249 // If we go into cold idle, need to wait for acknowledgement
3250 // so that fast mixer stops doing I/O.
3251 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003252 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003253 }
3254 sq->end();
3255 }
3256 if (sq != NULL) {
3257 sq->end(didModify);
3258 sq->push(block);
3259 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07003260 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3261 mAudioWatchdog->pause();
3262 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003263
3264 // Now perform the deferred reset on fast tracks that have stopped
3265 while (resetMask != 0) {
3266 size_t i = __builtin_ctz(resetMask);
3267 ALOG_ASSERT(i < count);
3268 resetMask &= ~(1 << i);
3269 sp<Track> t = mActiveTracks[i].promote();
3270 if (t == 0) continue;
3271 Track* track = t.get();
3272 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3273 track->reset();
3274 }
Glenn Kasten58912562012-04-03 10:45:00 -07003275
Mathias Agopian65ab4712010-07-14 17:59:35 -07003276 // remove all the tracks that need to be...
3277 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003278 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003279 for (size_t i=0 ; i<count ; i++) {
3280 const sp<Track>& track = tracksToRemove->itemAt(i);
3281 mActiveTracks.remove(track);
3282 if (track->mainBuffer() != mMixBuffer) {
3283 chain = getEffectChain_l(track->sessionId());
3284 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003285 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003286 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003287 }
3288 }
3289 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003290 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003291 }
3292 }
3293 }
3294
3295 // mix buffer must be cleared if all tracks are connected to an
3296 // effect chain as in this case the mixer will not write to
3297 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003298 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3299 // FIXME as a performance optimization, should remember previous zero status
3300 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003301 }
3302
Glenn Kasten58912562012-04-03 10:45:00 -07003303 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003304 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003305 if (fastTracks > 0) {
3306 mixerStatus = MIXER_TRACKS_READY;
3307 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003308 return mixerStatus;
3309}
3310
Glenn Kasten66fcab92012-02-24 14:59:21 -08003311/*
3312The derived values that are cached:
3313 - mixBufferSize from frame count * frame size
3314 - activeSleepTime from activeSleepTimeUs()
3315 - idleSleepTime from idleSleepTimeUs()
3316 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3317 - maxPeriod from frame count and sample rate (MIXER only)
3318
3319The parameters that affect these derived values are:
3320 - frame count
3321 - frame size
3322 - sample rate
3323 - device type: A2DP or not
3324 - device latency
3325 - format: PCM or not
3326 - active sleep time
3327 - idle sleep time
3328*/
3329
3330void AudioFlinger::PlaybackThread::cacheParameters_l()
3331{
Glenn Kasten58912562012-04-03 10:45:00 -07003332 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003333 activeSleepTime = activeSleepTimeUs();
3334 idleSleepTime = idleSleepTimeUs();
3335}
3336
Eric Laurent22167852012-06-20 12:26:32 -07003337void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003338{
Steve Block3856b092011-10-20 11:56:00 +01003339 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003340 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003341 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003342
Mathias Agopian65ab4712010-07-14 17:59:35 -07003343 size_t size = mTracks.size();
3344 for (size_t i = 0; i < size; i++) {
3345 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003346 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003347 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003348 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003349 }
3350 }
3351}
3352
Mathias Agopian65ab4712010-07-14 17:59:35 -07003353// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003354int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003355{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003356 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003357}
3358
3359// deleteTrackName_l() must be called with ThreadBase::mLock held
3360void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3361{
Steve Block3856b092011-10-20 11:56:00 +01003362 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003363 mAudioMixer->deleteTrackName(name);
3364}
3365
3366// checkForNewParameters_l() must be called with ThreadBase::mLock held
3367bool AudioFlinger::MixerThread::checkForNewParameters_l()
3368{
Glenn Kasten58912562012-04-03 10:45:00 -07003369 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3370 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003371 bool reconfig = false;
3372
3373 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003374
3375 if (mFastMixer != NULL) {
3376 FastMixerStateQueue *sq = mFastMixer->sq();
3377 FastMixerState *state = sq->begin();
3378 if (!(state->mCommand & FastMixerState::IDLE)) {
3379 previousCommand = state->mCommand;
3380 state->mCommand = FastMixerState::HOT_IDLE;
3381 sq->end();
3382 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3383 } else {
3384 sq->end(false /*didModify*/);
3385 }
3386 }
3387
Mathias Agopian65ab4712010-07-14 17:59:35 -07003388 status_t status = NO_ERROR;
3389 String8 keyValuePair = mNewParameters[0];
3390 AudioParameter param = AudioParameter(keyValuePair);
3391 int value;
3392
3393 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3394 reconfig = true;
3395 }
3396 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003397 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003398 status = BAD_VALUE;
3399 } else {
3400 reconfig = true;
3401 }
3402 }
3403 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003404 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003405 status = BAD_VALUE;
3406 } else {
3407 reconfig = true;
3408 }
3409 }
3410 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3411 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003412 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003413 // if frame count is changed after track creation
3414 if (!mTracks.isEmpty()) {
3415 status = INVALID_OPERATION;
3416 } else {
3417 reconfig = true;
3418 }
3419 }
3420 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003421#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003422 // when changing the audio output device, call addBatteryData to notify
3423 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003424 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003425 uint32_t params = 0;
3426 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003427 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003428 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3429 }
3430
3431 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003432 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003433 // check if any other device (except speaker) is on
3434 if (value & deviceWithoutSpeaker ) {
3435 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3436 }
3437
3438 if (params != 0) {
3439 addBatteryData(params);
3440 }
3441 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003442#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003443
Mathias Agopian65ab4712010-07-14 17:59:35 -07003444 // forward device change to effects that have requested to be
3445 // aware of attached audio device.
Glenn Kasten94479fd2012-07-09 15:39:54 -07003446 mDevice = (audio_devices_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003447 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003448 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003449 }
3450 }
3451
3452 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003453 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003454 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003455 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003456 mOutput->stream->common.standby(&mOutput->stream->common);
3457 mStandby = true;
3458 mBytesWritten = 0;
3459 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003460 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003461 }
3462 if (status == NO_ERROR && reconfig) {
3463 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003464 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3465 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003466 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003467 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003468 for (size_t i = 0; i < mTracks.size() ; i++) {
Glenn Kasten254af182012-07-03 14:59:05 -07003469 int name = getTrackName_l(mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003470 if (name < 0) break;
3471 mTracks[i]->mName = name;
3472 // limit track sample rate to 2 x new output sample rate
3473 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3474 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3475 }
3476 }
3477 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3478 }
3479 }
3480
3481 mNewParameters.removeAt(0);
3482
3483 mParamStatus = status;
3484 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003485 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3486 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003487 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003488 }
Glenn Kasten58912562012-04-03 10:45:00 -07003489
3490 if (!(previousCommand & FastMixerState::IDLE)) {
3491 ALOG_ASSERT(mFastMixer != NULL);
3492 FastMixerStateQueue *sq = mFastMixer->sq();
3493 FastMixerState *state = sq->begin();
3494 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3495 state->mCommand = previousCommand;
3496 sq->end();
3497 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3498 }
3499
Mathias Agopian65ab4712010-07-14 17:59:35 -07003500 return reconfig;
3501}
3502
3503status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3504{
3505 const size_t SIZE = 256;
3506 char buffer[SIZE];
3507 String8 result;
3508
3509 PlaybackThread::dumpInternals(fd, args);
3510
3511 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3512 result.append(buffer);
3513 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003514
3515 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3516 FastMixerDumpState copy = mFastMixerDumpState;
3517 copy.dump(fd);
3518
Glenn Kasten39993082012-05-31 13:40:27 -07003519#ifdef STATE_QUEUE_DUMP
3520 // Similar for state queue
3521 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3522 observerCopy.dump(fd);
3523 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3524 mutatorCopy.dump(fd);
3525#endif
3526
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003527 // Write the tee output to a .wav file
3528 NBAIO_Source *teeSource = mTeeSource.get();
3529 if (teeSource != NULL) {
3530 char teePath[64];
3531 struct timeval tv;
3532 gettimeofday(&tv, NULL);
3533 struct tm tm;
3534 localtime_r(&tv.tv_sec, &tm);
3535 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3536 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3537 if (teeFd >= 0) {
3538 char wavHeader[44];
3539 memcpy(wavHeader,
3540 "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",
3541 sizeof(wavHeader));
3542 NBAIO_Format format = teeSource->format();
3543 unsigned channelCount = Format_channelCount(format);
3544 ALOG_ASSERT(channelCount <= FCC_2);
3545 unsigned sampleRate = Format_sampleRate(format);
3546 wavHeader[22] = channelCount; // number of channels
3547 wavHeader[24] = sampleRate; // sample rate
3548 wavHeader[25] = sampleRate >> 8;
3549 wavHeader[32] = channelCount * 2; // block alignment
3550 write(teeFd, wavHeader, sizeof(wavHeader));
3551 size_t total = 0;
3552 bool firstRead = true;
3553 for (;;) {
3554#define TEE_SINK_READ 1024
3555 short buffer[TEE_SINK_READ * FCC_2];
3556 size_t count = TEE_SINK_READ;
3557 ssize_t actual = teeSource->read(buffer, count);
3558 bool wasFirstRead = firstRead;
3559 firstRead = false;
3560 if (actual <= 0) {
3561 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3562 continue;
3563 }
3564 break;
3565 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003566 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003567 write(teeFd, buffer, actual * channelCount * sizeof(short));
3568 total += actual;
3569 }
3570 lseek(teeFd, (off_t) 4, SEEK_SET);
3571 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3572 write(teeFd, &temp, sizeof(temp));
3573 lseek(teeFd, (off_t) 40, SEEK_SET);
3574 temp = total * channelCount * sizeof(short);
3575 write(teeFd, &temp, sizeof(temp));
3576 close(teeFd);
3577 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3578 } else {
3579 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3580 }
3581 }
3582
Glenn Kastenc15d6652012-05-30 14:52:57 -07003583 if (mAudioWatchdog != 0) {
3584 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3585 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3586 wdCopy.dump(fd);
3587 }
3588
Mathias Agopian65ab4712010-07-14 17:59:35 -07003589 return NO_ERROR;
3590}
3591
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003592uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003593{
Glenn Kasten58912562012-04-03 10:45:00 -07003594 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003595}
3596
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003597uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003598{
Glenn Kasten58912562012-04-03 10:45:00 -07003599 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003600}
3601
Glenn Kasten66fcab92012-02-24 14:59:21 -08003602void AudioFlinger::MixerThread::cacheParameters_l()
3603{
3604 PlaybackThread::cacheParameters_l();
3605
3606 // FIXME: Relaxed timing because of a certain device that can't meet latency
3607 // Should be reduced to 2x after the vendor fixes the driver issue
3608 // increase threshold again due to low power audio mode. The way this warning
3609 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003610 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003611}
3612
Mathias Agopian65ab4712010-07-14 17:59:35 -07003613// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003614AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3615 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003616 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003617 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003618{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003619}
3620
3621AudioFlinger::DirectOutputThread::~DirectOutputThread()
3622{
3623}
3624
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003625AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3626 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003627)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003628{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003629 sp<Track> trackToRemove;
3630
Glenn Kastenfec279f2012-03-08 07:47:15 -08003631 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003632
Glenn Kasten952eeb22012-03-06 11:30:57 -08003633 // find out which tracks need to be processed
3634 if (mActiveTracks.size() != 0) {
3635 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003636 // The track died recently
3637 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003638
Glenn Kasten952eeb22012-03-06 11:30:57 -08003639 Track* const track = t.get();
3640 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003641
Glenn Kasten952eeb22012-03-06 11:30:57 -08003642 // The first time a track is added we wait
3643 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003644 uint32_t minFrames;
3645 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3646 minFrames = mNormalFrameCount;
3647 } else {
3648 minFrames = 1;
3649 }
3650 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003651 !track->isPaused() && !track->isTerminated())
3652 {
3653 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003654
Glenn Kasten952eeb22012-03-06 11:30:57 -08003655 if (track->mFillingUpStatus == Track::FS_FILLED) {
3656 track->mFillingUpStatus = Track::FS_ACTIVE;
3657 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003658 if (track->mState == TrackBase::RESUMING) {
3659 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003660 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003661 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003662
Glenn Kasten952eeb22012-03-06 11:30:57 -08003663 // compute volume for this track
3664 float left, right;
3665 if (track->isMuted() || mMasterMute || track->isPausing() ||
3666 mStreamTypes[track->streamType()].mute) {
3667 left = right = 0;
3668 if (track->isPausing()) {
3669 track->setPaused();
3670 }
3671 } else {
3672 float typeVolume = mStreamTypes[track->streamType()].volume;
3673 float v = mMasterVolume * typeVolume;
3674 uint32_t vlr = cblk->getVolumeLR();
3675 float v_clamped = v * (vlr & 0xFFFF);
3676 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3677 left = v_clamped/MAX_GAIN;
3678 v_clamped = v * (vlr >> 16);
3679 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3680 right = v_clamped/MAX_GAIN;
3681 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003682
Glenn Kasten952eeb22012-03-06 11:30:57 -08003683 if (left != mLeftVolFloat || right != mRightVolFloat) {
3684 mLeftVolFloat = left;
3685 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003686
Glenn Kasten952eeb22012-03-06 11:30:57 -08003687 // Convert volumes from float to 8.24
3688 uint32_t vl = (uint32_t)(left * (1 << 24));
3689 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003690
Glenn Kasten952eeb22012-03-06 11:30:57 -08003691 // Delegate volume control to effect in track effect chain if needed
3692 // only one effect chain can be present on DirectOutputThread, so if
3693 // there is one, the track is connected to it
3694 if (!mEffectChains.isEmpty()) {
3695 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003696 mEffectChains[0]->setVolume_l(&vl, &vr);
3697 left = (float)vl / (1 << 24);
3698 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003699 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003700 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003701 }
3702
3703 // reset retry count
3704 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003705 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003706 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003707 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003708 // clear effect chain input buffer if an active track underruns to avoid sending
3709 // previous audio buffer again to effects
3710 if (!mEffectChains.isEmpty()) {
3711 mEffectChains[0]->clearInputBuffer();
3712 }
3713
Glenn Kasten952eeb22012-03-06 11:30:57 -08003714 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurent67c0a582012-05-01 19:31:12 -07003715 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3716 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003717 // We have consumed all the buffers of this track.
3718 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003719 // TODO: implement behavior for compressed audio
3720 size_t audioHALFrames =
3721 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3722 size_t framesWritten =
3723 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3724 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003725 if (track->isStopped()) {
3726 track->reset();
3727 }
Eric Laurenta011e352012-03-29 15:51:43 -07003728 trackToRemove = track;
3729 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003730 } else {
3731 // No buffers for this track. Give it a few chances to
3732 // fill a buffer, then remove it from active list.
3733 if (--(track->mRetryCount) <= 0) {
3734 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3735 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003736 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003737 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003738 }
3739 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003740 }
3741 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003742
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003743 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003744 // remove all the tracks that need to be...
3745 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003746 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003747 mActiveTracks.remove(trackToRemove);
3748 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003749 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003750 trackToRemove->sessionId());
3751 mEffectChains[0]->decActiveTrackCnt();
3752 }
3753 if (trackToRemove->isTerminated()) {
3754 removeTrack_l(trackToRemove);
3755 }
3756 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003757
Glenn Kastenfec279f2012-03-08 07:47:15 -08003758 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003759}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003760
Glenn Kasten000f0e32012-03-01 17:10:56 -08003761void AudioFlinger::DirectOutputThread::threadLoop_mix()
3762{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003763 AudioBufferProvider::Buffer buffer;
3764 size_t frameCount = mFrameCount;
3765 int8_t *curBuf = (int8_t *)mMixBuffer;
3766 // output audio to hardware
3767 while (frameCount) {
3768 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003769 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003770 if (CC_UNLIKELY(buffer.raw == NULL)) {
3771 memset(curBuf, 0, frameCount * mFrameSize);
3772 break;
3773 }
3774 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3775 frameCount -= buffer.frameCount;
3776 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003777 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003778 }
3779 sleepTime = 0;
3780 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003781 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003782
Glenn Kasten000f0e32012-03-01 17:10:56 -08003783}
3784
3785void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3786{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003787 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003788 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003789 sleepTime = activeSleepTime;
3790 } else {
3791 sleepTime = idleSleepTime;
3792 }
3793 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003794 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003795 sleepTime = 0;
3796 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003797}
3798
3799// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003800int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003801{
3802 return 0;
3803}
3804
3805// deleteTrackName_l() must be called with ThreadBase::mLock held
3806void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3807{
3808}
3809
3810// checkForNewParameters_l() must be called with ThreadBase::mLock held
3811bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3812{
3813 bool reconfig = false;
3814
3815 while (!mNewParameters.isEmpty()) {
3816 status_t status = NO_ERROR;
3817 String8 keyValuePair = mNewParameters[0];
3818 AudioParameter param = AudioParameter(keyValuePair);
3819 int value;
3820
3821 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3822 // do not accept frame count changes if tracks are open as the track buffer
3823 // size depends on frame count and correct behavior would not be garantied
3824 // if frame count is changed after track creation
3825 if (!mTracks.isEmpty()) {
3826 status = INVALID_OPERATION;
3827 } else {
3828 reconfig = true;
3829 }
3830 }
3831 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003832 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003833 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003834 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003835 mOutput->stream->common.standby(&mOutput->stream->common);
3836 mStandby = true;
3837 mBytesWritten = 0;
3838 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003839 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003840 }
3841 if (status == NO_ERROR && reconfig) {
3842 readOutputParameters();
3843 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3844 }
3845 }
3846
3847 mNewParameters.removeAt(0);
3848
3849 mParamStatus = status;
3850 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003851 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3852 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003853 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003854 }
3855 return reconfig;
3856}
3857
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003858uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003859{
3860 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003861 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003862 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003863 } else {
3864 time = 10000;
3865 }
3866 return time;
3867}
3868
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003869uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003870{
3871 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003872 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003873 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003874 } else {
3875 time = 10000;
3876 }
3877 return time;
3878}
3879
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003880uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003881{
3882 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003883 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003884 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3885 } else {
3886 time = 10000;
3887 }
3888 return time;
3889}
3890
Glenn Kasten66fcab92012-02-24 14:59:21 -08003891void AudioFlinger::DirectOutputThread::cacheParameters_l()
3892{
3893 PlaybackThread::cacheParameters_l();
3894
3895 // use shorter standby delay as on normal output to release
3896 // hardware resources as soon as possible
3897 standbyDelay = microseconds(activeSleepTime*2);
3898}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003899
Mathias Agopian65ab4712010-07-14 17:59:35 -07003900// ----------------------------------------------------------------------------
3901
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003902AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003903 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003904 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3905 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003906{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003907 addOutputTrack(mainThread);
3908}
3909
3910AudioFlinger::DuplicatingThread::~DuplicatingThread()
3911{
3912 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3913 mOutputTracks[i]->destroy();
3914 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003915}
3916
Glenn Kasten000f0e32012-03-01 17:10:56 -08003917void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003918{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003919 // mix buffers...
3920 if (outputsReady(outputTracks)) {
3921 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3922 } else {
3923 memset(mMixBuffer, 0, mixBufferSize);
3924 }
3925 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003926 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003927 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003928}
3929
3930void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3931{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003932 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003933 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003934 sleepTime = activeSleepTime;
3935 } else {
3936 sleepTime = idleSleepTime;
3937 }
3938 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003939 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3940 writeFrames = mNormalFrameCount;
3941 memset(mMixBuffer, 0, mixBufferSize);
3942 } else {
3943 // flush remaining overflow buffers in output tracks
3944 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003945 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003946 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003947 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003948}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003949
Glenn Kasten000f0e32012-03-01 17:10:56 -08003950void AudioFlinger::DuplicatingThread::threadLoop_write()
3951{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003952 for (size_t i = 0; i < outputTracks.size(); i++) {
3953 outputTracks[i]->write(mMixBuffer, writeFrames);
3954 }
3955 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003956}
Glenn Kasten688a6402012-02-29 07:57:06 -08003957
Glenn Kasten000f0e32012-03-01 17:10:56 -08003958void AudioFlinger::DuplicatingThread::threadLoop_standby()
3959{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003960 // DuplicatingThread implements standby by stopping all tracks
3961 for (size_t i = 0; i < outputTracks.size(); i++) {
3962 outputTracks[i]->stop();
3963 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003964}
3965
Glenn Kastenfa26a852012-03-06 11:28:04 -08003966void AudioFlinger::DuplicatingThread::saveOutputTracks()
3967{
3968 outputTracks = mOutputTracks;
3969}
3970
3971void AudioFlinger::DuplicatingThread::clearOutputTracks()
3972{
3973 outputTracks.clear();
3974}
3975
Mathias Agopian65ab4712010-07-14 17:59:35 -07003976void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3977{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003978 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003979 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07003980 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003981 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003982 this,
3983 mSampleRate,
3984 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003985 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003986 frameCount);
3987 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003988 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003989 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003990 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003991 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003992 }
3993}
3994
3995void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3996{
3997 Mutex::Autolock _l(mLock);
3998 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003999 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004000 mOutputTracks[i]->destroy();
4001 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004002 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004003 return;
4004 }
4005 }
Steve Block3856b092011-10-20 11:56:00 +01004006 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004007}
4008
Glenn Kasten438b0362012-03-06 11:24:48 -08004009// caller must hold mLock
4010void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004011{
4012 mWaitTimeMs = UINT_MAX;
4013 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4014 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004015 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004016 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4017 if (waitTimeMs < mWaitTimeMs) {
4018 mWaitTimeMs = waitTimeMs;
4019 }
4020 }
4021 }
4022}
4023
4024
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004025bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004026{
4027 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004028 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004029 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004030 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004031 return false;
4032 }
4033 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004034 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004035 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004036 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004037 return false;
4038 }
4039 }
4040 return true;
4041}
4042
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004043uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004044{
4045 return (mWaitTimeMs * 1000) / 2;
4046}
4047
Glenn Kasten66fcab92012-02-24 14:59:21 -08004048void AudioFlinger::DuplicatingThread::cacheParameters_l()
4049{
4050 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4051 updateWaitTime_l();
4052
4053 MixerThread::cacheParameters_l();
4054}
4055
Mathias Agopian65ab4712010-07-14 17:59:35 -07004056// ----------------------------------------------------------------------------
4057
4058// TrackBase constructor must be called with AudioFlinger::mLock held
4059AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004060 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004061 const sp<Client>& client,
4062 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004063 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004064 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004065 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004066 const sp<IMemory>& sharedBuffer,
4067 int sessionId)
4068 : RefBase(),
4069 mThread(thread),
4070 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004071 mCblk(NULL),
4072 // mBuffer
4073 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004074 mFrameCount(0),
4075 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004076 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004077 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004078 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004079 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004080 // mChannelCount
4081 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004082{
Steve Block3856b092011-10-20 11:56:00 +01004083 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004084
Steve Blockb8a80522011-12-20 16:23:08 +00004085 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004086 size_t size = sizeof(audio_track_cblk_t);
4087 uint8_t channelCount = popcount(channelMask);
4088 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4089 if (sharedBuffer == 0) {
4090 size += bufferSize;
4091 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004092
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004093 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004094 mCblkMemory = client->heap()->allocate(size);
4095 if (mCblkMemory != 0) {
4096 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004097 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004098 new(mCblk) audio_track_cblk_t();
4099 // clear all buffers
4100 mCblk->frameCount = frameCount;
4101 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004102// uncomment the following lines to quickly test 32-bit wraparound
4103// mCblk->user = 0xffff0000;
4104// mCblk->server = 0xffff0000;
4105// mCblk->userBase = 0xffff0000;
4106// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004107 mChannelCount = channelCount;
4108 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004109 if (sharedBuffer == 0) {
4110 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4111 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4112 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004113 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004114 mCblk->flags = CBLK_UNDERRUN_ON;
4115 } else {
4116 mBuffer = sharedBuffer->pointer();
4117 }
4118 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4119 }
4120 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004121 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004122 client->heap()->dump("AudioTrack");
4123 return;
4124 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004125 } else {
4126 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004127 // construct the shared structure in-place.
4128 new(mCblk) audio_track_cblk_t();
4129 // clear all buffers
4130 mCblk->frameCount = frameCount;
4131 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004132// uncomment the following lines to quickly test 32-bit wraparound
4133// mCblk->user = 0xffff0000;
4134// mCblk->server = 0xffff0000;
4135// mCblk->userBase = 0xffff0000;
4136// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004137 mChannelCount = channelCount;
4138 mChannelMask = channelMask;
4139 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4140 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4141 // Force underrun condition to avoid false underrun callback until first data is
4142 // written to buffer (other flags are cleared)
4143 mCblk->flags = CBLK_UNDERRUN_ON;
4144 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004145 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004146}
4147
4148AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4149{
Glenn Kastena0d68332012-01-27 16:47:15 -08004150 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004151 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004152 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004153 } else {
4154 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004155 }
4156 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004157 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004158 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004159 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004160 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004161 // If the client's reference count drops to zero, the associated destructor
4162 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4163 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004164 mClient.clear();
4165 }
4166}
4167
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004168// AudioBufferProvider interface
4169// getNextBuffer() = 0;
4170// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004171void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4172{
Glenn Kastene0feee32011-12-13 11:53:26 -08004173 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004174 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004175 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004176 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004177 buffer->frameCount = 0;
4178}
4179
4180bool AudioFlinger::ThreadBase::TrackBase::step() {
4181 bool result;
4182 audio_track_cblk_t* cblk = this->cblk();
4183
4184 result = cblk->stepServer(mFrameCount);
4185 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004186 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004187 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004188 }
4189 return result;
4190}
4191
4192void AudioFlinger::ThreadBase::TrackBase::reset() {
4193 audio_track_cblk_t* cblk = this->cblk();
4194
4195 cblk->user = 0;
4196 cblk->server = 0;
4197 cblk->userBase = 0;
4198 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004199 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004200 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004201}
4202
Mathias Agopian65ab4712010-07-14 17:59:35 -07004203int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4204 return (int)mCblk->sampleRate;
4205}
4206
Mathias Agopian65ab4712010-07-14 17:59:35 -07004207void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4208 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004209 size_t frameSize = cblk->frameSize;
4210 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4211 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004212
4213 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004214 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4215 "TrackBase::getBuffer buffer out of range:\n"
4216 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4217 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004218 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004219 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004220
4221 return bufferStart;
4222}
4223
Eric Laurenta011e352012-03-29 15:51:43 -07004224status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4225{
4226 mSyncEvents.add(event);
4227 return NO_ERROR;
4228}
4229
Mathias Agopian65ab4712010-07-14 17:59:35 -07004230// ----------------------------------------------------------------------------
4231
4232// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4233AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004234 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004235 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004236 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004237 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004238 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004239 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004240 int frameCount,
4241 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004242 int sessionId,
4243 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004244 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004245 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004246 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004247 // mRetryCount initialized later when needed
4248 mSharedBuffer(sharedBuffer),
4249 mStreamType(streamType),
4250 mName(-1), // see note below
4251 mMainBuffer(thread->mixBuffer()),
4252 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004253 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004254 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004255 mFlags(flags),
4256 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004257 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004258 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004259{
4260 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004261 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4262 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004263 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004264 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Glenn Kasten254af182012-07-03 14:59:05 -07004265 mName = thread->getTrackName_l(channelMask);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004266 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004267 if (mName < 0) {
4268 ALOGE("no more track names available");
4269 return;
4270 }
4271 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004272 if (flags & IAudioFlinger::TRACK_FAST) {
4273 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4274 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4275 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004276 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004277 // FIXME This is too eager. We allocate a fast track index before the
4278 // fast track becomes active. Since fast tracks are a scarce resource,
4279 // this means we are potentially denying other more important fast tracks from
4280 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004281 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004282 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004283 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004284 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004285 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004286 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004287 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004288 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004289}
4290
4291AudioFlinger::PlaybackThread::Track::~Track()
4292{
Steve Block3856b092011-10-20 11:56:00 +01004293 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004294 sp<ThreadBase> thread = mThread.promote();
4295 if (thread != 0) {
4296 Mutex::Autolock _l(thread->mLock);
4297 mState = TERMINATED;
4298 }
4299}
4300
4301void AudioFlinger::PlaybackThread::Track::destroy()
4302{
4303 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4304 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004305 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004306 // we must acquire a strong reference on this Track before locking mLock
4307 // here so that the destructor is called only when exiting this function.
4308 // On the other hand, as long as Track::destroy() is only called by
4309 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4310 // this Track with its member mTrack.
4311 sp<Track> keep(this);
4312 { // scope for mLock
4313 sp<ThreadBase> thread = mThread.promote();
4314 if (thread != 0) {
4315 if (!isOutputTrack()) {
4316 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004317 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004318
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004319#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004320 // to track the speaker usage
4321 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004322#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004323 }
4324 AudioSystem::releaseOutput(thread->id());
4325 }
4326 Mutex::Autolock _l(thread->mLock);
4327 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4328 playbackThread->destroyTrack_l(this);
4329 }
4330 }
4331}
4332
Glenn Kasten288ed212012-04-25 17:52:27 -07004333/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4334{
Glenn Kastene213c862012-04-25 13:46:15 -07004335 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 -07004336 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004337}
4338
Mathias Agopian65ab4712010-07-14 17:59:35 -07004339void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4340{
Glenn Kasten83d86532012-01-17 14:39:34 -08004341 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004342 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004343 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004344 } else {
4345 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4346 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004347 track_state state = mState;
4348 char stateChar;
4349 switch (state) {
4350 case IDLE:
4351 stateChar = 'I';
4352 break;
4353 case TERMINATED:
4354 stateChar = 'T';
4355 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004356 case STOPPING_1:
4357 stateChar = 's';
4358 break;
4359 case STOPPING_2:
4360 stateChar = '5';
4361 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004362 case STOPPED:
4363 stateChar = 'S';
4364 break;
4365 case RESUMING:
4366 stateChar = 'R';
4367 break;
4368 case ACTIVE:
4369 stateChar = 'A';
4370 break;
4371 case PAUSING:
4372 stateChar = 'p';
4373 break;
4374 case PAUSED:
4375 stateChar = 'P';
4376 break;
Eric Laurent29864602012-05-08 18:57:51 -07004377 case FLUSHED:
4378 stateChar = 'F';
4379 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004380 default:
4381 stateChar = '?';
4382 break;
4383 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004384 char nowInUnderrun;
4385 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4386 case UNDERRUN_FULL:
4387 nowInUnderrun = ' ';
4388 break;
4389 case UNDERRUN_PARTIAL:
4390 nowInUnderrun = '<';
4391 break;
4392 case UNDERRUN_EMPTY:
4393 nowInUnderrun = '*';
4394 break;
4395 default:
4396 nowInUnderrun = '?';
4397 break;
4398 }
Glenn Kastene213c862012-04-25 13:46:15 -07004399 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4400 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004401 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004402 mStreamType,
4403 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004404 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004405 mSessionId,
4406 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004407 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004408 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004409 mMute,
4410 mFillingUpStatus,
4411 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004412 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4413 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004414 mCblk->server,
4415 mCblk->user,
4416 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004417 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004418 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004419 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004420 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004421}
4422
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004423// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004424status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004425 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004426{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004427 audio_track_cblk_t* cblk = this->cblk();
4428 uint32_t framesReady;
4429 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004430
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004431 // Check if last stepServer failed, try to step now
4432 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004433 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4434 // Since the fast mixer is higher priority than client callback thread,
4435 // it does not result in priority inversion for client.
4436 // But a non-blocking solution would be preferable to avoid
4437 // fast mixer being unable to tryLock(), and
4438 // to avoid the extra context switches if the client wakes up,
4439 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004440 if (!step()) goto getNextBuffer_exit;
4441 ALOGV("stepServer recovered");
4442 mStepServerFailed = false;
4443 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004444
Glenn Kasten288ed212012-04-25 17:52:27 -07004445 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004446 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004447
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004448 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004449 uint32_t s = cblk->server;
4450 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4451
4452 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4453 if (framesReq > framesReady) {
4454 framesReq = framesReady;
4455 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004456 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004457 framesReq = bufferEnd - s;
4458 }
4459
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004460 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004461 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004462 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004463 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004464
4465getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004466 buffer->raw = NULL;
4467 buffer->frameCount = 0;
4468 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4469 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004470}
4471
Glenn Kasten288ed212012-04-25 17:52:27 -07004472// Note that framesReady() takes a mutex on the control block using tryLock().
4473// This could result in priority inversion if framesReady() is called by the normal mixer,
4474// as the normal mixer thread runs at lower
4475// priority than the client's callback thread: there is a short window within framesReady()
4476// during which the normal mixer could be preempted, and the client callback would block.
4477// Another problem can occur if framesReady() is called by the fast mixer:
4478// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4479// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4480size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004481 return mCblk->framesReady();
4482}
4483
Glenn Kasten288ed212012-04-25 17:52:27 -07004484// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004485bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004486 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004487
John Grossman4ff14ba2012-02-08 16:37:41 -08004488 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004489 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4490 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004491 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004492 return true;
4493 }
4494 return false;
4495}
4496
Glenn Kasten3acbd052012-02-28 10:39:56 -08004497status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004498 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004499{
4500 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004501 ALOGV("start(%d), calling pid %d session %d",
4502 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004503
Mathias Agopian65ab4712010-07-14 17:59:35 -07004504 sp<ThreadBase> thread = mThread.promote();
4505 if (thread != 0) {
4506 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004507 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004508 // here the track could be either new, or restarted
4509 // in both cases "unstop" the track
4510 if (mState == PAUSED) {
4511 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004512 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004513 } else {
4514 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004515 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004516 }
4517
4518 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4519 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004520 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004521 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004522
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004523#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004524 // to track the speaker usage
4525 if (status == NO_ERROR) {
4526 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4527 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004528#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004529 }
4530 if (status == NO_ERROR) {
4531 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4532 playbackThread->addTrack_l(this);
4533 } else {
4534 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004535 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004536 }
4537 } else {
4538 status = BAD_VALUE;
4539 }
4540 return status;
4541}
4542
4543void AudioFlinger::PlaybackThread::Track::stop()
4544{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004545 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004546 sp<ThreadBase> thread = mThread.promote();
4547 if (thread != 0) {
4548 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004549 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004550 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004551 // If the track is not active (PAUSED and buffers full), flush buffers
4552 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4553 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4554 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004555 mState = STOPPED;
4556 } else if (!isFastTrack()) {
4557 mState = STOPPED;
4558 } else {
4559 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4560 // and then to STOPPED and reset() when presentation is complete
4561 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004562 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004563 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004564 }
4565 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4566 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004567 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004568 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004569
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004570#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004571 // to track the speaker usage
4572 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004573#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004574 }
4575 }
4576}
4577
4578void AudioFlinger::PlaybackThread::Track::pause()
4579{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004580 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004581 sp<ThreadBase> thread = mThread.promote();
4582 if (thread != 0) {
4583 Mutex::Autolock _l(thread->mLock);
4584 if (mState == ACTIVE || mState == RESUMING) {
4585 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004586 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004587 if (!isOutputTrack()) {
4588 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004589 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004590 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004591
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004592#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004593 // to track the speaker usage
4594 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004595#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004596 }
4597 }
4598 }
4599}
4600
4601void AudioFlinger::PlaybackThread::Track::flush()
4602{
Steve Block3856b092011-10-20 11:56:00 +01004603 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004604 sp<ThreadBase> thread = mThread.promote();
4605 if (thread != 0) {
4606 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004607 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4608 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004609 return;
4610 }
4611 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004612 // FLUSHED state
4613 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004614 // do not reset the track if it is still in the process of being stopped or paused.
4615 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004616 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004617 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004618 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4619 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4620 reset();
4621 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004622 }
4623}
4624
4625void AudioFlinger::PlaybackThread::Track::reset()
4626{
4627 // Do not reset twice to avoid discarding data written just after a flush and before
4628 // the audioflinger thread detects the track is stopped.
4629 if (!mResetDone) {
4630 TrackBase::reset();
4631 // Force underrun condition to avoid false underrun callback until first data is
4632 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004633 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4634 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004635 mFillingUpStatus = FS_FILLING;
4636 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004637 if (mState == FLUSHED) {
4638 mState = IDLE;
4639 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004640 }
4641}
4642
4643void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4644{
4645 mMute = muted;
4646}
4647
Mathias Agopian65ab4712010-07-14 17:59:35 -07004648status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4649{
4650 status_t status = DEAD_OBJECT;
4651 sp<ThreadBase> thread = mThread.promote();
4652 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004653 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004654 sp<AudioFlinger> af = mClient->audioFlinger();
4655
4656 Mutex::Autolock _l(af->mLock);
4657
4658 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004659
Eric Laurent109347d2012-07-02 12:31:03 -07004660 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004661 Mutex::Autolock _dl(playbackThread->mLock);
4662 Mutex::Autolock _sl(srcThread->mLock);
4663 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4664 if (chain == 0) {
4665 return INVALID_OPERATION;
4666 }
4667
4668 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4669 if (effect == 0) {
4670 return INVALID_OPERATION;
4671 }
4672 srcThread->removeEffect_l(effect);
4673 playbackThread->addEffect_l(effect);
4674 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4675 if (effect->state() == EffectModule::ACTIVE ||
4676 effect->state() == EffectModule::STOPPING) {
4677 effect->start();
4678 }
4679
4680 sp<EffectChain> dstChain = effect->chain().promote();
4681 if (dstChain == 0) {
4682 srcThread->addEffect_l(effect);
4683 return INVALID_OPERATION;
4684 }
4685 AudioSystem::unregisterEffect(effect->id());
4686 AudioSystem::registerEffect(&effect->desc(),
4687 srcThread->id(),
4688 dstChain->strategy(),
4689 AUDIO_SESSION_OUTPUT_MIX,
4690 effect->id());
4691 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004692 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004693 }
4694 return status;
4695}
4696
4697void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4698{
4699 mAuxEffectId = EffectId;
4700 mAuxBuffer = buffer;
4701}
4702
Eric Laurenta011e352012-03-29 15:51:43 -07004703bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4704 size_t audioHalFrames)
4705{
4706 // a track is considered presented when the total number of frames written to audio HAL
4707 // corresponds to the number of frames written when presentationComplete() is called for the
4708 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4709 if (mPresentationCompleteFrames == 0) {
4710 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4711 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4712 mPresentationCompleteFrames, audioHalFrames);
4713 }
4714 if (framesWritten >= mPresentationCompleteFrames) {
4715 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4716 mSessionId, framesWritten);
4717 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004718 return true;
4719 }
4720 return false;
4721}
4722
4723void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4724{
4725 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4726 if (mSyncEvents[i]->type() == type) {
4727 mSyncEvents[i]->trigger();
4728 mSyncEvents.removeAt(i);
4729 i--;
4730 }
4731 }
4732}
4733
Glenn Kasten58912562012-04-03 10:45:00 -07004734// implement VolumeBufferProvider interface
4735
4736uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4737{
4738 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4739 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4740 uint32_t vlr = mCblk->getVolumeLR();
4741 uint32_t vl = vlr & 0xFFFF;
4742 uint32_t vr = vlr >> 16;
4743 // track volumes come from shared memory, so can't be trusted and must be clamped
4744 if (vl > MAX_GAIN_INT) {
4745 vl = MAX_GAIN_INT;
4746 }
4747 if (vr > MAX_GAIN_INT) {
4748 vr = MAX_GAIN_INT;
4749 }
4750 // now apply the cached master volume and stream type volume;
4751 // this is trusted but lacks any synchronization or barrier so may be stale
4752 float v = mCachedVolume;
4753 vl *= v;
4754 vr *= v;
4755 // re-combine into U4.16
4756 vlr = (vr << 16) | (vl & 0xFFFF);
4757 // FIXME look at mute, pause, and stop flags
4758 return vlr;
4759}
Eric Laurenta011e352012-03-29 15:51:43 -07004760
Eric Laurent29864602012-05-08 18:57:51 -07004761status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4762{
4763 if (mState == TERMINATED || mState == PAUSED ||
4764 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4765 (mState == STOPPED)))) {
4766 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4767 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4768 event->cancel();
4769 return INVALID_OPERATION;
4770 }
4771 TrackBase::setSyncEvent(event);
4772 return NO_ERROR;
4773}
4774
John Grossman4ff14ba2012-02-08 16:37:41 -08004775// timed audio tracks
4776
4777sp<AudioFlinger::PlaybackThread::TimedTrack>
4778AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004779 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004780 const sp<Client>& client,
4781 audio_stream_type_t streamType,
4782 uint32_t sampleRate,
4783 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004784 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004785 int frameCount,
4786 const sp<IMemory>& sharedBuffer,
4787 int sessionId) {
4788 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004789 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004790
Glenn Kastena0356762012-03-19 10:38:51 -07004791 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004792 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4793 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004794}
4795
4796AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004797 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004798 const sp<Client>& client,
4799 audio_stream_type_t streamType,
4800 uint32_t sampleRate,
4801 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004802 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004803 int frameCount,
4804 const sp<IMemory>& sharedBuffer,
4805 int sessionId)
4806 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004807 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004808 mQueueHeadInFlight(false),
4809 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004810 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004811 mTimedSilenceBuffer(NULL),
4812 mTimedSilenceBufferSize(0),
4813 mTimedAudioOutputOnTime(false),
4814 mMediaTimeTransformValid(false)
4815{
4816 LocalClock lc;
4817 mLocalTimeFreq = lc.getLocalFreq();
4818
4819 mLocalTimeToSampleTransform.a_zero = 0;
4820 mLocalTimeToSampleTransform.b_zero = 0;
4821 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4822 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4823 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4824 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004825
4826 mMediaTimeToSampleTransform.a_zero = 0;
4827 mMediaTimeToSampleTransform.b_zero = 0;
4828 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4829 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4830 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4831 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004832}
4833
4834AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4835 mClient->releaseTimedTrack();
4836 delete [] mTimedSilenceBuffer;
4837}
4838
4839status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4840 size_t size, sp<IMemory>* buffer) {
4841
4842 Mutex::Autolock _l(mTimedBufferQueueLock);
4843
4844 trimTimedBufferQueue_l();
4845
4846 // lazily initialize the shared memory heap for timed buffers
4847 if (mTimedMemoryDealer == NULL) {
4848 const int kTimedBufferHeapSize = 512 << 10;
4849
4850 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4851 "AudioFlingerTimed");
4852 if (mTimedMemoryDealer == NULL)
4853 return NO_MEMORY;
4854 }
4855
4856 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4857 if (newBuffer == NULL) {
4858 newBuffer = mTimedMemoryDealer->allocate(size);
4859 if (newBuffer == NULL)
4860 return NO_MEMORY;
4861 }
4862
4863 *buffer = newBuffer;
4864 return NO_ERROR;
4865}
4866
4867// caller must hold mTimedBufferQueueLock
4868void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4869 int64_t mediaTimeNow;
4870 {
4871 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4872 if (!mMediaTimeTransformValid)
4873 return;
4874
4875 int64_t targetTimeNow;
4876 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4877 ? mCCHelper.getCommonTime(&targetTimeNow)
4878 : mCCHelper.getLocalTime(&targetTimeNow);
4879
4880 if (OK != res)
4881 return;
4882
4883 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4884 &mediaTimeNow)) {
4885 return;
4886 }
4887 }
4888
John Grossman1c345192012-03-27 14:00:17 -07004889 size_t trimEnd;
4890 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004891 int64_t bufEnd;
4892
John Grossmanc95cfbb2012-04-12 11:53:11 -07004893 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4894 // We have a next buffer. Just use its PTS as the PTS of the frame
4895 // following the last frame in this buffer. If the stream is sparse
4896 // (ie, there are deliberate gaps left in the stream which should be
4897 // filled with silence by the TimedAudioTrack), then this can result
4898 // in one extra buffer being left un-trimmed when it could have
4899 // been. In general, this is not typical, and we would rather
4900 // optimized away the TS calculation below for the more common case
4901 // where PTSes are contiguous.
4902 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4903 } else {
4904 // We have no next buffer. Compute the PTS of the frame following
4905 // the last frame in this buffer by computing the duration of of
4906 // this frame in media time units and adding it to the PTS of the
4907 // buffer.
4908 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4909 / mCblk->frameSize;
4910
4911 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4912 &bufEnd)) {
4913 ALOGE("Failed to convert frame count of %lld to media time"
4914 " duration" " (scale factor %d/%u) in %s",
4915 frameCount,
4916 mMediaTimeToSampleTransform.a_to_b_numer,
4917 mMediaTimeToSampleTransform.a_to_b_denom,
4918 __PRETTY_FUNCTION__);
4919 break;
4920 }
4921 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004922 }
John Grossman9fbdee12012-03-26 17:51:46 -07004923
4924 if (bufEnd > mediaTimeNow)
4925 break;
4926
4927 // Is the buffer we want to use in the middle of a mix operation right
4928 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4929 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004930 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004931 mTrimQueueHeadOnRelease = true;
4932 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004933 }
4934
John Grossman9fbdee12012-03-26 17:51:46 -07004935 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004936 if (trimStart < trimEnd) {
4937 // Update the bookkeeping for framesReady()
4938 for (size_t i = trimStart; i < trimEnd; ++i) {
4939 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4940 }
4941
4942 // Now actually remove the buffers from the queue.
4943 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004944 }
4945}
4946
John Grossman1c345192012-03-27 14:00:17 -07004947void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4948 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004949 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4950 "%s called (reason \"%s\"), but timed buffer queue has no"
4951 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004952
4953 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4954 mTimedBufferQueue.removeAt(0);
4955}
4956
4957void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4958 const TimedBuffer& buf,
4959 const char* logTag) {
4960 uint32_t bufBytes = buf.buffer()->size();
4961 uint32_t consumedAlready = buf.position();
4962
Eric Laurentb388e532012-04-14 13:32:48 -07004963 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004964 "Bad bookkeeping while updating frames pending. Timed buffer is"
4965 " only %u bytes long, but claims to have consumed %u"
4966 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004967 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004968
4969 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004970 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4971 "Bad bookkeeping while updating frames pending. Should have at"
4972 " least %u queued frames, but we think we have only %u. (update"
4973 " reason: \"%s\")",
4974 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004975
4976 mFramesPendingInQueue -= bufFrames;
4977}
4978
John Grossman4ff14ba2012-02-08 16:37:41 -08004979status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4980 const sp<IMemory>& buffer, int64_t pts) {
4981
4982 {
4983 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4984 if (!mMediaTimeTransformValid)
4985 return INVALID_OPERATION;
4986 }
4987
4988 Mutex::Autolock _l(mTimedBufferQueueLock);
4989
John Grossman1c345192012-03-27 14:00:17 -07004990 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4991 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004992 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4993
4994 return NO_ERROR;
4995}
4996
4997status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4998 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4999
John Grossman1c345192012-03-27 14:00:17 -07005000 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5001 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5002 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005003
5004 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5005 target == TimedAudioTrack::COMMON_TIME)) {
5006 return BAD_VALUE;
5007 }
5008
5009 Mutex::Autolock lock(mMediaTimeTransformLock);
5010 mMediaTimeTransform = xform;
5011 mMediaTimeTransformTarget = target;
5012 mMediaTimeTransformValid = true;
5013
5014 return NO_ERROR;
5015}
5016
5017#define min(a, b) ((a) < (b) ? (a) : (b))
5018
5019// implementation of getNextBuffer for tracks whose buffers have timestamps
5020status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5021 AudioBufferProvider::Buffer* buffer, int64_t pts)
5022{
5023 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005024 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005025 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005026 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005027 return INVALID_OPERATION;
5028 }
5029
John Grossman4ff14ba2012-02-08 16:37:41 -08005030 Mutex::Autolock _l(mTimedBufferQueueLock);
5031
John Grossman9fbdee12012-03-26 17:51:46 -07005032 ALOG_ASSERT(!mQueueHeadInFlight,
5033 "getNextBuffer called without releaseBuffer!");
5034
John Grossman4ff14ba2012-02-08 16:37:41 -08005035 while (true) {
5036
5037 // if we have no timed buffers, then fail
5038 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005039 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005040 buffer->frameCount = 0;
5041 return NOT_ENOUGH_DATA;
5042 }
5043
5044 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5045
5046 // calculate the PTS of the head of the timed buffer queue expressed in
5047 // local time
5048 int64_t headLocalPTS;
5049 {
5050 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5051
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005052 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005053
5054 if (mMediaTimeTransform.a_to_b_denom == 0) {
5055 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005056 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005057 return NO_ERROR;
5058 }
5059
5060 int64_t transformedPTS;
5061 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5062 &transformedPTS)) {
5063 // the transform failed. this shouldn't happen, but if it does
5064 // then just drop this buffer
5065 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005066 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005067 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005068 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005069 return NO_ERROR;
5070 }
5071
5072 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5073 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5074 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005075 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005076 buffer->frameCount = 0;
5077 return INVALID_OPERATION;
5078 }
5079 } else {
5080 headLocalPTS = transformedPTS;
5081 }
5082 }
5083
5084 // adjust the head buffer's PTS to reflect the portion of the head buffer
5085 // that has already been consumed
5086 int64_t effectivePTS = headLocalPTS +
5087 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5088
5089 // Calculate the delta in samples between the head of the input buffer
5090 // queue and the start of the next output buffer that will be written.
5091 // If the transformation fails because of over or underflow, it means
5092 // that the sample's position in the output stream is so far out of
5093 // whack that it should just be dropped.
5094 int64_t sampleDelta;
5095 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5096 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005097 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5098 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005099 continue;
5100 }
5101 if (!mLocalTimeToSampleTransform.doForwardTransform(
5102 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005103 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005104 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005105 continue;
5106 }
5107
John Grossman1c345192012-03-27 14:00:17 -07005108 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5109 " sampleDelta=[%d.%08x]",
5110 head.pts(), head.position(), pts,
5111 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5112 + (sampleDelta >> 32)),
5113 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005114
5115 // if the delta between the ideal placement for the next input sample and
5116 // the current output position is within this threshold, then we will
5117 // concatenate the next input samples to the previous output
5118 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005119 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005120
5121 // if this is the first buffer of audio that we're emitting from this track
5122 // then it should be almost exactly on time.
5123 const int64_t kSampleStartupThreshold = 1LL << 32;
5124
5125 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005126 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005127 // the next input is close enough to being on time, so concatenate it
5128 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005129 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005130
John Grossman1c345192012-03-27 14:00:17 -07005131 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5132 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005133 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005134 }
5135
5136 // Looks like our output is not on time. Reset our on timed status.
5137 // Next time we mix samples from our input queue, then should be within
5138 // the StartupThreshold.
5139 mTimedAudioOutputOnTime = false;
5140 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005141 // the gap between the current output position and the proper start of
5142 // the next input sample is too big, so fill it with silence
5143 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5144
John Grossman9fbdee12012-03-26 17:51:46 -07005145 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005146 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5147 return NO_ERROR;
5148 } else {
5149 // the next input sample is late
5150 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5151 size_t onTimeSamplePosition =
5152 head.position() + lateFrames * mCblk->frameSize;
5153
5154 if (onTimeSamplePosition > head.buffer()->size()) {
5155 // all the remaining samples in the head are too late, so
5156 // drop it and move on
5157 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005158 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005159 continue;
5160 } else {
5161 // skip over the late samples
5162 head.setPosition(onTimeSamplePosition);
5163
5164 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005165 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005166
5167 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5168 return NO_ERROR;
5169 }
5170 }
5171 }
5172}
5173
5174// Yield samples from the timed buffer queue head up to the given output
5175// buffer's capacity.
5176//
5177// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005178void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005179 AudioBufferProvider::Buffer* buffer) {
5180
5181 const TimedBuffer& head = mTimedBufferQueue[0];
5182
5183 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5184 head.position());
5185
5186 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5187 mCblk->frameSize);
5188 size_t framesRequested = buffer->frameCount;
5189 buffer->frameCount = min(framesLeftInHead, framesRequested);
5190
John Grossman9fbdee12012-03-26 17:51:46 -07005191 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005192 mTimedAudioOutputOnTime = true;
5193}
5194
5195// Yield samples of silence up to the given output buffer's capacity
5196//
5197// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005198void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005199 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5200
5201 // lazily allocate a buffer filled with silence
5202 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5203 delete [] mTimedSilenceBuffer;
5204 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5205 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5206 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5207 }
5208
5209 buffer->raw = mTimedSilenceBuffer;
5210 size_t framesRequested = buffer->frameCount;
5211 buffer->frameCount = min(numFrames, framesRequested);
5212
5213 mTimedAudioOutputOnTime = false;
5214}
5215
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005216// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005217void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5218 AudioBufferProvider::Buffer* buffer) {
5219
5220 Mutex::Autolock _l(mTimedBufferQueueLock);
5221
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005222 // If the buffer which was just released is part of the buffer at the head
5223 // of the queue, be sure to update the amt of the buffer which has been
5224 // consumed. If the buffer being returned is not part of the head of the
5225 // queue, its either because the buffer is part of the silence buffer, or
5226 // because the head of the timed queue was trimmed after the mixer called
5227 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005228 if (buffer->raw == mTimedSilenceBuffer) {
5229 ALOG_ASSERT(!mQueueHeadInFlight,
5230 "Queue head in flight during release of silence buffer!");
5231 goto done;
5232 }
5233
5234 ALOG_ASSERT(mQueueHeadInFlight,
5235 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5236 " head in flight.");
5237
5238 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005239 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005240
5241 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005242 void* end = reinterpret_cast<void*>(
5243 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5244 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005245
John Grossman9fbdee12012-03-26 17:51:46 -07005246 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5247 "released buffer not within the head of the timed buffer"
5248 " queue; qHead = [%p, %p], released buffer = %p",
5249 start, end, buffer->raw);
5250
5251 head.setPosition(head.position() +
5252 (buffer->frameCount * mCblk->frameSize));
5253 mQueueHeadInFlight = false;
5254
John Grossman1c345192012-03-27 14:00:17 -07005255 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5256 "Bad bookkeeping during releaseBuffer! Should have at"
5257 " least %u queued frames, but we think we have only %u",
5258 buffer->frameCount, mFramesPendingInQueue);
5259
5260 mFramesPendingInQueue -= buffer->frameCount;
5261
John Grossman9fbdee12012-03-26 17:51:46 -07005262 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5263 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005264 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005265 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005266 }
John Grossman9fbdee12012-03-26 17:51:46 -07005267 } else {
5268 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5269 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005270 }
5271
John Grossman9fbdee12012-03-26 17:51:46 -07005272done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005273 buffer->raw = 0;
5274 buffer->frameCount = 0;
5275}
5276
Glenn Kasten288ed212012-04-25 17:52:27 -07005277size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005278 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005279 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005280}
5281
5282AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5283 : mPTS(0), mPosition(0) {}
5284
5285AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5286 const sp<IMemory>& buffer, int64_t pts)
5287 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5288
Mathias Agopian65ab4712010-07-14 17:59:35 -07005289// ----------------------------------------------------------------------------
5290
5291// RecordTrack constructor must be called with AudioFlinger::mLock held
5292AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005293 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005294 const sp<Client>& client,
5295 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005296 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005297 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005298 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005299 int sessionId)
5300 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005301 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005302 mOverflow(false)
5303{
5304 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005305 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5306 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5307 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5308 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5309 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5310 } else {
5311 mCblk->frameSize = sizeof(int8_t);
5312 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005313 }
5314}
5315
5316AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5317{
5318 sp<ThreadBase> thread = mThread.promote();
5319 if (thread != 0) {
5320 AudioSystem::releaseInput(thread->id());
5321 }
5322}
5323
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005324// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005325status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005326{
5327 audio_track_cblk_t* cblk = this->cblk();
5328 uint32_t framesAvail;
5329 uint32_t framesReq = buffer->frameCount;
5330
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005331 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005332 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005333 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005334 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005335 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005336 }
5337
5338 framesAvail = cblk->framesAvailable_l();
5339
Glenn Kastenf6b16782011-12-15 09:51:17 -08005340 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005341 uint32_t s = cblk->server;
5342 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5343
5344 if (framesReq > framesAvail) {
5345 framesReq = framesAvail;
5346 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005347 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005348 framesReq = bufferEnd - s;
5349 }
5350
5351 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005352 buffer->frameCount = framesReq;
5353 return NO_ERROR;
5354 }
5355
5356getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005357 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005358 buffer->frameCount = 0;
5359 return NOT_ENOUGH_DATA;
5360}
5361
Glenn Kasten3acbd052012-02-28 10:39:56 -08005362status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005363 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005364{
5365 sp<ThreadBase> thread = mThread.promote();
5366 if (thread != 0) {
5367 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005368 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005369 } else {
5370 return BAD_VALUE;
5371 }
5372}
5373
5374void AudioFlinger::RecordThread::RecordTrack::stop()
5375{
5376 sp<ThreadBase> thread = mThread.promote();
5377 if (thread != 0) {
5378 RecordThread *recordThread = (RecordThread *)thread.get();
5379 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005380 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005381 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005382 // read from buffer
5383 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005384 }
5385}
5386
5387void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5388{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005389 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005390 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005391 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005392 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005393 mSessionId,
5394 mFrameCount,
5395 mState,
5396 mCblk->sampleRate,
5397 mCblk->server,
5398 mCblk->user);
5399}
5400
5401
5402// ----------------------------------------------------------------------------
5403
5404AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005405 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005406 DuplicatingThread *sourceThread,
5407 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005408 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005409 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005410 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005411 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5412 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005413 mActive(false), mSourceThread(sourceThread)
5414{
5415
Mathias Agopian65ab4712010-07-14 17:59:35 -07005416 if (mCblk != NULL) {
5417 mCblk->flags |= CBLK_DIRECTION_OUT;
5418 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005419 mOutBuffer.frameCount = 0;
5420 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005421 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005422 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5423 mCblk, mBuffer, mCblk->buffers,
5424 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005425 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005426 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005427 }
5428}
5429
5430AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5431{
5432 clearBufferQueue();
5433}
5434
Glenn Kasten3acbd052012-02-28 10:39:56 -08005435status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005436 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005437{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005438 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005439 if (status != NO_ERROR) {
5440 return status;
5441 }
5442
5443 mActive = true;
5444 mRetryCount = 127;
5445 return status;
5446}
5447
5448void AudioFlinger::PlaybackThread::OutputTrack::stop()
5449{
5450 Track::stop();
5451 clearBufferQueue();
5452 mOutBuffer.frameCount = 0;
5453 mActive = false;
5454}
5455
5456bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5457{
5458 Buffer *pInBuffer;
5459 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005460 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005461 bool outputBufferFull = false;
5462 inBuffer.frameCount = frames;
5463 inBuffer.i16 = data;
5464
5465 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5466
5467 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005468 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005469 sp<ThreadBase> thread = mThread.promote();
5470 if (thread != 0) {
5471 MixerThread *mixerThread = (MixerThread *)thread.get();
5472 if (mCblk->frameCount > frames){
5473 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5474 uint32_t startFrames = (mCblk->frameCount - frames);
5475 pInBuffer = new Buffer;
5476 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5477 pInBuffer->frameCount = startFrames;
5478 pInBuffer->i16 = pInBuffer->mBuffer;
5479 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5480 mBufferQueue.add(pInBuffer);
5481 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005482 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005483 }
5484 }
5485 }
5486 }
5487
5488 while (waitTimeLeftMs) {
5489 // First write pending buffers, then new data
5490 if (mBufferQueue.size()) {
5491 pInBuffer = mBufferQueue.itemAt(0);
5492 } else {
5493 pInBuffer = &inBuffer;
5494 }
5495
5496 if (pInBuffer->frameCount == 0) {
5497 break;
5498 }
5499
5500 if (mOutBuffer.frameCount == 0) {
5501 mOutBuffer.frameCount = pInBuffer->frameCount;
5502 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005503 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005504 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005505 outputBufferFull = true;
5506 break;
5507 }
5508 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5509 if (waitTimeLeftMs >= waitTimeMs) {
5510 waitTimeLeftMs -= waitTimeMs;
5511 } else {
5512 waitTimeLeftMs = 0;
5513 }
5514 }
5515
5516 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5517 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5518 mCblk->stepUser(outFrames);
5519 pInBuffer->frameCount -= outFrames;
5520 pInBuffer->i16 += outFrames * channelCount;
5521 mOutBuffer.frameCount -= outFrames;
5522 mOutBuffer.i16 += outFrames * channelCount;
5523
5524 if (pInBuffer->frameCount == 0) {
5525 if (mBufferQueue.size()) {
5526 mBufferQueue.removeAt(0);
5527 delete [] pInBuffer->mBuffer;
5528 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005529 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005530 } else {
5531 break;
5532 }
5533 }
5534 }
5535
5536 // If we could not write all frames, allocate a buffer and queue it for next time.
5537 if (inBuffer.frameCount) {
5538 sp<ThreadBase> thread = mThread.promote();
5539 if (thread != 0 && !thread->standby()) {
5540 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5541 pInBuffer = new Buffer;
5542 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5543 pInBuffer->frameCount = inBuffer.frameCount;
5544 pInBuffer->i16 = pInBuffer->mBuffer;
5545 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5546 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005547 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005548 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005549 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005550 }
5551 }
5552 }
5553
5554 // Calling write() with a 0 length buffer, means that no more data will be written:
5555 // If no more buffers are pending, fill output track buffer to make sure it is started
5556 // by output mixer.
5557 if (frames == 0 && mBufferQueue.size() == 0) {
5558 if (mCblk->user < mCblk->frameCount) {
5559 frames = mCblk->frameCount - mCblk->user;
5560 pInBuffer = new Buffer;
5561 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5562 pInBuffer->frameCount = frames;
5563 pInBuffer->i16 = pInBuffer->mBuffer;
5564 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5565 mBufferQueue.add(pInBuffer);
5566 } else if (mActive) {
5567 stop();
5568 }
5569 }
5570
5571 return outputBufferFull;
5572}
5573
5574status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5575{
5576 int active;
5577 status_t result;
5578 audio_track_cblk_t* cblk = mCblk;
5579 uint32_t framesReq = buffer->frameCount;
5580
Steve Block3856b092011-10-20 11:56:00 +01005581// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005582 buffer->frameCount = 0;
5583
5584 uint32_t framesAvail = cblk->framesAvailable();
5585
5586
5587 if (framesAvail == 0) {
5588 Mutex::Autolock _l(cblk->lock);
5589 goto start_loop_here;
5590 while (framesAvail == 0) {
5591 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005592 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005593 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005594 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005595 }
5596 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5597 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005598 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005599 }
5600 // read the server count again
5601 start_loop_here:
5602 framesAvail = cblk->framesAvailable_l();
5603 }
5604 }
5605
5606// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005607// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005608// }
5609
5610 if (framesReq > framesAvail) {
5611 framesReq = framesAvail;
5612 }
5613
5614 uint32_t u = cblk->user;
5615 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5616
Marco Nelissena1472d92012-03-30 14:36:54 -07005617 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005618 framesReq = bufferEnd - u;
5619 }
5620
5621 buffer->frameCount = framesReq;
5622 buffer->raw = (void *)cblk->buffer(u);
5623 return NO_ERROR;
5624}
5625
5626
5627void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5628{
5629 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005630
5631 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005632 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005633 delete [] pBuffer->mBuffer;
5634 delete pBuffer;
5635 }
5636 mBufferQueue.clear();
5637}
5638
5639// ----------------------------------------------------------------------------
5640
5641AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5642 : RefBase(),
5643 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005644 // 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 -07005645 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005646 mPid(pid),
5647 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005648{
5649 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5650}
5651
5652// Client destructor must be called with AudioFlinger::mLock held
5653AudioFlinger::Client::~Client()
5654{
5655 mAudioFlinger->removeClient_l(mPid);
5656}
5657
Glenn Kasten435dbe62012-01-30 10:15:48 -08005658sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005659{
5660 return mMemoryDealer;
5661}
5662
John Grossman4ff14ba2012-02-08 16:37:41 -08005663// Reserve one of the limited slots for a timed audio track associated
5664// with this client
5665bool AudioFlinger::Client::reserveTimedTrack()
5666{
5667 const int kMaxTimedTracksPerClient = 4;
5668
5669 Mutex::Autolock _l(mTimedTrackLock);
5670
5671 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5672 ALOGW("can not create timed track - pid %d has exceeded the limit",
5673 mPid);
5674 return false;
5675 }
5676
5677 mTimedTrackCount++;
5678 return true;
5679}
5680
5681// Release a slot for a timed audio track
5682void AudioFlinger::Client::releaseTimedTrack()
5683{
5684 Mutex::Autolock _l(mTimedTrackLock);
5685 mTimedTrackCount--;
5686}
5687
Mathias Agopian65ab4712010-07-14 17:59:35 -07005688// ----------------------------------------------------------------------------
5689
5690AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5691 const sp<IAudioFlingerClient>& client,
5692 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005693 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005694{
5695}
5696
5697AudioFlinger::NotificationClient::~NotificationClient()
5698{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005699}
5700
5701void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5702{
5703 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005704 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005705}
5706
5707// ----------------------------------------------------------------------------
5708
5709AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5710 : BnAudioTrack(),
5711 mTrack(track)
5712{
5713}
5714
5715AudioFlinger::TrackHandle::~TrackHandle() {
5716 // just stop the track on deletion, associated resources
5717 // will be freed from the main thread once all pending buffers have
5718 // been played. Unless it's not in the active track list, in which
5719 // case we free everything now...
5720 mTrack->destroy();
5721}
5722
Glenn Kasten90716c52012-01-26 13:40:12 -08005723sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5724 return mTrack->getCblk();
5725}
5726
Glenn Kasten3acbd052012-02-28 10:39:56 -08005727status_t AudioFlinger::TrackHandle::start() {
5728 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005729}
5730
5731void AudioFlinger::TrackHandle::stop() {
5732 mTrack->stop();
5733}
5734
5735void AudioFlinger::TrackHandle::flush() {
5736 mTrack->flush();
5737}
5738
5739void AudioFlinger::TrackHandle::mute(bool e) {
5740 mTrack->mute(e);
5741}
5742
5743void AudioFlinger::TrackHandle::pause() {
5744 mTrack->pause();
5745}
5746
Mathias Agopian65ab4712010-07-14 17:59:35 -07005747status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5748{
5749 return mTrack->attachAuxEffect(EffectId);
5750}
5751
John Grossman4ff14ba2012-02-08 16:37:41 -08005752status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5753 sp<IMemory>* buffer) {
5754 if (!mTrack->isTimedTrack())
5755 return INVALID_OPERATION;
5756
5757 PlaybackThread::TimedTrack* tt =
5758 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5759 return tt->allocateTimedBuffer(size, buffer);
5760}
5761
5762status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5763 int64_t pts) {
5764 if (!mTrack->isTimedTrack())
5765 return INVALID_OPERATION;
5766
5767 PlaybackThread::TimedTrack* tt =
5768 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5769 return tt->queueTimedBuffer(buffer, pts);
5770}
5771
5772status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5773 const LinearTransform& xform, int target) {
5774
5775 if (!mTrack->isTimedTrack())
5776 return INVALID_OPERATION;
5777
5778 PlaybackThread::TimedTrack* tt =
5779 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5780 return tt->setMediaTimeTransform(
5781 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5782}
5783
Mathias Agopian65ab4712010-07-14 17:59:35 -07005784status_t AudioFlinger::TrackHandle::onTransact(
5785 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5786{
5787 return BnAudioTrack::onTransact(code, data, reply, flags);
5788}
5789
5790// ----------------------------------------------------------------------------
5791
5792sp<IAudioRecord> AudioFlinger::openRecord(
5793 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005794 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005795 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005796 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005797 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005798 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005799 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005800 int *sessionId,
5801 status_t *status)
5802{
5803 sp<RecordThread::RecordTrack> recordTrack;
5804 sp<RecordHandle> recordHandle;
5805 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005806 status_t lStatus;
5807 RecordThread *thread;
5808 size_t inFrameCount;
5809 int lSessionId;
5810
5811 // check calling permissions
5812 if (!recordingAllowed()) {
5813 lStatus = PERMISSION_DENIED;
5814 goto Exit;
5815 }
5816
5817 // add client to list
5818 { // scope for mLock
5819 Mutex::Autolock _l(mLock);
5820 thread = checkRecordThread_l(input);
5821 if (thread == NULL) {
5822 lStatus = BAD_VALUE;
5823 goto Exit;
5824 }
5825
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005826 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005827
5828 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005829 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005830 lSessionId = *sessionId;
5831 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005832 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005833 if (sessionId != NULL) {
5834 *sessionId = lSessionId;
5835 }
5836 }
5837 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005838 recordTrack = thread->createRecordTrack_l(client,
5839 sampleRate,
5840 format,
5841 channelMask,
5842 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005843 lSessionId,
5844 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005845 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005846 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005847 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5848 // destructor is called by the TrackBase destructor with mLock held
5849 client.clear();
5850 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005851 goto Exit;
5852 }
5853
5854 // return to handle to client
5855 recordHandle = new RecordHandle(recordTrack);
5856 lStatus = NO_ERROR;
5857
5858Exit:
5859 if (status) {
5860 *status = lStatus;
5861 }
5862 return recordHandle;
5863}
5864
5865// ----------------------------------------------------------------------------
5866
5867AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5868 : BnAudioRecord(),
5869 mRecordTrack(recordTrack)
5870{
5871}
5872
5873AudioFlinger::RecordHandle::~RecordHandle() {
5874 stop();
5875}
5876
Glenn Kasten90716c52012-01-26 13:40:12 -08005877sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5878 return mRecordTrack->getCblk();
5879}
5880
Glenn Kasten3acbd052012-02-28 10:39:56 -08005881status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005882 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005883 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005884}
5885
5886void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005887 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005888 mRecordTrack->stop();
5889}
5890
Mathias Agopian65ab4712010-07-14 17:59:35 -07005891status_t AudioFlinger::RecordHandle::onTransact(
5892 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5893{
5894 return BnAudioRecord::onTransact(code, data, reply, flags);
5895}
5896
5897// ----------------------------------------------------------------------------
5898
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005899AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5900 AudioStreamIn *input,
5901 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07005902 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005903 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005904 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005905 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005906 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5907 // mRsmpInIndex and mInputBytes set by readInputParameters()
Glenn Kasten254af182012-07-03 14:59:05 -07005908 mReqChannelCount(popcount(channelMask)),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005909 mReqSampleRate(sampleRate)
5910 // mBytesRead is only meaningful while active, and so is cleared in start()
5911 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005912{
Glenn Kasten480b4682012-02-28 12:30:08 -08005913 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005914
Mathias Agopian65ab4712010-07-14 17:59:35 -07005915 readInputParameters();
5916}
5917
5918
5919AudioFlinger::RecordThread::~RecordThread()
5920{
5921 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005922 delete mResampler;
5923 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005924}
5925
5926void AudioFlinger::RecordThread::onFirstRef()
5927{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005928 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005929}
5930
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005931status_t AudioFlinger::RecordThread::readyToRun()
5932{
5933 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005934 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005935 return status;
5936}
5937
Mathias Agopian65ab4712010-07-14 17:59:35 -07005938bool AudioFlinger::RecordThread::threadLoop()
5939{
5940 AudioBufferProvider::Buffer buffer;
5941 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005942 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005943
Eric Laurent44d98482010-09-30 16:12:31 -07005944 nsecs_t lastWarning = 0;
5945
Eric Laurentfeb0db62011-07-22 09:04:31 -07005946 acquireWakeLock();
5947
Mathias Agopian65ab4712010-07-14 17:59:35 -07005948 // start recording
5949 while (!exitPending()) {
5950
5951 processConfigEvents();
5952
5953 { // scope for mLock
5954 Mutex::Autolock _l(mLock);
5955 checkForNewParameters_l();
5956 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5957 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005958 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005959 mStandby = true;
5960 }
5961
5962 if (exitPending()) break;
5963
Eric Laurentfeb0db62011-07-22 09:04:31 -07005964 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005965 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005966 // go to sleep
5967 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005968 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005969 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005970 continue;
5971 }
5972 if (mActiveTrack != 0) {
5973 if (mActiveTrack->mState == TrackBase::PAUSING) {
5974 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005975 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005976 mStandby = true;
5977 }
5978 mActiveTrack.clear();
5979 mStartStopCond.broadcast();
5980 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5981 if (mReqChannelCount != mActiveTrack->channelCount()) {
5982 mActiveTrack.clear();
5983 mStartStopCond.broadcast();
5984 } else if (mBytesRead != 0) {
5985 // record start succeeds only if first read from audio input
5986 // succeeds
5987 if (mBytesRead > 0) {
5988 mActiveTrack->mState = TrackBase::ACTIVE;
5989 } else {
5990 mActiveTrack.clear();
5991 }
5992 mStartStopCond.broadcast();
5993 }
5994 mStandby = false;
5995 }
5996 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005997 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005998 }
5999
6000 if (mActiveTrack != 0) {
6001 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6002 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006003 unlockEffectChains(effectChains);
6004 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006005 continue;
6006 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006007 for (size_t i = 0; i < effectChains.size(); i ++) {
6008 effectChains[i]->process_l();
6009 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006010
Mathias Agopian65ab4712010-07-14 17:59:35 -07006011 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006012 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006013 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006014 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006015 // no resampling
6016 while (framesOut) {
6017 size_t framesIn = mFrameCount - mRsmpInIndex;
6018 if (framesIn) {
6019 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6020 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6021 if (framesIn > framesOut)
6022 framesIn = framesOut;
6023 mRsmpInIndex += framesIn;
6024 framesOut -= framesIn;
6025 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006026 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006027 memcpy(dst, src, framesIn * mFrameSize);
6028 } else {
6029 int16_t *src16 = (int16_t *)src;
6030 int16_t *dst16 = (int16_t *)dst;
6031 if (mChannelCount == 1) {
6032 while (framesIn--) {
6033 *dst16++ = *src16;
6034 *dst16++ = *src16++;
6035 }
6036 } else {
6037 while (framesIn--) {
6038 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
6039 src16 += 2;
6040 }
6041 }
6042 }
6043 }
6044 if (framesOut && mFrameCount == mRsmpInIndex) {
6045 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006046 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006047 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006048 framesOut = 0;
6049 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006050 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006051 mRsmpInIndex = 0;
6052 }
6053 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006054 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006055 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6056 // Force input into standby so that it tries to
6057 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006058 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006059 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006060 }
6061 mRsmpInIndex = mFrameCount;
6062 framesOut = 0;
6063 buffer.frameCount = 0;
6064 }
6065 }
6066 }
6067 } else {
6068 // resampling
6069
6070 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6071 // alter output frame count as if we were expecting stereo samples
6072 if (mChannelCount == 1 && mReqChannelCount == 1) {
6073 framesOut >>= 1;
6074 }
6075 mResampler->resample(mRsmpOutBuffer, framesOut, this);
6076 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6077 // are 32 bit aligned which should be always true.
6078 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006079 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006080 // the resampler always outputs stereo samples: do post stereo to mono conversion
6081 int16_t *src = (int16_t *)mRsmpOutBuffer;
6082 int16_t *dst = buffer.i16;
6083 while (framesOut--) {
6084 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
6085 src += 2;
6086 }
6087 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006088 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006089 }
6090
6091 }
Eric Laurenta011e352012-03-29 15:51:43 -07006092 if (mFramestoDrop == 0) {
6093 mActiveTrack->releaseBuffer(&buffer);
6094 } else {
6095 if (mFramestoDrop > 0) {
6096 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006097 if (mFramestoDrop <= 0) {
6098 clearSyncStartEvent();
6099 }
6100 } else {
6101 mFramestoDrop += buffer.frameCount;
6102 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6103 mSyncStartEvent->isCancelled()) {
6104 ALOGW("Synced record %s, session %d, trigger session %d",
6105 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6106 mActiveTrack->sessionId(),
6107 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6108 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006109 }
6110 }
6111 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006112 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006113 }
6114 // client isn't retrieving buffers fast enough
6115 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006116 if (!mActiveTrack->setOverflow()) {
6117 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006118 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006119 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006120 lastWarning = now;
6121 }
6122 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006123 // Release the processor for a while before asking for a new buffer.
6124 // This will give the application more chance to read from the buffer and
6125 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006126 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006127 }
6128 }
Eric Laurentec437d82011-07-26 20:54:46 -07006129 // enable changes in effect chain
6130 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006131 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006132 }
6133
6134 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006135 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006136 }
6137 mActiveTrack.clear();
6138
6139 mStartStopCond.broadcast();
6140
Eric Laurentfeb0db62011-07-22 09:04:31 -07006141 releaseWakeLock();
6142
Steve Block3856b092011-10-20 11:56:00 +01006143 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006144 return false;
6145}
6146
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006147
6148sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6149 const sp<AudioFlinger::Client>& client,
6150 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006151 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006152 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006153 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006154 int sessionId,
6155 status_t *status)
6156{
6157 sp<RecordTrack> track;
6158 status_t lStatus;
6159
6160 lStatus = initCheck();
6161 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006162 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006163 goto Exit;
6164 }
6165
6166 { // scope for mLock
6167 Mutex::Autolock _l(mLock);
6168
6169 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006170 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006171
Glenn Kasten7378ca52012-01-20 13:44:40 -08006172 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006173 lStatus = NO_MEMORY;
6174 goto Exit;
6175 }
6176
6177 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006178 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6179 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006180 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006181 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6182 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006183 }
6184 lStatus = NO_ERROR;
6185
6186Exit:
6187 if (status) {
6188 *status = lStatus;
6189 }
6190 return track;
6191}
6192
Eric Laurenta011e352012-03-29 15:51:43 -07006193status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006194 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006195 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006196{
Glenn Kasten58912562012-04-03 10:45:00 -07006197 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006198 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006199 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006200
6201 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006202 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006203 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6204 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6205 triggerSession,
6206 recordTrack->sessionId(),
6207 syncStartEventCallback,
6208 this);
Eric Laurent29864602012-05-08 18:57:51 -07006209 // Sync event can be cancelled by the trigger session if the track is not in a
6210 // compatible state in which case we start record immediately
6211 if (mSyncStartEvent->isCancelled()) {
6212 clearSyncStartEvent();
6213 } else {
6214 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6215 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6216 }
Eric Laurenta011e352012-03-29 15:51:43 -07006217 }
6218
Mathias Agopian65ab4712010-07-14 17:59:35 -07006219 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006220 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006221 if (mActiveTrack != 0) {
6222 if (recordTrack != mActiveTrack.get()) {
6223 status = -EBUSY;
6224 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6225 mActiveTrack->mState = TrackBase::ACTIVE;
6226 }
6227 return status;
6228 }
6229
6230 recordTrack->mState = TrackBase::IDLE;
6231 mActiveTrack = recordTrack;
6232 mLock.unlock();
6233 status_t status = AudioSystem::startInput(mId);
6234 mLock.lock();
6235 if (status != NO_ERROR) {
6236 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006237 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006238 return status;
6239 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006240 mRsmpInIndex = mFrameCount;
6241 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006242 if (mResampler != NULL) {
6243 mResampler->reset();
6244 }
6245 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006246 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006247 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006248 mWaitWorkCV.signal();
6249 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006250 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006251 mActiveTrack.clear();
6252 status = INVALID_OPERATION;
6253 goto startError;
6254 }
6255 mStartStopCond.wait(mLock);
6256 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006257 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006258 status = BAD_VALUE;
6259 goto startError;
6260 }
Steve Block3856b092011-10-20 11:56:00 +01006261 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006262 return status;
6263 }
6264startError:
6265 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006266 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006267 return status;
6268}
6269
Eric Laurenta011e352012-03-29 15:51:43 -07006270void AudioFlinger::RecordThread::clearSyncStartEvent()
6271{
6272 if (mSyncStartEvent != 0) {
6273 mSyncStartEvent->cancel();
6274 }
6275 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006276 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006277}
6278
6279void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6280{
6281 sp<SyncEvent> strongEvent = event.promote();
6282
6283 if (strongEvent != 0) {
6284 RecordThread *me = (RecordThread *)strongEvent->cookie();
6285 me->handleSyncStartEvent(strongEvent);
6286 }
6287}
6288
6289void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6290{
Eric Laurent29864602012-05-08 18:57:51 -07006291 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006292 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6293 // from audio HAL
6294 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006295 }
6296}
6297
Mathias Agopian65ab4712010-07-14 17:59:35 -07006298void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006299 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006300 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006301 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006302 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006303 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6304 mActiveTrack->mState = TrackBase::PAUSING;
6305 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006306 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006307 return;
6308 }
6309 mStartStopCond.wait(mLock);
6310 // if we have been restarted, recordTrack == mActiveTrack.get() here
6311 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6312 mLock.unlock();
6313 AudioSystem::stopInput(mId);
6314 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006315 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006316 }
6317 }
6318 }
6319}
6320
Eric Laurenta011e352012-03-29 15:51:43 -07006321bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6322{
6323 return false;
6324}
6325
6326status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6327{
6328 if (!isValidSyncEvent(event)) {
6329 return BAD_VALUE;
6330 }
6331
6332 Mutex::Autolock _l(mLock);
6333
6334 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6335 mTrack->setSyncEvent(event);
6336 return NO_ERROR;
6337 }
6338 return NAME_NOT_FOUND;
6339}
6340
Mathias Agopian65ab4712010-07-14 17:59:35 -07006341status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6342{
6343 const size_t SIZE = 256;
6344 char buffer[SIZE];
6345 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006346
6347 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6348 result.append(buffer);
6349
6350 if (mActiveTrack != 0) {
6351 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006352 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006353 mActiveTrack->dump(buffer, SIZE);
6354 result.append(buffer);
6355
6356 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6357 result.append(buffer);
6358 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6359 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006360 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006361 result.append(buffer);
6362 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6363 result.append(buffer);
6364 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6365 result.append(buffer);
6366
6367
6368 } else {
6369 result.append("No record client\n");
6370 }
6371 write(fd, result.string(), result.size());
6372
6373 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006374 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006375
6376 return NO_ERROR;
6377}
6378
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006379// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006380status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006381{
6382 size_t framesReq = buffer->frameCount;
6383 size_t framesReady = mFrameCount - mRsmpInIndex;
6384 int channelCount;
6385
6386 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006387 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006388 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006389 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006390 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6391 // Force input into standby so that it tries to
6392 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006393 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006394 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006395 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006396 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006397 buffer->frameCount = 0;
6398 return NOT_ENOUGH_DATA;
6399 }
6400 mRsmpInIndex = 0;
6401 framesReady = mFrameCount;
6402 }
6403
6404 if (framesReq > framesReady) {
6405 framesReq = framesReady;
6406 }
6407
6408 if (mChannelCount == 1 && mReqChannelCount == 2) {
6409 channelCount = 1;
6410 } else {
6411 channelCount = 2;
6412 }
6413 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6414 buffer->frameCount = framesReq;
6415 return NO_ERROR;
6416}
6417
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006418// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006419void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6420{
6421 mRsmpInIndex += buffer->frameCount;
6422 buffer->frameCount = 0;
6423}
6424
6425bool AudioFlinger::RecordThread::checkForNewParameters_l()
6426{
6427 bool reconfig = false;
6428
6429 while (!mNewParameters.isEmpty()) {
6430 status_t status = NO_ERROR;
6431 String8 keyValuePair = mNewParameters[0];
6432 AudioParameter param = AudioParameter(keyValuePair);
6433 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006434 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006435 int reqSamplingRate = mReqSampleRate;
6436 int reqChannelCount = mReqChannelCount;
6437
6438 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6439 reqSamplingRate = value;
6440 reconfig = true;
6441 }
6442 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006443 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006444 reconfig = true;
6445 }
6446 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006447 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006448 reconfig = true;
6449 }
6450 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6451 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006452 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006453 // if frame count is changed after track creation
6454 if (mActiveTrack != 0) {
6455 status = INVALID_OPERATION;
6456 } else {
6457 reconfig = true;
6458 }
6459 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006460 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6461 // forward device change to effects that have requested to be
6462 // aware of attached audio device.
6463 for (size_t i = 0; i < mEffectChains.size(); i++) {
6464 mEffectChains[i]->setDevice_l(value);
6465 }
6466 // store input device and output device but do not forward output device to audio HAL.
6467 // Note that status is ignored by the caller for output device
6468 // (see AudioFlinger::setParameters()
Glenn Kasten94479fd2012-07-09 15:39:54 -07006469 uint32_t /*audio_devices_t*/ newDevice = mDevice;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006470 if (value & AUDIO_DEVICE_OUT_ALL) {
Glenn Kasten01542f22012-07-02 12:46:15 -07006471 newDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006472 status = BAD_VALUE;
6473 } else {
Glenn Kasten01542f22012-07-02 12:46:15 -07006474 newDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006475 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6476 if (mTrack != NULL) {
6477 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006478 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006479 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6480 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6481 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006482 }
Glenn Kasten01542f22012-07-02 12:46:15 -07006483 newDevice |= value;
Glenn Kasten94479fd2012-07-09 15:39:54 -07006484 mDevice = (audio_devices_t) newDevice; // since mDevice is read by other threads, only write to it once
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006485 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006486 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006487 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006488 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006489 mInput->stream->common.standby(&mInput->stream->common);
6490 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6491 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006492 }
6493 if (reconfig) {
6494 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006495 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006496 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006497 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006498 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6499 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006500 status = NO_ERROR;
6501 }
6502 if (status == NO_ERROR) {
6503 readInputParameters();
6504 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6505 }
6506 }
6507 }
6508
6509 mNewParameters.removeAt(0);
6510
6511 mParamStatus = status;
6512 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006513 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6514 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006515 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006516 }
6517 return reconfig;
6518}
6519
6520String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6521{
Dima Zavinfce7a472011-04-19 22:30:36 -07006522 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006523 String8 out_s8 = String8();
6524
6525 Mutex::Autolock _l(mLock);
6526 if (initCheck() != NO_ERROR) {
6527 return out_s8;
6528 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006529
Dima Zavin799a70e2011-04-18 16:57:27 -07006530 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006531 out_s8 = String8(s);
6532 free(s);
6533 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006534}
6535
6536void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6537 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006538 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006539
6540 switch (event) {
6541 case AudioSystem::INPUT_OPENED:
6542 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006543 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006544 desc.samplingRate = mSampleRate;
6545 desc.format = mFormat;
6546 desc.frameCount = mFrameCount;
6547 desc.latency = 0;
6548 param2 = &desc;
6549 break;
6550
6551 case AudioSystem::INPUT_CLOSED:
6552 default:
6553 break;
6554 }
6555 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6556}
6557
6558void AudioFlinger::RecordThread::readInputParameters()
6559{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006560 delete mRsmpInBuffer;
6561 // mRsmpInBuffer is always assigned a new[] below
6562 delete mRsmpOutBuffer;
6563 mRsmpOutBuffer = NULL;
6564 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006565 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006566
Dima Zavin799a70e2011-04-18 16:57:27 -07006567 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006568 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6569 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006570 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006571 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006572 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006573 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006574 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006575 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6576
Glenn Kasten53d76db2012-03-08 12:32:47 -08006577 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006578 {
6579 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006580 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6581 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006582 if (mChannelCount == 1 && mReqChannelCount == 2) {
6583 channelCount = 1;
6584 } else {
6585 channelCount = 2;
6586 }
6587 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6588 mResampler->setSampleRate(mSampleRate);
6589 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6590 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6591
6592 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6593 if (mChannelCount == 1 && mReqChannelCount == 1) {
6594 mFrameCount >>= 1;
6595 }
6596
6597 }
6598 mRsmpInIndex = mFrameCount;
6599}
6600
6601unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6602{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006603 Mutex::Autolock _l(mLock);
6604 if (initCheck() != NO_ERROR) {
6605 return 0;
6606 }
6607
Dima Zavin799a70e2011-04-18 16:57:27 -07006608 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006609}
6610
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006611uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6612{
6613 Mutex::Autolock _l(mLock);
6614 uint32_t result = 0;
6615 if (getEffectChain_l(sessionId) != 0) {
6616 result = EFFECT_SESSION;
6617 }
6618
6619 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6620 result |= TRACK_SESSION;
6621 }
6622
6623 return result;
6624}
6625
Eric Laurent59bd0da2011-08-01 09:52:20 -07006626AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6627{
6628 Mutex::Autolock _l(mLock);
6629 return mTrack;
6630}
6631
Glenn Kastenaed850d2012-01-26 09:46:34 -08006632AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006633{
6634 Mutex::Autolock _l(mLock);
6635 return mInput;
6636}
6637
6638AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6639{
6640 Mutex::Autolock _l(mLock);
6641 AudioStreamIn *input = mInput;
6642 mInput = NULL;
6643 return input;
6644}
6645
6646// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006647audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006648{
6649 if (mInput == NULL) {
6650 return NULL;
6651 }
6652 return &mInput->stream->common;
6653}
6654
6655
Mathias Agopian65ab4712010-07-14 17:59:35 -07006656// ----------------------------------------------------------------------------
6657
Eric Laurenta4c5a552012-03-29 10:12:40 -07006658audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6659{
6660 if (!settingsAllowed()) {
6661 return 0;
6662 }
6663 Mutex::Autolock _l(mLock);
6664 return loadHwModule_l(name);
6665}
6666
6667// loadHwModule_l() must be called with AudioFlinger::mLock held
6668audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6669{
6670 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6671 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6672 ALOGW("loadHwModule() module %s already loaded", name);
6673 return mAudioHwDevs.keyAt(i);
6674 }
6675 }
6676
Eric Laurenta4c5a552012-03-29 10:12:40 -07006677 audio_hw_device_t *dev;
6678
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006679 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006680 if (rc) {
6681 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6682 return 0;
6683 }
6684
6685 mHardwareStatus = AUDIO_HW_INIT;
6686 rc = dev->init_check(dev);
6687 mHardwareStatus = AUDIO_HW_IDLE;
6688 if (rc) {
6689 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6690 return 0;
6691 }
6692
6693 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6694 (NULL != dev->set_master_volume)) {
6695 AutoMutex lock(mHardwareLock);
6696 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6697 dev->set_master_volume(dev, mMasterVolume);
6698 mHardwareStatus = AUDIO_HW_IDLE;
6699 }
6700
6701 audio_module_handle_t handle = nextUniqueId();
6702 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6703
6704 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006705 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006706
6707 return handle;
6708
6709}
6710
6711audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6712 audio_devices_t *pDevices,
6713 uint32_t *pSamplingRate,
6714 audio_format_t *pFormat,
6715 audio_channel_mask_t *pChannelMask,
6716 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006717 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006718{
6719 status_t status;
6720 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006721 struct audio_config config = {
6722 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6723 channel_mask: pChannelMask ? *pChannelMask : 0,
6724 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6725 };
6726 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006727 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006728
Eric Laurenta4c5a552012-03-29 10:12:40 -07006729 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6730 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006731 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006732 config.sample_rate,
6733 config.format,
6734 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006735 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006736
6737 if (pDevices == NULL || *pDevices == 0) {
6738 return 0;
6739 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006740
Mathias Agopian65ab4712010-07-14 17:59:35 -07006741 Mutex::Autolock _l(mLock);
6742
Eric Laurenta4c5a552012-03-29 10:12:40 -07006743 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006744 if (outHwDev == NULL)
6745 return 0;
6746
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006747 audio_io_handle_t id = nextUniqueId();
6748
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006749 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006750
6751 status = outHwDev->open_output_stream(outHwDev,
6752 id,
6753 *pDevices,
6754 (audio_output_flags_t)flags,
6755 &config,
6756 &outStream);
6757
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006758 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006759 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006760 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006761 config.sample_rate,
6762 config.format,
6763 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006764 status);
6765
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006766 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006767 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006768
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006769 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006770 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6771 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006772 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006773 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006774 } else {
6775 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006776 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006777 }
6778 mPlaybackThreads.add(id, thread);
6779
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006780 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6781 if (pFormat != NULL) *pFormat = config.format;
6782 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006783 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006784
6785 // notify client processes of the new output creation
6786 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006787
6788 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006789 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006790 ALOGI("Using module %d has the primary audio interface", module);
6791 mPrimaryHardwareDev = outHwDev;
6792
6793 AutoMutex lock(mHardwareLock);
6794 mHardwareStatus = AUDIO_HW_SET_MODE;
6795 outHwDev->set_mode(outHwDev, mMode);
6796
6797 // Determine the level of master volume support the primary audio HAL has,
6798 // and set the initial master volume at the same time.
6799 float initialVolume = 1.0;
6800 mMasterVolumeSupportLvl = MVS_NONE;
6801
6802 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6803 if ((NULL != outHwDev->get_master_volume) &&
6804 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6805 mMasterVolumeSupportLvl = MVS_FULL;
6806 } else {
6807 mMasterVolumeSupportLvl = MVS_SETONLY;
6808 initialVolume = 1.0;
6809 }
6810
6811 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6812 if ((NULL == outHwDev->set_master_volume) ||
6813 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6814 mMasterVolumeSupportLvl = MVS_NONE;
6815 }
6816 // now that we have a primary device, initialize master volume on other devices
6817 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6818 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6819
6820 if ((dev != mPrimaryHardwareDev) &&
6821 (NULL != dev->set_master_volume)) {
6822 dev->set_master_volume(dev, initialVolume);
6823 }
6824 }
6825 mHardwareStatus = AUDIO_HW_IDLE;
6826 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6827 ? initialVolume
6828 : 1.0;
6829 mMasterVolume = initialVolume;
6830 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006831 return id;
6832 }
6833
6834 return 0;
6835}
6836
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006837audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6838 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006839{
6840 Mutex::Autolock _l(mLock);
6841 MixerThread *thread1 = checkMixerThread_l(output1);
6842 MixerThread *thread2 = checkMixerThread_l(output2);
6843
6844 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006845 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006846 return 0;
6847 }
6848
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006849 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006850 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6851 thread->addOutputTrack(thread2);
6852 mPlaybackThreads.add(id, thread);
6853 // notify client processes of the new output creation
6854 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6855 return id;
6856}
6857
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006858status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006859{
6860 // keep strong reference on the playback thread so that
6861 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006862 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006863 {
6864 Mutex::Autolock _l(mLock);
6865 thread = checkPlaybackThread_l(output);
6866 if (thread == NULL) {
6867 return BAD_VALUE;
6868 }
6869
Steve Block3856b092011-10-20 11:56:00 +01006870 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006871
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006872 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006873 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006874 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006875 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6876 dupThread->removeOutputTrack((MixerThread *)thread.get());
6877 }
6878 }
6879 }
Glenn Kastena1117922012-01-26 10:53:32 -08006880 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006881 mPlaybackThreads.removeItem(output);
6882 }
6883 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006884 // The thread entity (active unit of execution) is no longer running here,
6885 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006886
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006887 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006888 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006889 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006890 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006891 out->hwDev->close_output_stream(out->hwDev, out->stream);
6892 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006893 }
6894 return NO_ERROR;
6895}
6896
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006897status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006898{
6899 Mutex::Autolock _l(mLock);
6900 PlaybackThread *thread = checkPlaybackThread_l(output);
6901
6902 if (thread == NULL) {
6903 return BAD_VALUE;
6904 }
6905
Steve Block3856b092011-10-20 11:56:00 +01006906 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006907 thread->suspend();
6908
6909 return NO_ERROR;
6910}
6911
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006912status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006913{
6914 Mutex::Autolock _l(mLock);
6915 PlaybackThread *thread = checkPlaybackThread_l(output);
6916
6917 if (thread == NULL) {
6918 return BAD_VALUE;
6919 }
6920
Steve Block3856b092011-10-20 11:56:00 +01006921 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006922
6923 thread->restore();
6924
6925 return NO_ERROR;
6926}
6927
Eric Laurenta4c5a552012-03-29 10:12:40 -07006928audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6929 audio_devices_t *pDevices,
6930 uint32_t *pSamplingRate,
6931 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07006932 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006933{
6934 status_t status;
6935 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006936 struct audio_config config = {
6937 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6938 channel_mask: pChannelMask ? *pChannelMask : 0,
6939 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6940 };
6941 uint32_t reqSamplingRate = config.sample_rate;
6942 audio_format_t reqFormat = config.format;
6943 audio_channel_mask_t reqChannels = config.channel_mask;
6944 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006945 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006946
6947 if (pDevices == NULL || *pDevices == 0) {
6948 return 0;
6949 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006950
Mathias Agopian65ab4712010-07-14 17:59:35 -07006951 Mutex::Autolock _l(mLock);
6952
Eric Laurenta4c5a552012-03-29 10:12:40 -07006953 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006954 if (inHwDev == NULL)
6955 return 0;
6956
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006957 audio_io_handle_t id = nextUniqueId();
6958
6959 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006960 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006961 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006962 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006963 config.sample_rate,
6964 config.format,
6965 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006966 status);
6967
6968 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6969 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6970 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006971 if (status == BAD_VALUE &&
6972 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6973 (config.sample_rate <= 2 * reqSamplingRate) &&
6974 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07006975 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006976 inStream = NULL;
6977 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006978 }
6979
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006980 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006981 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6982
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006983 // Start record thread
6984 // RecorThread require both input and output device indication to forward to audio
6985 // pre processing modules
6986 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6987 thread = new RecordThread(this,
6988 input,
6989 reqSamplingRate,
6990 reqChannels,
6991 id,
6992 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006993 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006994 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006995 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006996 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006997 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006998
Dima Zavin799a70e2011-04-18 16:57:27 -07006999 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007000
7001 // notify client processes of the new input creation
7002 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7003 return id;
7004 }
7005
7006 return 0;
7007}
7008
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007009status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007010{
7011 // keep strong reference on the record thread so that
7012 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007013 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007014 {
7015 Mutex::Autolock _l(mLock);
7016 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007017 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007018 return BAD_VALUE;
7019 }
7020
Steve Block3856b092011-10-20 11:56:00 +01007021 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007022 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007023 mRecordThreads.removeItem(input);
7024 }
7025 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007026 // The thread entity (active unit of execution) is no longer running here,
7027 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007028
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007029 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007030 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007031 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07007032 in->hwDev->close_input_stream(in->hwDev, in->stream);
7033 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007034
7035 return NO_ERROR;
7036}
7037
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007038status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007039{
7040 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007041 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007042
7043 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7044 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007045 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007046 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007047
7048 return NO_ERROR;
7049}
7050
7051
7052int AudioFlinger::newAudioSessionId()
7053{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007054 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007055}
7056
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007057void AudioFlinger::acquireAudioSessionId(int audioSession)
7058{
7059 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007060 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007061 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007062 size_t num = mAudioSessionRefs.size();
7063 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007064 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007065 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7066 ref->mCnt++;
7067 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007068 return;
7069 }
7070 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007071 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7072 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007073}
7074
7075void AudioFlinger::releaseAudioSessionId(int audioSession)
7076{
7077 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007078 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007079 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007080 size_t num = mAudioSessionRefs.size();
7081 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007082 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007083 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7084 ref->mCnt--;
7085 ALOGV(" decremented refcount to %d", ref->mCnt);
7086 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007087 mAudioSessionRefs.removeAt(i);
7088 delete ref;
7089 purgeStaleEffects_l();
7090 }
7091 return;
7092 }
7093 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007094 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007095}
7096
7097void AudioFlinger::purgeStaleEffects_l() {
7098
Steve Block3856b092011-10-20 11:56:00 +01007099 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007100
7101 Vector< sp<EffectChain> > chains;
7102
7103 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7104 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7105 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7106 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007107 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7108 chains.push(ec);
7109 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007110 }
7111 }
7112 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7113 sp<RecordThread> t = mRecordThreads.valueAt(i);
7114 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7115 sp<EffectChain> ec = t->mEffectChains[j];
7116 chains.push(ec);
7117 }
7118 }
7119
7120 for (size_t i = 0; i < chains.size(); i++) {
7121 sp<EffectChain> ec = chains[i];
7122 int sessionid = ec->sessionId();
7123 sp<ThreadBase> t = ec->mThread.promote();
7124 if (t == 0) {
7125 continue;
7126 }
7127 size_t numsessionrefs = mAudioSessionRefs.size();
7128 bool found = false;
7129 for (size_t k = 0; k < numsessionrefs; k++) {
7130 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007131 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007132 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007133 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007134 found = true;
7135 break;
7136 }
7137 }
7138 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007139 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007140 // remove all effects from the chain
7141 while (ec->mEffects.size()) {
7142 sp<EffectModule> effect = ec->mEffects[0];
7143 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007144 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007145 if (effect->purgeHandles()) {
7146 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007147 }
7148 AudioSystem::unregisterEffect(effect->id());
7149 }
7150 }
7151 }
7152 return;
7153}
7154
Mathias Agopian65ab4712010-07-14 17:59:35 -07007155// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007156AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007157{
Glenn Kastena1117922012-01-26 10:53:32 -08007158 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007159}
7160
7161// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007162AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007163{
7164 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007165 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007166}
7167
7168// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007169AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007170{
Glenn Kastena1117922012-01-26 10:53:32 -08007171 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007172}
7173
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007174uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007175{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007176 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007177}
7178
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007179AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007180{
7181 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7182 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007183 AudioStreamOut *output = thread->getOutput();
7184 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007185 return thread;
7186 }
7187 }
7188 return NULL;
7189}
7190
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007191uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007192{
7193 PlaybackThread *thread = primaryPlaybackThread_l();
7194
7195 if (thread == NULL) {
7196 return 0;
7197 }
7198
7199 return thread->device();
7200}
7201
Eric Laurenta011e352012-03-29 15:51:43 -07007202sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7203 int triggerSession,
7204 int listenerSession,
7205 sync_event_callback_t callBack,
7206 void *cookie)
7207{
7208 Mutex::Autolock _l(mLock);
7209
7210 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7211 status_t playStatus = NAME_NOT_FOUND;
7212 status_t recStatus = NAME_NOT_FOUND;
7213 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7214 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7215 if (playStatus == NO_ERROR) {
7216 return event;
7217 }
7218 }
7219 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7220 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7221 if (recStatus == NO_ERROR) {
7222 return event;
7223 }
7224 }
7225 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7226 mPendingSyncEvents.add(event);
7227 } else {
7228 ALOGV("createSyncEvent() invalid event %d", event->type());
7229 event.clear();
7230 }
7231 return event;
7232}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007233
Mathias Agopian65ab4712010-07-14 17:59:35 -07007234// ----------------------------------------------------------------------------
7235// Effect management
7236// ----------------------------------------------------------------------------
7237
7238
Glenn Kastenf587ba52012-01-26 16:25:10 -08007239status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007240{
7241 Mutex::Autolock _l(mLock);
7242 return EffectQueryNumberEffects(numEffects);
7243}
7244
Glenn Kastenf587ba52012-01-26 16:25:10 -08007245status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007246{
7247 Mutex::Autolock _l(mLock);
7248 return EffectQueryEffect(index, descriptor);
7249}
7250
Glenn Kasten5e92a782012-01-30 07:40:52 -08007251status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007252 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007253{
7254 Mutex::Autolock _l(mLock);
7255 return EffectGetDescriptor(pUuid, descriptor);
7256}
7257
7258
Mathias Agopian65ab4712010-07-14 17:59:35 -07007259sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7260 effect_descriptor_t *pDesc,
7261 const sp<IEffectClient>& effectClient,
7262 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007263 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007264 int sessionId,
7265 status_t *status,
7266 int *id,
7267 int *enabled)
7268{
7269 status_t lStatus = NO_ERROR;
7270 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007271 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007272
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007273 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007274 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007275
7276 if (pDesc == NULL) {
7277 lStatus = BAD_VALUE;
7278 goto Exit;
7279 }
7280
Eric Laurent84e9a102010-09-23 16:10:16 -07007281 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007282 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007283 lStatus = PERMISSION_DENIED;
7284 goto Exit;
7285 }
7286
Dima Zavinfce7a472011-04-19 22:30:36 -07007287 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007288 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007289 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007290 lStatus = PERMISSION_DENIED;
7291 goto Exit;
7292 }
7293
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007294 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007295 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007296 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007297 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007298 lStatus = BAD_VALUE;
7299 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007300 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007301 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007302 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007303 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007304 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007305 }
7306 }
7307
Mathias Agopian65ab4712010-07-14 17:59:35 -07007308 {
7309 Mutex::Autolock _l(mLock);
7310
Mathias Agopian65ab4712010-07-14 17:59:35 -07007311
7312 if (!EffectIsNullUuid(&pDesc->uuid)) {
7313 // if uuid is specified, request effect descriptor
7314 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7315 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007316 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007317 goto Exit;
7318 }
7319 } else {
7320 // if uuid is not specified, look for an available implementation
7321 // of the required type in effect factory
7322 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007323 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007324 lStatus = BAD_VALUE;
7325 goto Exit;
7326 }
7327 uint32_t numEffects = 0;
7328 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007329 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007330 bool found = false;
7331
7332 lStatus = EffectQueryNumberEffects(&numEffects);
7333 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007334 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007335 goto Exit;
7336 }
7337 for (uint32_t i = 0; i < numEffects; i++) {
7338 lStatus = EffectQueryEffect(i, &desc);
7339 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007340 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007341 continue;
7342 }
7343 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7344 // If matching type found save effect descriptor. If the session is
7345 // 0 and the effect is not auxiliary, continue enumeration in case
7346 // an auxiliary version of this effect type is available
7347 found = true;
7348 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07007349 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007350 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7351 break;
7352 }
7353 }
7354 }
7355 if (!found) {
7356 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007357 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007358 goto Exit;
7359 }
7360 // For same effect type, chose auxiliary version over insert version if
7361 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007362 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007363 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7364 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7365 }
7366 }
7367
7368 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007369 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007370 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7371 lStatus = INVALID_OPERATION;
7372 goto Exit;
7373 }
7374
Eric Laurent59255e42011-07-27 19:49:51 -07007375 // check recording permission for visualizer
7376 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7377 !recordingAllowed()) {
7378 lStatus = PERMISSION_DENIED;
7379 goto Exit;
7380 }
7381
Mathias Agopian65ab4712010-07-14 17:59:35 -07007382 // return effect descriptor
7383 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7384
7385 // If output is not specified try to find a matching audio session ID in one of the
7386 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007387 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7388 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007389 // Note: io is never 0 when creating an effect on an input
7390 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007391 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007392 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7393 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007394 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007395 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007396 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007397 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007398 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007399 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7400 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7401 io = mRecordThreads.keyAt(i);
7402 break;
7403 }
7404 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007405 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007406 // If no output thread contains the requested session ID, default to
7407 // first output. The effect chain will be moved to the correct output
7408 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007409 if (io == 0 && mPlaybackThreads.size()) {
7410 io = mPlaybackThreads.keyAt(0);
7411 }
Steve Block3856b092011-10-20 11:56:00 +01007412 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007413 }
7414 ThreadBase *thread = checkRecordThread_l(io);
7415 if (thread == NULL) {
7416 thread = checkPlaybackThread_l(io);
7417 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007418 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007419 lStatus = BAD_VALUE;
7420 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007421 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007422 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007423
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007424 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007425
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007426 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007427 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7428 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007429 if (handle != 0 && id != NULL) {
7430 *id = handle->id();
7431 }
7432 }
7433
7434Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007435 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007436 *status = lStatus;
7437 }
7438 return handle;
7439}
7440
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007441status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7442 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007443{
Steve Block3856b092011-10-20 11:56:00 +01007444 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007445 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007446 Mutex::Autolock _l(mLock);
7447 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007448 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007449 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007450 }
Eric Laurentde070132010-07-13 04:45:46 -07007451 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7452 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007453 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007454 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007455 }
Eric Laurentde070132010-07-13 04:45:46 -07007456 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7457 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007458 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007459 return BAD_VALUE;
7460 }
7461
7462 Mutex::Autolock _dl(dstThread->mLock);
7463 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007464 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007465
Mathias Agopian65ab4712010-07-14 17:59:35 -07007466 return NO_ERROR;
7467}
7468
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007469// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007470status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007471 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007472 AudioFlinger::PlaybackThread *dstThread,
7473 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007474{
Steve Block3856b092011-10-20 11:56:00 +01007475 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007476 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007477
Eric Laurent59255e42011-07-27 19:49:51 -07007478 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007479 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007480 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007481 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007482 return INVALID_OPERATION;
7483 }
7484
Eric Laurent39e94f82010-07-28 01:32:47 -07007485 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007486 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007487 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007488 // removed.
7489 srcThread->removeEffectChain_l(chain);
7490
7491 // transfer all effects one by one so that new effect chain is created on new thread with
7492 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007493 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007494 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007495 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007496 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7497 while (effect != 0) {
7498 srcThread->removeEffect_l(effect);
7499 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007500 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7501 if (effect->state() == EffectModule::ACTIVE ||
7502 effect->state() == EffectModule::STOPPING) {
7503 effect->start();
7504 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007505 // if the move request is not received from audio policy manager, the effect must be
7506 // re-registered with the new strategy and output
7507 if (dstChain == 0) {
7508 dstChain = effect->chain().promote();
7509 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007510 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007511 srcThread->addEffect_l(effect);
7512 return NO_INIT;
7513 }
7514 strategy = dstChain->strategy();
7515 }
7516 if (reRegister) {
7517 AudioSystem::unregisterEffect(effect->id());
7518 AudioSystem::registerEffect(&effect->desc(),
7519 dstOutput,
7520 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007521 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007522 effect->id());
7523 }
Eric Laurentde070132010-07-13 04:45:46 -07007524 effect = chain->getEffectFromId_l(0);
7525 }
7526
7527 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007528}
7529
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007530
Mathias Agopian65ab4712010-07-14 17:59:35 -07007531// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007532sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007533 const sp<AudioFlinger::Client>& client,
7534 const sp<IEffectClient>& effectClient,
7535 int32_t priority,
7536 int sessionId,
7537 effect_descriptor_t *desc,
7538 int *enabled,
7539 status_t *status
7540 )
7541{
7542 sp<EffectModule> effect;
7543 sp<EffectHandle> handle;
7544 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007545 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007546 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007547 bool effectCreated = false;
7548 bool effectRegistered = false;
7549
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007550 lStatus = initCheck();
7551 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007552 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007553 goto Exit;
7554 }
7555
7556 // Do not allow effects with session ID 0 on direct output or duplicating threads
7557 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007558 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007559 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007560 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007561 lStatus = BAD_VALUE;
7562 goto Exit;
7563 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007564 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007565 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007566 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007567 desc->name, desc->flags, mType);
7568 lStatus = BAD_VALUE;
7569 goto Exit;
7570 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007571
Steve Block3856b092011-10-20 11:56:00 +01007572 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007573
7574 { // scope for mLock
7575 Mutex::Autolock _l(mLock);
7576
7577 // check for existing effect chain with the requested audio session
7578 chain = getEffectChain_l(sessionId);
7579 if (chain == 0) {
7580 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007581 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007582 chain = new EffectChain(this, sessionId);
7583 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007584 chain->setStrategy(getStrategyForSession_l(sessionId));
7585 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007586 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007587 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007588 }
7589
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007590 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007591
7592 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007593 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007594 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007595 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007596 if (lStatus != NO_ERROR) {
7597 goto Exit;
7598 }
7599 effectRegistered = true;
7600 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007601 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007602 lStatus = effect->status();
7603 if (lStatus != NO_ERROR) {
7604 goto Exit;
7605 }
Eric Laurentcab11242010-07-15 12:50:15 -07007606 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007607 if (lStatus != NO_ERROR) {
7608 goto Exit;
7609 }
7610 effectCreated = true;
7611
7612 effect->setDevice(mDevice);
7613 effect->setMode(mAudioFlinger->getMode());
7614 }
7615 // create effect handle and connect it to effect module
7616 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007617 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007618 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007619 *enabled = (int)effect->isEnabled();
7620 }
7621 }
7622
7623Exit:
7624 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007625 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007626 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007627 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007628 }
7629 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007630 AudioSystem::unregisterEffect(effect->id());
7631 }
7632 if (chainCreated) {
7633 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007634 }
7635 handle.clear();
7636 }
7637
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007638 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007639 *status = lStatus;
7640 }
7641 return handle;
7642}
7643
Eric Laurent717e1282012-06-29 16:36:52 -07007644sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7645{
7646 Mutex::Autolock _l(mLock);
7647 return getEffect_l(sessionId, effectId);
7648}
7649
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007650sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7651{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007652 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007653 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007654}
7655
Eric Laurentde070132010-07-13 04:45:46 -07007656// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7657// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007658status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007659{
7660 // check for existing effect chain with the requested audio session
7661 int sessionId = effect->sessionId();
7662 sp<EffectChain> chain = getEffectChain_l(sessionId);
7663 bool chainCreated = false;
7664
7665 if (chain == 0) {
7666 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007667 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007668 chain = new EffectChain(this, sessionId);
7669 addEffectChain_l(chain);
7670 chain->setStrategy(getStrategyForSession_l(sessionId));
7671 chainCreated = true;
7672 }
Steve Block3856b092011-10-20 11:56:00 +01007673 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007674
7675 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007676 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007677 this, effect->desc().name, chain.get());
7678 return BAD_VALUE;
7679 }
7680
7681 status_t status = chain->addEffect_l(effect);
7682 if (status != NO_ERROR) {
7683 if (chainCreated) {
7684 removeEffectChain_l(chain);
7685 }
7686 return status;
7687 }
7688
7689 effect->setDevice(mDevice);
7690 effect->setMode(mAudioFlinger->getMode());
7691 return NO_ERROR;
7692}
7693
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007694void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007695
Steve Block3856b092011-10-20 11:56:00 +01007696 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007697 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007698 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7699 detachAuxEffect_l(effect->id());
7700 }
7701
7702 sp<EffectChain> chain = effect->chain().promote();
7703 if (chain != 0) {
7704 // remove effect chain if removing last effect
7705 if (chain->removeEffect_l(effect) == 0) {
7706 removeEffectChain_l(chain);
7707 }
7708 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007709 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007710 }
7711}
7712
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007713void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007714 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007715{
7716 effectChains = mEffectChains;
7717 for (size_t i = 0; i < mEffectChains.size(); i++) {
7718 mEffectChains[i]->lock();
7719 }
7720}
7721
7722void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007723 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007724{
7725 for (size_t i = 0; i < effectChains.size(); i++) {
7726 effectChains[i]->unlock();
7727 }
7728}
7729
7730sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7731{
7732 Mutex::Autolock _l(mLock);
7733 return getEffectChain_l(sessionId);
7734}
7735
7736sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7737{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007738 size_t size = mEffectChains.size();
7739 for (size_t i = 0; i < size; i++) {
7740 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007741 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007742 }
7743 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007744 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007745}
7746
Glenn Kastenf78aee72012-01-04 11:00:47 -08007747void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007748{
7749 Mutex::Autolock _l(mLock);
7750 size_t size = mEffectChains.size();
7751 for (size_t i = 0; i < size; i++) {
7752 mEffectChains[i]->setMode_l(mode);
7753 }
7754}
7755
7756void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007757 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007758 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007759
Mathias Agopian65ab4712010-07-14 17:59:35 -07007760 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007761 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007762 // delete the effect module if removing last handle on it
7763 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007764 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007765 removeEffect_l(effect);
7766 AudioSystem::unregisterEffect(effect->id());
7767 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007768 }
7769}
7770
7771status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7772{
7773 int session = chain->sessionId();
7774 int16_t *buffer = mMixBuffer;
7775 bool ownsBuffer = false;
7776
Steve Block3856b092011-10-20 11:56:00 +01007777 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007778 if (session > 0) {
7779 // Only one effect chain can be present in direct output thread and it uses
7780 // the mix buffer as input
7781 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007782 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007783 buffer = new int16_t[numSamples];
7784 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007785 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007786 ownsBuffer = true;
7787 }
7788
7789 // Attach all tracks with same session ID to this chain.
7790 for (size_t i = 0; i < mTracks.size(); ++i) {
7791 sp<Track> track = mTracks[i];
7792 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007793 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007794 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007795 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007796 }
7797 }
7798
7799 // indicate all active tracks in the chain
7800 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7801 sp<Track> track = mActiveTracks[i].promote();
7802 if (track == 0) continue;
7803 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007804 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007805 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007806 }
7807 }
7808 }
7809
7810 chain->setInBuffer(buffer, ownsBuffer);
7811 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007812 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007813 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007814 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7815 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007816 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007817 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7818 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007819 // Effect chain for other sessions are inserted at beginning of effect
7820 // chains list to be processed before output mix effects. Relative order between other
7821 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007822 size_t size = mEffectChains.size();
7823 size_t i = 0;
7824 for (i = 0; i < size; i++) {
7825 if (mEffectChains[i]->sessionId() < session) break;
7826 }
7827 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007828 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007829
7830 return NO_ERROR;
7831}
7832
7833size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7834{
7835 int session = chain->sessionId();
7836
Steve Block3856b092011-10-20 11:56:00 +01007837 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007838
7839 for (size_t i = 0; i < mEffectChains.size(); i++) {
7840 if (chain == mEffectChains[i]) {
7841 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007842 // detach all active tracks from the chain
7843 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7844 sp<Track> track = mActiveTracks[i].promote();
7845 if (track == 0) continue;
7846 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007847 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007848 chain.get(), session);
7849 chain->decActiveTrackCnt();
7850 }
7851 }
7852
Mathias Agopian65ab4712010-07-14 17:59:35 -07007853 // detach all tracks with same session ID from this chain
7854 for (size_t i = 0; i < mTracks.size(); ++i) {
7855 sp<Track> track = mTracks[i];
7856 if (session == track->sessionId()) {
7857 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007858 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007859 }
7860 }
Eric Laurentde070132010-07-13 04:45:46 -07007861 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007862 }
7863 }
7864 return mEffectChains.size();
7865}
7866
Eric Laurentde070132010-07-13 04:45:46 -07007867status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7868 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007869{
7870 Mutex::Autolock _l(mLock);
7871 return attachAuxEffect_l(track, EffectId);
7872}
7873
Eric Laurentde070132010-07-13 04:45:46 -07007874status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7875 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007876{
7877 status_t status = NO_ERROR;
7878
7879 if (EffectId == 0) {
7880 track->setAuxBuffer(0, NULL);
7881 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007882 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7883 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007884 if (effect != 0) {
7885 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7886 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7887 } else {
7888 status = INVALID_OPERATION;
7889 }
7890 } else {
7891 status = BAD_VALUE;
7892 }
7893 }
7894 return status;
7895}
7896
7897void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7898{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007899 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007900 sp<Track> track = mTracks[i];
7901 if (track->auxEffectId() == effectId) {
7902 attachAuxEffect_l(track, 0);
7903 }
7904 }
7905}
7906
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007907status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7908{
7909 // only one chain per input thread
7910 if (mEffectChains.size() != 0) {
7911 return INVALID_OPERATION;
7912 }
Steve Block3856b092011-10-20 11:56:00 +01007913 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007914
7915 chain->setInBuffer(NULL);
7916 chain->setOutBuffer(NULL);
7917
Eric Laurent59255e42011-07-27 19:49:51 -07007918 checkSuspendOnAddEffectChain_l(chain);
7919
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007920 mEffectChains.add(chain);
7921
7922 return NO_ERROR;
7923}
7924
7925size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7926{
Steve Block3856b092011-10-20 11:56:00 +01007927 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007928 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007929 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7930 chain.get(), mEffectChains.size(), this);
7931 if (mEffectChains.size() == 1) {
7932 mEffectChains.removeAt(0);
7933 }
7934 return 0;
7935}
7936
Mathias Agopian65ab4712010-07-14 17:59:35 -07007937// ----------------------------------------------------------------------------
7938// EffectModule implementation
7939// ----------------------------------------------------------------------------
7940
7941#undef LOG_TAG
7942#define LOG_TAG "AudioFlinger::EffectModule"
7943
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007944AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007945 const wp<AudioFlinger::EffectChain>& chain,
7946 effect_descriptor_t *desc,
7947 int id,
7948 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07007949 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
7950 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
7951 // mDescriptor is set below
7952 // mConfig is set by configure() and not used before then
7953 mEffectInterface(NULL),
7954 mStatus(NO_INIT), mState(IDLE),
7955 // mMaxDisableWaitCnt is set by configure() and not used before then
7956 // mDisableWaitCnt is set by process() and updateState() and not used before then
7957 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007958{
Steve Block3856b092011-10-20 11:56:00 +01007959 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007960 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007961 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007962 return;
7963 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007964
7965 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7966
7967 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007968 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007969
7970 if (mStatus != NO_ERROR) {
7971 return;
7972 }
7973 lStatus = init();
7974 if (lStatus < 0) {
7975 mStatus = lStatus;
7976 goto Error;
7977 }
7978
Steve Block3856b092011-10-20 11:56:00 +01007979 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007980 return;
7981Error:
7982 EffectRelease(mEffectInterface);
7983 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007984 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007985}
7986
7987AudioFlinger::EffectModule::~EffectModule()
7988{
Steve Block3856b092011-10-20 11:56:00 +01007989 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007990 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007991 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7992 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7993 sp<ThreadBase> thread = mThread.promote();
7994 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007995 audio_stream_t *stream = thread->stream();
7996 if (stream != NULL) {
7997 stream->remove_audio_effect(stream, mEffectInterface);
7998 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007999 }
8000 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008001 // release effect engine
8002 EffectRelease(mEffectInterface);
8003 }
8004}
8005
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008006status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008007{
8008 status_t status;
8009
8010 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008011 int priority = handle->priority();
8012 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008013 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008014 size_t i;
8015 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008016 EffectHandle *h = mHandles[i];
8017 if (h == NULL || h->destroyed_l()) continue;
8018 // first non destroyed handle is considered in control
8019 if (controlHandle == NULL)
8020 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008021 if (h->priority() <= priority) break;
8022 }
8023 // if inserted in first place, move effect control from previous owner to this handle
8024 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008025 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008026 if (controlHandle != NULL) {
8027 enabled = controlHandle->enabled();
8028 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008029 }
Eric Laurent59255e42011-07-27 19:49:51 -07008030 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008031 status = NO_ERROR;
8032 } else {
8033 status = ALREADY_EXISTS;
8034 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008035 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008036 mHandles.insertAt(handle, i);
8037 return status;
8038}
8039
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008040size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008041{
8042 Mutex::Autolock _l(mLock);
8043 size_t size = mHandles.size();
8044 size_t i;
8045 for (i = 0; i < size; i++) {
8046 if (mHandles[i] == handle) break;
8047 }
8048 if (i == size) {
8049 return size;
8050 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008051 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008052
Mathias Agopian65ab4712010-07-14 17:59:35 -07008053 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008054 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008055 if (i == 0) {
8056 EffectHandle *h = controlHandle_l();
8057 if (h != NULL) {
8058 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008059 }
8060 }
8061
Eric Laurentec437d82011-07-26 20:54:46 -07008062 // Prevent calls to process() and other functions on effect interface from now on.
8063 // The effect engine will be released by the destructor when the last strong reference on
8064 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008065 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008066 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008067 }
8068
Mathias Agopian65ab4712010-07-14 17:59:35 -07008069 return size;
8070}
8071
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008072// must be called with EffectModule::mLock held
8073AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008074{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008075 // the first valid handle in the list has control over the module
8076 for (size_t i = 0; i < mHandles.size(); i++) {
8077 EffectHandle *h = mHandles[i];
8078 if (h != NULL && !h->destroyed_l()) {
8079 return h;
8080 }
8081 }
8082
8083 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008084}
8085
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008086size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008087{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008088 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008089 // keep a strong reference on this EffectModule to avoid calling the
8090 // destructor before we exit
8091 sp<EffectModule> keep(this);
8092 {
8093 sp<ThreadBase> thread = mThread.promote();
8094 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008095 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008096 }
8097 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008098 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008099}
8100
8101void AudioFlinger::EffectModule::updateState() {
8102 Mutex::Autolock _l(mLock);
8103
8104 switch (mState) {
8105 case RESTART:
8106 reset_l();
8107 // FALL THROUGH
8108
8109 case STARTING:
8110 // clear auxiliary effect input buffer for next accumulation
8111 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8112 memset(mConfig.inputCfg.buffer.raw,
8113 0,
8114 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8115 }
8116 start_l();
8117 mState = ACTIVE;
8118 break;
8119 case STOPPING:
8120 stop_l();
8121 mDisableWaitCnt = mMaxDisableWaitCnt;
8122 mState = STOPPED;
8123 break;
8124 case STOPPED:
8125 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8126 // turn off sequence.
8127 if (--mDisableWaitCnt == 0) {
8128 reset_l();
8129 mState = IDLE;
8130 }
8131 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008132 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008133 break;
8134 }
8135}
8136
8137void AudioFlinger::EffectModule::process()
8138{
8139 Mutex::Autolock _l(mLock);
8140
Eric Laurentec437d82011-07-26 20:54:46 -07008141 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008142 mConfig.inputCfg.buffer.raw == NULL ||
8143 mConfig.outputCfg.buffer.raw == NULL) {
8144 return;
8145 }
8146
Eric Laurent8f45bd72010-08-31 13:50:07 -07008147 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008148 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8149 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008150 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008151 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008152 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008153 }
8154
8155 // do the actual processing in the effect engine
8156 int ret = (*mEffectInterface)->process(mEffectInterface,
8157 &mConfig.inputCfg.buffer,
8158 &mConfig.outputCfg.buffer);
8159
8160 // force transition to IDLE state when engine is ready
8161 if (mState == STOPPED && ret == -ENODATA) {
8162 mDisableWaitCnt = 1;
8163 }
8164
8165 // clear auxiliary effect input buffer for next accumulation
8166 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008167 memset(mConfig.inputCfg.buffer.raw, 0,
8168 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008169 }
8170 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008171 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8172 // If an insert effect is idle and input buffer is different from output buffer,
8173 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008174 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008175 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008176 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8177 int16_t *in = mConfig.inputCfg.buffer.s16;
8178 int16_t *out = mConfig.outputCfg.buffer.s16;
8179 for (size_t i = 0; i < frameCnt; i++) {
8180 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008181 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008182 }
8183 }
8184}
8185
8186void AudioFlinger::EffectModule::reset_l()
8187{
8188 if (mEffectInterface == NULL) {
8189 return;
8190 }
8191 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8192}
8193
8194status_t AudioFlinger::EffectModule::configure()
8195{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008196 if (mEffectInterface == NULL) {
8197 return NO_INIT;
8198 }
8199
8200 sp<ThreadBase> thread = mThread.promote();
8201 if (thread == 0) {
8202 return DEAD_OBJECT;
8203 }
8204
8205 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07008206 audio_channel_mask_t channelMask = thread->channelMask();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008207
8208 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008209 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008210 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07008211 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008212 }
Glenn Kasten254af182012-07-03 14:59:05 -07008213 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07008214 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8215 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008216 mConfig.inputCfg.samplingRate = thread->sampleRate();
8217 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8218 mConfig.inputCfg.bufferProvider.cookie = NULL;
8219 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8220 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8221 mConfig.outputCfg.bufferProvider.cookie = NULL;
8222 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8223 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8224 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8225 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008226 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008227 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008228 // - in other sessions:
8229 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8230 // other effect: overwrites output buffer: input buffer == output buffer
8231 // Auxiliary effect:
8232 // accumulates in output buffer: input buffer != output buffer
8233 // Therefore: accumulate <=> input buffer != output buffer
8234 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8235 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8236 } else {
8237 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8238 }
8239 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8240 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8241 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8242 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8243
Steve Block3856b092011-10-20 11:56:00 +01008244 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008245 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8246
Mathias Agopian65ab4712010-07-14 17:59:35 -07008247 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008248 uint32_t size = sizeof(int);
8249 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008250 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008251 sizeof(effect_config_t),
8252 &mConfig,
8253 &size,
8254 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008255 if (status == 0) {
8256 status = cmdStatus;
8257 }
8258
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008259 if (status == 0 &&
8260 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8261 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8262 effect_param_t *p = (effect_param_t *)buf32;
8263
8264 p->psize = sizeof(uint32_t);
8265 p->vsize = sizeof(uint32_t);
8266 size = sizeof(int);
8267 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8268
8269 uint32_t latency = 0;
8270 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8271 if (pbt != NULL) {
8272 latency = pbt->latency_l();
8273 }
8274
8275 *((int32_t *)p->data + 1)= latency;
8276 (*mEffectInterface)->command(mEffectInterface,
8277 EFFECT_CMD_SET_PARAM,
8278 sizeof(effect_param_t) + 8,
8279 &buf32,
8280 &size,
8281 &cmdStatus);
8282 }
8283
Mathias Agopian65ab4712010-07-14 17:59:35 -07008284 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8285 (1000 * mConfig.outputCfg.buffer.frameCount);
8286
8287 return status;
8288}
8289
8290status_t AudioFlinger::EffectModule::init()
8291{
8292 Mutex::Autolock _l(mLock);
8293 if (mEffectInterface == NULL) {
8294 return NO_INIT;
8295 }
8296 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008297 uint32_t size = sizeof(status_t);
8298 status_t status = (*mEffectInterface)->command(mEffectInterface,
8299 EFFECT_CMD_INIT,
8300 0,
8301 NULL,
8302 &size,
8303 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008304 if (status == 0) {
8305 status = cmdStatus;
8306 }
8307 return status;
8308}
8309
Eric Laurentec35a142011-10-05 17:42:25 -07008310status_t AudioFlinger::EffectModule::start()
8311{
8312 Mutex::Autolock _l(mLock);
8313 return start_l();
8314}
8315
Mathias Agopian65ab4712010-07-14 17:59:35 -07008316status_t AudioFlinger::EffectModule::start_l()
8317{
8318 if (mEffectInterface == NULL) {
8319 return NO_INIT;
8320 }
8321 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008322 uint32_t size = sizeof(status_t);
8323 status_t status = (*mEffectInterface)->command(mEffectInterface,
8324 EFFECT_CMD_ENABLE,
8325 0,
8326 NULL,
8327 &size,
8328 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008329 if (status == 0) {
8330 status = cmdStatus;
8331 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008332 if (status == 0 &&
8333 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8334 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8335 sp<ThreadBase> thread = mThread.promote();
8336 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008337 audio_stream_t *stream = thread->stream();
8338 if (stream != NULL) {
8339 stream->add_audio_effect(stream, mEffectInterface);
8340 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008341 }
8342 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008343 return status;
8344}
8345
Eric Laurentec437d82011-07-26 20:54:46 -07008346status_t AudioFlinger::EffectModule::stop()
8347{
8348 Mutex::Autolock _l(mLock);
8349 return stop_l();
8350}
8351
Mathias Agopian65ab4712010-07-14 17:59:35 -07008352status_t AudioFlinger::EffectModule::stop_l()
8353{
8354 if (mEffectInterface == NULL) {
8355 return NO_INIT;
8356 }
8357 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008358 uint32_t size = sizeof(status_t);
8359 status_t status = (*mEffectInterface)->command(mEffectInterface,
8360 EFFECT_CMD_DISABLE,
8361 0,
8362 NULL,
8363 &size,
8364 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008365 if (status == 0) {
8366 status = cmdStatus;
8367 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008368 if (status == 0 &&
8369 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8370 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8371 sp<ThreadBase> thread = mThread.promote();
8372 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008373 audio_stream_t *stream = thread->stream();
8374 if (stream != NULL) {
8375 stream->remove_audio_effect(stream, mEffectInterface);
8376 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008377 }
8378 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008379 return status;
8380}
8381
Eric Laurent25f43952010-07-28 05:40:18 -07008382status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8383 uint32_t cmdSize,
8384 void *pCmdData,
8385 uint32_t *replySize,
8386 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008387{
8388 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008389// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008390
Eric Laurentec437d82011-07-26 20:54:46 -07008391 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008392 return NO_INIT;
8393 }
Eric Laurent25f43952010-07-28 05:40:18 -07008394 status_t status = (*mEffectInterface)->command(mEffectInterface,
8395 cmdCode,
8396 cmdSize,
8397 pCmdData,
8398 replySize,
8399 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008400 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008401 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008402 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008403 EffectHandle *h = mHandles[i];
8404 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008405 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8406 }
8407 }
8408 }
8409 return status;
8410}
8411
8412status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8413{
8414 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008415 return setEnabled_l(enabled);
8416}
8417
8418// must be called with EffectModule::mLock held
8419status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8420{
8421
Steve Block3856b092011-10-20 11:56:00 +01008422 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008423
8424 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008425 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8426 if (enabled && status != NO_ERROR) {
8427 return status;
8428 }
8429
Mathias Agopian65ab4712010-07-14 17:59:35 -07008430 switch (mState) {
8431 // going from disabled to enabled
8432 case IDLE:
8433 mState = STARTING;
8434 break;
8435 case STOPPED:
8436 mState = RESTART;
8437 break;
8438 case STOPPING:
8439 mState = ACTIVE;
8440 break;
8441
8442 // going from enabled to disabled
8443 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008444 mState = STOPPED;
8445 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008446 case STARTING:
8447 mState = IDLE;
8448 break;
8449 case ACTIVE:
8450 mState = STOPPING;
8451 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008452 case DESTROYED:
8453 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008454 }
8455 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008456 EffectHandle *h = mHandles[i];
8457 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008458 h->setEnabled(enabled);
8459 }
8460 }
8461 }
8462 return NO_ERROR;
8463}
8464
Glenn Kastenc59c0042012-02-02 14:06:11 -08008465bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008466{
8467 switch (mState) {
8468 case RESTART:
8469 case STARTING:
8470 case ACTIVE:
8471 return true;
8472 case IDLE:
8473 case STOPPING:
8474 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008475 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008476 default:
8477 return false;
8478 }
8479}
8480
Glenn Kastenc59c0042012-02-02 14:06:11 -08008481bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008482{
8483 switch (mState) {
8484 case RESTART:
8485 case ACTIVE:
8486 case STOPPING:
8487 case STOPPED:
8488 return true;
8489 case IDLE:
8490 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008491 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008492 default:
8493 return false;
8494 }
8495}
8496
Mathias Agopian65ab4712010-07-14 17:59:35 -07008497status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8498{
8499 Mutex::Autolock _l(mLock);
8500 status_t status = NO_ERROR;
8501
8502 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8503 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008504 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008505 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8506 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008507 status_t cmdStatus;
8508 uint32_t volume[2];
8509 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008510 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008511 volume[0] = *left;
8512 volume[1] = *right;
8513 if (controller) {
8514 pVolume = volume;
8515 }
Eric Laurent25f43952010-07-28 05:40:18 -07008516 status = (*mEffectInterface)->command(mEffectInterface,
8517 EFFECT_CMD_SET_VOLUME,
8518 size,
8519 volume,
8520 &size,
8521 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008522 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8523 *left = volume[0];
8524 *right = volume[1];
8525 }
8526 }
8527 return status;
8528}
8529
8530status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8531{
8532 Mutex::Autolock _l(mLock);
8533 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008534 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8535 // audio pre processing modules on RecordThread can receive both output and
8536 // input device indication in the same call
8537 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8538 if (dev) {
8539 status_t cmdStatus;
8540 uint32_t size = sizeof(status_t);
8541
8542 status = (*mEffectInterface)->command(mEffectInterface,
8543 EFFECT_CMD_SET_DEVICE,
8544 sizeof(uint32_t),
8545 &dev,
8546 &size,
8547 &cmdStatus);
8548 if (status == NO_ERROR) {
8549 status = cmdStatus;
8550 }
8551 }
8552 dev = device & AUDIO_DEVICE_IN_ALL;
8553 if (dev) {
8554 status_t cmdStatus;
8555 uint32_t size = sizeof(status_t);
8556
8557 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8558 EFFECT_CMD_SET_INPUT_DEVICE,
8559 sizeof(uint32_t),
8560 &dev,
8561 &size,
8562 &cmdStatus);
8563 if (status2 == NO_ERROR) {
8564 status2 = cmdStatus;
8565 }
8566 if (status == NO_ERROR) {
8567 status = status2;
8568 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008569 }
8570 }
8571 return status;
8572}
8573
Glenn Kastenf78aee72012-01-04 11:00:47 -08008574status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008575{
8576 Mutex::Autolock _l(mLock);
8577 status_t status = NO_ERROR;
8578 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008579 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008580 uint32_t size = sizeof(status_t);
8581 status = (*mEffectInterface)->command(mEffectInterface,
8582 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008583 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008584 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008585 &size,
8586 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008587 if (status == NO_ERROR) {
8588 status = cmdStatus;
8589 }
8590 }
8591 return status;
8592}
8593
Eric Laurent59255e42011-07-27 19:49:51 -07008594void AudioFlinger::EffectModule::setSuspended(bool suspended)
8595{
8596 Mutex::Autolock _l(mLock);
8597 mSuspended = suspended;
8598}
Glenn Kastena3a85482012-01-04 11:01:11 -08008599
8600bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008601{
8602 Mutex::Autolock _l(mLock);
8603 return mSuspended;
8604}
8605
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008606bool AudioFlinger::EffectModule::purgeHandles()
8607{
8608 bool enabled = false;
8609 Mutex::Autolock _l(mLock);
8610 for (size_t i = 0; i < mHandles.size(); i++) {
8611 EffectHandle *handle = mHandles[i];
8612 if (handle != NULL && !handle->destroyed_l()) {
8613 handle->effect().clear();
8614 if (handle->hasControl()) {
8615 enabled = handle->enabled();
8616 }
8617 }
8618 }
8619 return enabled;
8620}
8621
Mathias Agopian65ab4712010-07-14 17:59:35 -07008622status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8623{
8624 const size_t SIZE = 256;
8625 char buffer[SIZE];
8626 String8 result;
8627
8628 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8629 result.append(buffer);
8630
8631 bool locked = tryLock(mLock);
8632 // failed to lock - AudioFlinger is probably deadlocked
8633 if (!locked) {
8634 result.append("\t\tCould not lock Fx mutex:\n");
8635 }
8636
8637 result.append("\t\tSession Status State Engine:\n");
8638 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8639 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8640 result.append(buffer);
8641
8642 result.append("\t\tDescriptor:\n");
8643 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8644 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8645 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8646 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8647 result.append(buffer);
8648 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8649 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8650 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8651 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8652 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008653 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008654 mDescriptor.apiVersion,
8655 mDescriptor.flags);
8656 result.append(buffer);
8657 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8658 mDescriptor.name);
8659 result.append(buffer);
8660 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8661 mDescriptor.implementor);
8662 result.append(buffer);
8663
8664 result.append("\t\t- Input configuration:\n");
8665 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8666 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8667 (uint32_t)mConfig.inputCfg.buffer.raw,
8668 mConfig.inputCfg.buffer.frameCount,
8669 mConfig.inputCfg.samplingRate,
8670 mConfig.inputCfg.channels,
8671 mConfig.inputCfg.format);
8672 result.append(buffer);
8673
8674 result.append("\t\t- Output configuration:\n");
8675 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8676 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8677 (uint32_t)mConfig.outputCfg.buffer.raw,
8678 mConfig.outputCfg.buffer.frameCount,
8679 mConfig.outputCfg.samplingRate,
8680 mConfig.outputCfg.channels,
8681 mConfig.outputCfg.format);
8682 result.append(buffer);
8683
8684 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8685 result.append(buffer);
8686 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8687 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008688 EffectHandle *handle = mHandles[i];
8689 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008690 handle->dump(buffer, SIZE);
8691 result.append(buffer);
8692 }
8693 }
8694
8695 result.append("\n");
8696
8697 write(fd, result.string(), result.length());
8698
8699 if (locked) {
8700 mLock.unlock();
8701 }
8702
8703 return NO_ERROR;
8704}
8705
8706// ----------------------------------------------------------------------------
8707// EffectHandle implementation
8708// ----------------------------------------------------------------------------
8709
8710#undef LOG_TAG
8711#define LOG_TAG "AudioFlinger::EffectHandle"
8712
8713AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8714 const sp<AudioFlinger::Client>& client,
8715 const sp<IEffectClient>& effectClient,
8716 int32_t priority)
8717 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008718 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008719 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008720{
Steve Block3856b092011-10-20 11:56:00 +01008721 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008722
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008723 if (client == 0) {
8724 return;
8725 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008726 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8727 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8728 if (mCblkMemory != 0) {
8729 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8730
Glenn Kastena0d68332012-01-27 16:47:15 -08008731 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008732 new(mCblk) effect_param_cblk_t();
8733 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008734 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008735 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008736 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008737 return;
8738 }
8739}
8740
8741AudioFlinger::EffectHandle::~EffectHandle()
8742{
Steve Block3856b092011-10-20 11:56:00 +01008743 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008744
8745 if (mEffect == 0) {
8746 mDestroyed = true;
8747 return;
8748 }
8749 mEffect->lock();
8750 mDestroyed = true;
8751 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008752 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008753}
8754
8755status_t AudioFlinger::EffectHandle::enable()
8756{
Steve Block3856b092011-10-20 11:56:00 +01008757 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008758 if (!mHasControl) return INVALID_OPERATION;
8759 if (mEffect == 0) return DEAD_OBJECT;
8760
Eric Laurentdb7c0792011-08-10 10:37:50 -07008761 if (mEnabled) {
8762 return NO_ERROR;
8763 }
8764
Eric Laurent59255e42011-07-27 19:49:51 -07008765 mEnabled = true;
8766
8767 sp<ThreadBase> thread = mEffect->thread().promote();
8768 if (thread != 0) {
8769 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8770 }
8771
8772 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8773 if (mEffect->suspended()) {
8774 return NO_ERROR;
8775 }
8776
Eric Laurentdb7c0792011-08-10 10:37:50 -07008777 status_t status = mEffect->setEnabled(true);
8778 if (status != NO_ERROR) {
8779 if (thread != 0) {
8780 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8781 }
8782 mEnabled = false;
8783 }
8784 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008785}
8786
8787status_t AudioFlinger::EffectHandle::disable()
8788{
Steve Block3856b092011-10-20 11:56:00 +01008789 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008790 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008791 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008792
Eric Laurentdb7c0792011-08-10 10:37:50 -07008793 if (!mEnabled) {
8794 return NO_ERROR;
8795 }
Eric Laurent59255e42011-07-27 19:49:51 -07008796 mEnabled = false;
8797
8798 if (mEffect->suspended()) {
8799 return NO_ERROR;
8800 }
8801
8802 status_t status = mEffect->setEnabled(false);
8803
8804 sp<ThreadBase> thread = mEffect->thread().promote();
8805 if (thread != 0) {
8806 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8807 }
8808
8809 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008810}
8811
8812void AudioFlinger::EffectHandle::disconnect()
8813{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008814 disconnect(true);
8815}
8816
Glenn Kasten58123c32012-02-03 10:32:24 -08008817void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008818{
Glenn Kasten58123c32012-02-03 10:32:24 -08008819 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008820 if (mEffect == 0) {
8821 return;
8822 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008823 // restore suspended effects if the disconnected handle was enabled and the last one.
8824 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008825 sp<ThreadBase> thread = mEffect->thread().promote();
8826 if (thread != 0) {
8827 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8828 }
Eric Laurent59255e42011-07-27 19:49:51 -07008829 }
8830
Mathias Agopian65ab4712010-07-14 17:59:35 -07008831 // release sp on module => module destructor can be called now
8832 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008833 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008834 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008835 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008836 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8837 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008838 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008839 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008840 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8841 mClient.clear();
8842 }
8843}
8844
Eric Laurent25f43952010-07-28 05:40:18 -07008845status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8846 uint32_t cmdSize,
8847 void *pCmdData,
8848 uint32_t *replySize,
8849 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008850{
Steve Block3856b092011-10-20 11:56:00 +01008851// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008852// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008853
8854 // only get parameter command is permitted for applications not controlling the effect
8855 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8856 return INVALID_OPERATION;
8857 }
8858 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008859 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008860
8861 // handle commands that are not forwarded transparently to effect engine
8862 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8863 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8864 // no risk to block the whole media server process or mixer threads is we are stuck here
8865 Mutex::Autolock _l(mCblk->lock);
8866 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8867 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8868 mCblk->serverIndex = 0;
8869 mCblk->clientIndex = 0;
8870 return BAD_VALUE;
8871 }
8872 status_t status = NO_ERROR;
8873 while (mCblk->serverIndex < mCblk->clientIndex) {
8874 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008875 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008876 int *p = (int *)(mBuffer + mCblk->serverIndex);
8877 int size = *p++;
8878 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008879 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008880 break;
8881 }
8882 effect_param_t *param = (effect_param_t *)p;
8883 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008884 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008885 mCblk->serverIndex += size;
8886 continue;
8887 }
Eric Laurent25f43952010-07-28 05:40:18 -07008888 uint32_t psize = sizeof(effect_param_t) +
8889 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8890 param->vsize;
8891 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8892 psize,
8893 p,
8894 &rsize,
8895 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008896 // stop at first error encountered
8897 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008898 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008899 *(int *)pReplyData = reply;
8900 break;
8901 } else if (reply != NO_ERROR) {
8902 *(int *)pReplyData = reply;
8903 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008904 }
8905 mCblk->serverIndex += size;
8906 }
8907 mCblk->serverIndex = 0;
8908 mCblk->clientIndex = 0;
8909 return status;
8910 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008911 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008912 return enable();
8913 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008914 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008915 return disable();
8916 }
8917
8918 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8919}
8920
Eric Laurent59255e42011-07-27 19:49:51 -07008921void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008922{
Steve Block3856b092011-10-20 11:56:00 +01008923 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008924
8925 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008926 mEnabled = enabled;
8927
Mathias Agopian65ab4712010-07-14 17:59:35 -07008928 if (signal && mEffectClient != 0) {
8929 mEffectClient->controlStatusChanged(hasControl);
8930 }
8931}
8932
Eric Laurent25f43952010-07-28 05:40:18 -07008933void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8934 uint32_t cmdSize,
8935 void *pCmdData,
8936 uint32_t replySize,
8937 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008938{
8939 if (mEffectClient != 0) {
8940 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8941 }
8942}
8943
8944
8945
8946void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8947{
8948 if (mEffectClient != 0) {
8949 mEffectClient->enableStatusChanged(enabled);
8950 }
8951}
8952
8953status_t AudioFlinger::EffectHandle::onTransact(
8954 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8955{
8956 return BnEffect::onTransact(code, data, reply, flags);
8957}
8958
8959
8960void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8961{
Glenn Kastena0d68332012-01-27 16:47:15 -08008962 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008963
8964 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008965 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008966 mPriority,
8967 mHasControl,
8968 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008969 mCblk ? mCblk->clientIndex : 0,
8970 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008971 );
8972
8973 if (locked) {
8974 mCblk->lock.unlock();
8975 }
8976}
8977
8978#undef LOG_TAG
8979#define LOG_TAG "AudioFlinger::EffectChain"
8980
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008981AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008982 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008983 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008984 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8985 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008986{
Dima Zavinfce7a472011-04-19 22:30:36 -07008987 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008988 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008989 return;
8990 }
8991 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8992 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008993}
8994
8995AudioFlinger::EffectChain::~EffectChain()
8996{
8997 if (mOwnInBuffer) {
8998 delete mInBuffer;
8999 }
9000
9001}
9002
Eric Laurent59255e42011-07-27 19:49:51 -07009003// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009004sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009005{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009006 size_t size = mEffects.size();
9007
9008 for (size_t i = 0; i < size; i++) {
9009 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009010 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009011 }
9012 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009013 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009014}
9015
Eric Laurent59255e42011-07-27 19:49:51 -07009016// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009017sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009018{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009019 size_t size = mEffects.size();
9020
9021 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009022 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9023 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009024 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009025 }
9026 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009027 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009028}
9029
Eric Laurent59255e42011-07-27 19:49:51 -07009030// getEffectFromType_l() must be called with ThreadBase::mLock held
9031sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9032 const effect_uuid_t *type)
9033{
Eric Laurent59255e42011-07-27 19:49:51 -07009034 size_t size = mEffects.size();
9035
9036 for (size_t i = 0; i < size; i++) {
9037 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009038 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009039 }
9040 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009041 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009042}
9043
Eric Laurent91b14c42012-05-30 12:30:29 -07009044void AudioFlinger::EffectChain::clearInputBuffer()
9045{
9046 Mutex::Autolock _l(mLock);
9047 sp<ThreadBase> thread = mThread.promote();
9048 if (thread == 0) {
9049 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9050 return;
9051 }
9052 clearInputBuffer_l(thread);
9053}
9054
9055// Must be called with EffectChain::mLock locked
9056void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9057{
9058 size_t numSamples = thread->frameCount() * thread->channelCount();
9059 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9060
9061}
9062
Mathias Agopian65ab4712010-07-14 17:59:35 -07009063// Must be called with EffectChain::mLock locked
9064void AudioFlinger::EffectChain::process_l()
9065{
Eric Laurentdac69112010-09-28 14:09:57 -07009066 sp<ThreadBase> thread = mThread.promote();
9067 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009068 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009069 return;
9070 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009071 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9072 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009073 // always process effects unless no more tracks are on the session and the effect tail
9074 // has been rendered
9075 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009076 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009077 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009078
Eric Laurent544fe9b2011-11-11 15:42:52 -08009079 if (!tracksOnSession && mTailBufferCount == 0) {
9080 doProcess = false;
9081 }
9082
9083 if (activeTrackCnt() == 0) {
9084 // if no track is active and the effect tail has not been rendered,
9085 // the input buffer must be cleared here as the mixer process will not do it
9086 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009087 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009088 if (mTailBufferCount > 0) {
9089 mTailBufferCount--;
9090 }
9091 }
9092 }
Eric Laurentdac69112010-09-28 14:09:57 -07009093 }
9094
Mathias Agopian65ab4712010-07-14 17:59:35 -07009095 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009096 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009097 for (size_t i = 0; i < size; i++) {
9098 mEffects[i]->process();
9099 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009100 }
9101 for (size_t i = 0; i < size; i++) {
9102 mEffects[i]->updateState();
9103 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009104}
9105
Eric Laurentcab11242010-07-15 12:50:15 -07009106// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009107status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009108{
9109 effect_descriptor_t desc = effect->desc();
9110 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9111
9112 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009113 effect->setChain(this);
9114 sp<ThreadBase> thread = mThread.promote();
9115 if (thread == 0) {
9116 return NO_INIT;
9117 }
9118 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009119
9120 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9121 // Auxiliary effects are inserted at the beginning of mEffects vector as
9122 // they are processed first and accumulated in chain input buffer
9123 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009124
Mathias Agopian65ab4712010-07-14 17:59:35 -07009125 // the input buffer for auxiliary effect contains mono samples in
9126 // 32 bit format. This is to avoid saturation in AudoMixer
9127 // accumulation stage. Saturation is done in EffectModule::process() before
9128 // calling the process in effect engine
9129 size_t numSamples = thread->frameCount();
9130 int32_t *buffer = new int32_t[numSamples];
9131 memset(buffer, 0, numSamples * sizeof(int32_t));
9132 effect->setInBuffer((int16_t *)buffer);
9133 // auxiliary effects output samples to chain input buffer for further processing
9134 // by insert effects
9135 effect->setOutBuffer(mInBuffer);
9136 } else {
9137 // Insert effects are inserted at the end of mEffects vector as they are processed
9138 // after track and auxiliary effects.
9139 // Insert effect order as a function of indicated preference:
9140 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9141 // another effect is present
9142 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9143 // last effect claiming first position
9144 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9145 // first effect claiming last position
9146 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9147 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9148 // already present
9149
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009150 size_t size = mEffects.size();
9151 size_t idx_insert = size;
9152 ssize_t idx_insert_first = -1;
9153 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009154
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009155 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009156 effect_descriptor_t d = mEffects[i]->desc();
9157 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9158 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9159 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9160 // check invalid effect chaining combinations
9161 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9162 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009163 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009164 return INVALID_OPERATION;
9165 }
9166 // remember position of first insert effect and by default
9167 // select this as insert position for new effect
9168 if (idx_insert == size) {
9169 idx_insert = i;
9170 }
9171 // remember position of last insert effect claiming
9172 // first position
9173 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9174 idx_insert_first = i;
9175 }
9176 // remember position of first insert effect claiming
9177 // last position
9178 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9179 idx_insert_last == -1) {
9180 idx_insert_last = i;
9181 }
9182 }
9183 }
9184
9185 // modify idx_insert from first position if needed
9186 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9187 if (idx_insert_last != -1) {
9188 idx_insert = idx_insert_last;
9189 } else {
9190 idx_insert = size;
9191 }
9192 } else {
9193 if (idx_insert_first != -1) {
9194 idx_insert = idx_insert_first + 1;
9195 }
9196 }
9197
9198 // always read samples from chain input buffer
9199 effect->setInBuffer(mInBuffer);
9200
9201 // if last effect in the chain, output samples to chain
9202 // output buffer, otherwise to chain input buffer
9203 if (idx_insert == size) {
9204 if (idx_insert != 0) {
9205 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9206 mEffects[idx_insert-1]->configure();
9207 }
9208 effect->setOutBuffer(mOutBuffer);
9209 } else {
9210 effect->setOutBuffer(mInBuffer);
9211 }
9212 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009213
Steve Block3856b092011-10-20 11:56:00 +01009214 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009215 }
9216 effect->configure();
9217 return NO_ERROR;
9218}
9219
Eric Laurentcab11242010-07-15 12:50:15 -07009220// removeEffect_l() must be called with PlaybackThread::mLock held
9221size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009222{
9223 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009224 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009225 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9226
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009227 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009228 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009229 // calling stop here will remove pre-processing effect from the audio HAL.
9230 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9231 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009232 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9233 mEffects[i]->state() == EffectModule::STOPPING) {
9234 mEffects[i]->stop();
9235 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009236 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9237 delete[] effect->inBuffer();
9238 } else {
9239 if (i == size - 1 && i != 0) {
9240 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9241 mEffects[i - 1]->configure();
9242 }
9243 }
9244 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009245 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009246 break;
9247 }
9248 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009249
9250 return mEffects.size();
9251}
9252
Eric Laurentcab11242010-07-15 12:50:15 -07009253// setDevice_l() must be called with PlaybackThread::mLock held
9254void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009255{
9256 size_t size = mEffects.size();
9257 for (size_t i = 0; i < size; i++) {
9258 mEffects[i]->setDevice(device);
9259 }
9260}
9261
Eric Laurentcab11242010-07-15 12:50:15 -07009262// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009263void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009264{
9265 size_t size = mEffects.size();
9266 for (size_t i = 0; i < size; i++) {
9267 mEffects[i]->setMode(mode);
9268 }
9269}
9270
Eric Laurentcab11242010-07-15 12:50:15 -07009271// setVolume_l() must be called with PlaybackThread::mLock held
9272bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009273{
9274 uint32_t newLeft = *left;
9275 uint32_t newRight = *right;
9276 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009277 int ctrlIdx = -1;
9278 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009279
Eric Laurentcab11242010-07-15 12:50:15 -07009280 // first update volume controller
9281 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009282 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009283 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9284 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009285 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009286 break;
9287 }
9288 }
9289
9290 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009291 if (hasControl) {
9292 *left = mNewLeftVolume;
9293 *right = mNewRightVolume;
9294 }
9295 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009296 }
9297
9298 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009299 mLeftVolume = newLeft;
9300 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009301
9302 // second get volume update from volume controller
9303 if (ctrlIdx >= 0) {
9304 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009305 mNewLeftVolume = newLeft;
9306 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009307 }
9308 // then indicate volume to all other effects in chain.
9309 // Pass altered volume to effects before volume controller
9310 // and requested volume to effects after controller
9311 uint32_t lVol = newLeft;
9312 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009313
Mathias Agopian65ab4712010-07-14 17:59:35 -07009314 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009315 if ((int)i == ctrlIdx) continue;
9316 // this also works for ctrlIdx == -1 when there is no volume controller
9317 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009318 lVol = *left;
9319 rVol = *right;
9320 }
9321 mEffects[i]->setVolume(&lVol, &rVol, false);
9322 }
9323 *left = newLeft;
9324 *right = newRight;
9325
9326 return hasControl;
9327}
9328
Mathias Agopian65ab4712010-07-14 17:59:35 -07009329status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9330{
9331 const size_t SIZE = 256;
9332 char buffer[SIZE];
9333 String8 result;
9334
9335 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9336 result.append(buffer);
9337
9338 bool locked = tryLock(mLock);
9339 // failed to lock - AudioFlinger is probably deadlocked
9340 if (!locked) {
9341 result.append("\tCould not lock mutex:\n");
9342 }
9343
Eric Laurentcab11242010-07-15 12:50:15 -07009344 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9345 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009346 mEffects.size(),
9347 (uint32_t)mInBuffer,
9348 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009349 mActiveTrackCnt);
9350 result.append(buffer);
9351 write(fd, result.string(), result.size());
9352
9353 for (size_t i = 0; i < mEffects.size(); ++i) {
9354 sp<EffectModule> effect = mEffects[i];
9355 if (effect != 0) {
9356 effect->dump(fd, args);
9357 }
9358 }
9359
9360 if (locked) {
9361 mLock.unlock();
9362 }
9363
9364 return NO_ERROR;
9365}
9366
Eric Laurent59255e42011-07-27 19:49:51 -07009367// must be called with ThreadBase::mLock held
9368void AudioFlinger::EffectChain::setEffectSuspended_l(
9369 const effect_uuid_t *type, bool suspend)
9370{
9371 sp<SuspendedEffectDesc> desc;
9372 // use effect type UUID timelow as key as there is no real risk of identical
9373 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009374 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009375 if (suspend) {
9376 if (index >= 0) {
9377 desc = mSuspendedEffects.valueAt(index);
9378 } else {
9379 desc = new SuspendedEffectDesc();
9380 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9381 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009382 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009383 }
9384 if (desc->mRefCount++ == 0) {
9385 sp<EffectModule> effect = getEffectIfEnabled(type);
9386 if (effect != 0) {
9387 desc->mEffect = effect;
9388 effect->setSuspended(true);
9389 effect->setEnabled(false);
9390 }
9391 }
9392 } else {
9393 if (index < 0) {
9394 return;
9395 }
9396 desc = mSuspendedEffects.valueAt(index);
9397 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009398 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009399 desc->mRefCount = 1;
9400 }
9401 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009402 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009403 if (desc->mEffect != 0) {
9404 sp<EffectModule> effect = desc->mEffect.promote();
9405 if (effect != 0) {
9406 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009407 effect->lock();
9408 EffectHandle *handle = effect->controlHandle_l();
9409 if (handle != NULL && !handle->destroyed_l()) {
9410 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009411 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009412 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009413 }
9414 desc->mEffect.clear();
9415 }
9416 mSuspendedEffects.removeItemsAt(index);
9417 }
9418 }
9419}
9420
9421// must be called with ThreadBase::mLock held
9422void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9423{
9424 sp<SuspendedEffectDesc> desc;
9425
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009426 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009427 if (suspend) {
9428 if (index >= 0) {
9429 desc = mSuspendedEffects.valueAt(index);
9430 } else {
9431 desc = new SuspendedEffectDesc();
9432 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009433 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009434 }
9435 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009436 Vector< sp<EffectModule> > effects;
9437 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009438 for (size_t i = 0; i < effects.size(); i++) {
9439 setEffectSuspended_l(&effects[i]->desc().type, true);
9440 }
9441 }
9442 } else {
9443 if (index < 0) {
9444 return;
9445 }
9446 desc = mSuspendedEffects.valueAt(index);
9447 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009448 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009449 desc->mRefCount = 1;
9450 }
9451 if (--desc->mRefCount == 0) {
9452 Vector<const effect_uuid_t *> types;
9453 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9454 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9455 continue;
9456 }
9457 types.add(&mSuspendedEffects.valueAt(i)->mType);
9458 }
9459 for (size_t i = 0; i < types.size(); i++) {
9460 setEffectSuspended_l(types[i], false);
9461 }
Steve Block3856b092011-10-20 11:56:00 +01009462 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009463 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9464 }
9465 }
9466}
9467
Eric Laurent6bffdb82011-09-23 08:40:41 -07009468
9469// The volume effect is used for automated tests only
9470#ifndef OPENSL_ES_H_
9471static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9472 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9473const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9474#endif //OPENSL_ES_H_
9475
Eric Laurentdb7c0792011-08-10 10:37:50 -07009476bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9477{
9478 // auxiliary effects and visualizer are never suspended on output mix
9479 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9480 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009481 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9482 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009483 return false;
9484 }
9485 return true;
9486}
9487
Glenn Kastend0539712012-01-30 12:56:03 -08009488void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009489{
Glenn Kastend0539712012-01-30 12:56:03 -08009490 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009491 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009492 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9493 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009494 }
Eric Laurent59255e42011-07-27 19:49:51 -07009495 }
Eric Laurent59255e42011-07-27 19:49:51 -07009496}
9497
9498sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9499 const effect_uuid_t *type)
9500{
Glenn Kasten090f0192012-01-30 13:00:02 -08009501 sp<EffectModule> effect = getEffectFromType_l(type);
9502 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009503}
9504
9505void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9506 bool enabled)
9507{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009508 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009509 if (enabled) {
9510 if (index < 0) {
9511 // if the effect is not suspend check if all effects are suspended
9512 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9513 if (index < 0) {
9514 return;
9515 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009516 if (!isEffectEligibleForSuspend(effect->desc())) {
9517 return;
9518 }
Eric Laurent59255e42011-07-27 19:49:51 -07009519 setEffectSuspended_l(&effect->desc().type, enabled);
9520 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009521 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009522 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009523 return;
9524 }
Eric Laurent59255e42011-07-27 19:49:51 -07009525 }
Steve Block3856b092011-10-20 11:56:00 +01009526 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009527 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009528 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9529 // if effect is requested to suspended but was not yet enabled, supend it now.
9530 if (desc->mEffect == 0) {
9531 desc->mEffect = effect;
9532 effect->setEnabled(false);
9533 effect->setSuspended(true);
9534 }
9535 } else {
9536 if (index < 0) {
9537 return;
9538 }
Steve Block3856b092011-10-20 11:56:00 +01009539 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009540 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009541 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9542 desc->mEffect.clear();
9543 effect->setSuspended(false);
9544 }
9545}
9546
Mathias Agopian65ab4712010-07-14 17:59:35 -07009547#undef LOG_TAG
9548#define LOG_TAG "AudioFlinger"
9549
9550// ----------------------------------------------------------------------------
9551
9552status_t AudioFlinger::onTransact(
9553 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9554{
9555 return BnAudioFlinger::onTransact(code, data, reply, flags);
9556}
9557
Mathias Agopian65ab4712010-07-14 17:59:35 -07009558}; // namespace android