blob: e2b29f71d4a6bcde1be995fa6a0c6fad98e94b1d [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{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700981 Mutex::Autolock _l(mLock);
982
983 RecordThread *recordThread = checkRecordThread_l(ioHandle);
984 if (recordThread != NULL) {
985 return recordThread->getInputFramesLost();
986 }
987 return 0;
988}
989
990status_t AudioFlinger::setVoiceVolume(float value)
991{
Eric Laurenta1884f92011-08-23 08:25:03 -0700992 status_t ret = initCheck();
993 if (ret != NO_ERROR) {
994 return ret;
995 }
996
Mathias Agopian65ab4712010-07-14 17:59:35 -0700997 // check calling permissions
998 if (!settingsAllowed()) {
999 return PERMISSION_DENIED;
1000 }
1001
1002 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001003 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -07001004 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001005 mHardwareStatus = AUDIO_HW_IDLE;
1006
1007 return ret;
1008}
1009
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001010status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1011 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001012{
1013 status_t status;
1014
1015 Mutex::Autolock _l(mLock);
1016
1017 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1018 if (playbackThread != NULL) {
1019 return playbackThread->getRenderPosition(halFrames, dspFrames);
1020 }
1021
1022 return BAD_VALUE;
1023}
1024
1025void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1026{
1027
1028 Mutex::Autolock _l(mLock);
1029
Glenn Kastenbb001922012-02-03 11:10:26 -08001030 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001031 if (mNotificationClients.indexOfKey(pid) < 0) {
1032 sp<NotificationClient> notificationClient = new NotificationClient(this,
1033 client,
1034 pid);
Steve Block3856b092011-10-20 11:56:00 +01001035 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001036
1037 mNotificationClients.add(pid, notificationClient);
1038
1039 sp<IBinder> binder = client->asBinder();
1040 binder->linkToDeath(notificationClient);
1041
1042 // the config change is always sent from playback or record threads to avoid deadlock
1043 // with AudioSystem::gLock
1044 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1045 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1046 }
1047
1048 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1049 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1050 }
1051 }
1052}
1053
1054void AudioFlinger::removeNotificationClient(pid_t pid)
1055{
1056 Mutex::Autolock _l(mLock);
1057
Glenn Kastena3b09252012-01-20 09:19:01 -08001058 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001059
Steve Block3856b092011-10-20 11:56:00 +01001060 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001061 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001062 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001063 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001064 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001065 ALOGV(" pid %d @ %d", ref->mPid, i);
1066 if (ref->mPid == pid) {
1067 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001068 mAudioSessionRefs.removeAt(i);
1069 delete ref;
1070 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001071 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001072 } else {
1073 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001074 }
1075 }
1076 if (removed) {
1077 purgeStaleEffects_l();
1078 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001079}
1080
1081// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001082void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001083{
1084 size_t size = mNotificationClients.size();
1085 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001086 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1087 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001088 }
1089}
1090
1091// removeClient_l() must be called with AudioFlinger::mLock held
1092void AudioFlinger::removeClient_l(pid_t pid)
1093{
Steve Block3856b092011-10-20 11:56:00 +01001094 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001095 mClients.removeItem(pid);
1096}
1097
Eric Laurent717e1282012-06-29 16:36:52 -07001098// getEffectThread_l() must be called with AudioFlinger::mLock held
1099sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1100{
1101 sp<PlaybackThread> thread;
1102
1103 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1104 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1105 ALOG_ASSERT(thread == 0);
1106 thread = mPlaybackThreads.valueAt(i);
1107 }
1108 }
1109
1110 return thread;
1111}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001112
1113// ----------------------------------------------------------------------------
1114
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001115AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1116 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001117 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001118 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001119 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001120 // mChannelMask
1121 mChannelCount(0),
1122 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1123 mParamStatus(NO_ERROR),
Glenn Kasten94479fd2012-07-09 15:39:54 -07001124 mStandby(false), mDevice((audio_devices_t) device), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001125 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001126{
1127}
1128
1129AudioFlinger::ThreadBase::~ThreadBase()
1130{
1131 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001132 // do not lock the mutex in destructor
1133 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001134 if (mPowerManager != 0) {
1135 sp<IBinder> binder = mPowerManager->asBinder();
1136 binder->unlinkToDeath(mDeathRecipient);
1137 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001138}
1139
1140void AudioFlinger::ThreadBase::exit()
1141{
Steve Block3856b092011-10-20 11:56:00 +01001142 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001143 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001144 // This lock prevents the following race in thread (uniprocessor for illustration):
1145 // if (!exitPending()) {
1146 // // context switch from here to exit()
1147 // // exit() calls requestExit(), what exitPending() observes
1148 // // exit() calls signal(), which is dropped since no waiters
1149 // // context switch back from exit() to here
1150 // mWaitWorkCV.wait(...);
1151 // // now thread is hung
1152 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001153 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001154 requestExit();
1155 mWaitWorkCV.signal();
1156 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001157 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1158 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001159 requestExitAndWait();
1160}
1161
Mathias Agopian65ab4712010-07-14 17:59:35 -07001162status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1163{
1164 status_t status;
1165
Steve Block3856b092011-10-20 11:56:00 +01001166 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001167 Mutex::Autolock _l(mLock);
1168
1169 mNewParameters.add(keyValuePairs);
1170 mWaitWorkCV.signal();
1171 // wait condition with timeout in case the thread loop has exited
1172 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001173 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001174 status = mParamStatus;
1175 mWaitWorkCV.signal();
1176 } else {
1177 status = TIMED_OUT;
1178 }
1179 return status;
1180}
1181
1182void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1183{
1184 Mutex::Autolock _l(mLock);
1185 sendConfigEvent_l(event, param);
1186}
1187
1188// sendConfigEvent_l() must be called with ThreadBase::mLock held
1189void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1190{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001191 ConfigEvent configEvent;
1192 configEvent.mEvent = event;
1193 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001194 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001195 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001196 mWaitWorkCV.signal();
1197}
1198
1199void AudioFlinger::ThreadBase::processConfigEvents()
1200{
1201 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001202 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001203 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001204 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001205 mConfigEvents.removeAt(0);
1206 // release mLock before locking AudioFlinger mLock: lock order is always
1207 // AudioFlinger then ThreadBase to avoid cross deadlock
1208 mLock.unlock();
1209 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001210 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001211 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001212 mLock.lock();
1213 }
1214 mLock.unlock();
1215}
1216
1217status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1218{
1219 const size_t SIZE = 256;
1220 char buffer[SIZE];
1221 String8 result;
1222
1223 bool locked = tryLock(mLock);
1224 if (!locked) {
1225 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1226 write(fd, buffer, strlen(buffer));
1227 }
1228
Eric Laurent612bbb52012-03-14 15:03:26 -07001229 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1230 result.append(buffer);
1231 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1232 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001233 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1234 result.append(buffer);
1235 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1236 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001237 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1238 result.append(buffer);
1239 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001240 result.append(buffer);
1241 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1242 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001243 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1244 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001245 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1246 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001247 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001248 result.append(buffer);
1249
1250 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1251 result.append(buffer);
1252 result.append(" Index Command");
1253 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1254 snprintf(buffer, SIZE, "\n %02d ", i);
1255 result.append(buffer);
1256 result.append(mNewParameters[i]);
1257 }
1258
1259 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1260 result.append(buffer);
1261 snprintf(buffer, SIZE, " Index event param\n");
1262 result.append(buffer);
1263 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001264 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001265 result.append(buffer);
1266 }
1267 result.append("\n");
1268
1269 write(fd, result.string(), result.size());
1270
1271 if (locked) {
1272 mLock.unlock();
1273 }
1274 return NO_ERROR;
1275}
1276
Eric Laurent1d2bff02011-07-24 17:49:51 -07001277status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1278{
1279 const size_t SIZE = 256;
1280 char buffer[SIZE];
1281 String8 result;
1282
1283 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1284 write(fd, buffer, strlen(buffer));
1285
1286 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1287 sp<EffectChain> chain = mEffectChains[i];
1288 if (chain != 0) {
1289 chain->dump(fd, args);
1290 }
1291 }
1292 return NO_ERROR;
1293}
1294
Eric Laurentfeb0db62011-07-22 09:04:31 -07001295void AudioFlinger::ThreadBase::acquireWakeLock()
1296{
1297 Mutex::Autolock _l(mLock);
1298 acquireWakeLock_l();
1299}
1300
1301void AudioFlinger::ThreadBase::acquireWakeLock_l()
1302{
1303 if (mPowerManager == 0) {
1304 // use checkService() to avoid blocking if power service is not up yet
1305 sp<IBinder> binder =
1306 defaultServiceManager()->checkService(String16("power"));
1307 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001308 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001309 } else {
1310 mPowerManager = interface_cast<IPowerManager>(binder);
1311 binder->linkToDeath(mDeathRecipient);
1312 }
1313 }
1314 if (mPowerManager != 0) {
1315 sp<IBinder> binder = new BBinder();
1316 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1317 binder,
1318 String16(mName));
1319 if (status == NO_ERROR) {
1320 mWakeLockToken = binder;
1321 }
Steve Block3856b092011-10-20 11:56:00 +01001322 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001323 }
1324}
1325
1326void AudioFlinger::ThreadBase::releaseWakeLock()
1327{
1328 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001329 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001330}
1331
1332void AudioFlinger::ThreadBase::releaseWakeLock_l()
1333{
1334 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001335 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001336 if (mPowerManager != 0) {
1337 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1338 }
1339 mWakeLockToken.clear();
1340 }
1341}
1342
1343void AudioFlinger::ThreadBase::clearPowerManager()
1344{
1345 Mutex::Autolock _l(mLock);
1346 releaseWakeLock_l();
1347 mPowerManager.clear();
1348}
1349
1350void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1351{
1352 sp<ThreadBase> thread = mThread.promote();
1353 if (thread != 0) {
1354 thread->clearPowerManager();
1355 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001356 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001357}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001358
Eric Laurent59255e42011-07-27 19:49:51 -07001359void AudioFlinger::ThreadBase::setEffectSuspended(
1360 const effect_uuid_t *type, bool suspend, int sessionId)
1361{
1362 Mutex::Autolock _l(mLock);
1363 setEffectSuspended_l(type, suspend, sessionId);
1364}
1365
1366void AudioFlinger::ThreadBase::setEffectSuspended_l(
1367 const effect_uuid_t *type, bool suspend, int sessionId)
1368{
Glenn Kasten090f0192012-01-30 13:00:02 -08001369 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001370 if (chain != 0) {
1371 if (type != NULL) {
1372 chain->setEffectSuspended_l(type, suspend);
1373 } else {
1374 chain->setEffectSuspendedAll_l(suspend);
1375 }
1376 }
1377
1378 updateSuspendedSessions_l(type, suspend, sessionId);
1379}
1380
1381void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1382{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001383 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001384 if (index < 0) {
1385 return;
1386 }
1387
1388 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1389 mSuspendedSessions.editValueAt(index);
1390
1391 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001392 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001393 for (int j = 0; j < desc->mRefCount; j++) {
1394 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1395 chain->setEffectSuspendedAll_l(true);
1396 } else {
Steve Block3856b092011-10-20 11:56:00 +01001397 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001398 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001399 chain->setEffectSuspended_l(&desc->mType, true);
1400 }
1401 }
1402 }
1403}
1404
Eric Laurent59255e42011-07-27 19:49:51 -07001405void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1406 bool suspend,
1407 int sessionId)
1408{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001409 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001410
1411 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1412
1413 if (suspend) {
1414 if (index >= 0) {
1415 sessionEffects = mSuspendedSessions.editValueAt(index);
1416 } else {
1417 mSuspendedSessions.add(sessionId, sessionEffects);
1418 }
1419 } else {
1420 if (index < 0) {
1421 return;
1422 }
1423 sessionEffects = mSuspendedSessions.editValueAt(index);
1424 }
1425
1426
1427 int key = EffectChain::kKeyForSuspendAll;
1428 if (type != NULL) {
1429 key = type->timeLow;
1430 }
1431 index = sessionEffects.indexOfKey(key);
1432
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001433 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001434 if (suspend) {
1435 if (index >= 0) {
1436 desc = sessionEffects.valueAt(index);
1437 } else {
1438 desc = new SuspendedSessionDesc();
1439 if (type != NULL) {
1440 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1441 }
1442 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001443 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001444 }
1445 desc->mRefCount++;
1446 } else {
1447 if (index < 0) {
1448 return;
1449 }
1450 desc = sessionEffects.valueAt(index);
1451 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001452 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001453 sessionEffects.removeItemsAt(index);
1454 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001455 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001456 sessionId);
1457 mSuspendedSessions.removeItem(sessionId);
1458 }
1459 }
1460 }
1461 if (!sessionEffects.isEmpty()) {
1462 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1463 }
1464}
1465
1466void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1467 bool enabled,
1468 int sessionId)
1469{
1470 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001471 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1472}
Eric Laurent59255e42011-07-27 19:49:51 -07001473
Eric Laurenta85a74a2011-10-19 11:44:54 -07001474void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1475 bool enabled,
1476 int sessionId)
1477{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001478 if (mType != RECORD) {
1479 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1480 // another session. This gives the priority to well behaved effect control panels
1481 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001482 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1483 // global effects
1484 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001485 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1486 }
1487 }
Eric Laurent59255e42011-07-27 19:49:51 -07001488
1489 sp<EffectChain> chain = getEffectChain_l(sessionId);
1490 if (chain != 0) {
1491 chain->checkSuspendOnEffectEnabled(effect, enabled);
1492 }
1493}
1494
Mathias Agopian65ab4712010-07-14 17:59:35 -07001495// ----------------------------------------------------------------------------
1496
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001497AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1498 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001499 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001500 uint32_t device,
1501 type_t type)
1502 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001503 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1504 // Assumes constructor is called by AudioFlinger with it's mLock held,
1505 // but it would be safer to explicitly pass initial masterMute as parameter
1506 mMasterMute(audioFlinger->masterMute_l()),
1507 // mStreamTypes[] initialized in constructor body
1508 mOutput(output),
1509 // Assumes constructor is called by AudioFlinger with it's mLock held,
1510 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001511 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001512 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001513 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001514 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001515 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001516 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001517 // index 0 is reserved for normal mixer's submix
1518 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001519{
Glenn Kasten480b4682012-02-28 12:30:08 -08001520 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001521
Mathias Agopian65ab4712010-07-14 17:59:35 -07001522 readOutputParameters();
1523
Glenn Kasten263709e2012-01-06 08:40:01 -08001524 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001525 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1526 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1527 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001528 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1529 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001530 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001531 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1532 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001533}
1534
1535AudioFlinger::PlaybackThread::~PlaybackThread()
1536{
1537 delete [] mMixBuffer;
1538}
1539
1540status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1541{
1542 dumpInternals(fd, args);
1543 dumpTracks(fd, args);
1544 dumpEffectChains(fd, args);
1545 return NO_ERROR;
1546}
1547
1548status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1549{
1550 const size_t SIZE = 256;
1551 char buffer[SIZE];
1552 String8 result;
1553
Glenn Kasten58912562012-04-03 10:45:00 -07001554 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1555 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1556 const stream_type_t *st = &mStreamTypes[i];
1557 if (i > 0) {
1558 result.appendFormat(", ");
1559 }
1560 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1561 if (st->mute) {
1562 result.append("M");
1563 }
1564 }
1565 result.append("\n");
1566 write(fd, result.string(), result.length());
1567 result.clear();
1568
Mathias Agopian65ab4712010-07-14 17:59:35 -07001569 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1570 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001571 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001572 for (size_t i = 0; i < mTracks.size(); ++i) {
1573 sp<Track> track = mTracks[i];
1574 if (track != 0) {
1575 track->dump(buffer, SIZE);
1576 result.append(buffer);
1577 }
1578 }
1579
1580 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1581 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001582 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001583 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001584 sp<Track> track = mActiveTracks[i].promote();
1585 if (track != 0) {
1586 track->dump(buffer, SIZE);
1587 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001588 }
1589 }
1590 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001591
1592 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1593 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1594 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1595 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1596
Mathias Agopian65ab4712010-07-14 17:59:35 -07001597 return NO_ERROR;
1598}
1599
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1601{
1602 const size_t SIZE = 256;
1603 char buffer[SIZE];
1604 String8 result;
1605
1606 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1607 result.append(buffer);
1608 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1609 result.append(buffer);
1610 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1611 result.append(buffer);
1612 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1613 result.append(buffer);
1614 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1615 result.append(buffer);
1616 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1617 result.append(buffer);
1618 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1619 result.append(buffer);
1620 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001621 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001622
1623 dumpBase(fd, args);
1624
1625 return NO_ERROR;
1626}
1627
1628// Thread virtuals
1629status_t AudioFlinger::PlaybackThread::readyToRun()
1630{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001631 status_t status = initCheck();
1632 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001633 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001634 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001635 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001636 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001637 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001638}
1639
1640void AudioFlinger::PlaybackThread::onFirstRef()
1641{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001642 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001643}
1644
1645// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001646sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001647 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001648 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001649 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001650 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001651 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001652 int frameCount,
1653 const sp<IMemory>& sharedBuffer,
1654 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001655 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001656 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001657 status_t *status)
1658{
1659 sp<Track> track;
1660 status_t lStatus;
1661
Glenn Kasten73d22752012-03-19 13:38:30 -07001662 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1663
1664 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001665 if (flags & IAudioFlinger::TRACK_FAST) {
1666 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001667 // not timed
1668 (!isTimed) &&
1669 // either of these use cases:
1670 (
1671 // use case 1: shared buffer with any frame count
1672 (
1673 (sharedBuffer != 0)
1674 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001675 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001676 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001677 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001678 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001679 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001680 )
1681 ) &&
1682 // PCM data
1683 audio_is_linear_pcm(format) &&
1684 // mono or stereo
1685 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1686 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001687#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001688 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001689 (sampleRate == mSampleRate) &&
1690#endif
1691 // normal mixer has an associated fast mixer
1692 hasFastMixer() &&
1693 // there are sufficient fast track slots available
1694 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001695 // FIXME test that MixerThread for this fast track has a capable output HAL
1696 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001697 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001698 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1699 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001700 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001701 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001702 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001703 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001704 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001705 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten254af182012-07-03 14:59:05 -07001706 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001707 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1708 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1709 audio_is_linear_pcm(format),
1710 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001711 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001712 // For compatibility with AudioTrack calculation, buffer depth is forced
1713 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1714 // This is probably too conservative, but legacy application code may depend on it.
1715 // If you change this calculation, also review the start threshold which is related.
1716 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1717 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1718 if (minBufCount < 2) {
1719 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001720 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001721 int minFrameCount = mNormalFrameCount * minBufCount;
1722 if (frameCount < minFrameCount) {
1723 frameCount = minFrameCount;
1724 }
1725 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001726 }
1727
Mathias Agopian65ab4712010-07-14 17:59:35 -07001728 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001729 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1730 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001731 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001732 "for output %p with format %d",
1733 sampleRate, format, channelMask, mOutput, mFormat);
1734 lStatus = BAD_VALUE;
1735 goto Exit;
1736 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001737 }
1738 } else {
1739 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1740 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001741 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742 lStatus = BAD_VALUE;
1743 goto Exit;
1744 }
1745 }
1746
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001747 lStatus = initCheck();
1748 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001749 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001750 goto Exit;
1751 }
1752
1753 { // scope for mLock
1754 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001755
1756 // all tracks in same audio session must share the same routing strategy otherwise
1757 // conflicts will happen when tracks are moved from one output to another by audio policy
1758 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001759 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001760 for (size_t i = 0; i < mTracks.size(); ++i) {
1761 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001762 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001763 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001764 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001765 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001766 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001767 lStatus = BAD_VALUE;
1768 goto Exit;
1769 }
1770 }
1771 }
1772
John Grossman4ff14ba2012-02-08 16:37:41 -08001773 if (!isTimed) {
1774 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001775 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001776 } else {
1777 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1778 channelMask, frameCount, sharedBuffer, sessionId);
1779 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001780 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001781 lStatus = NO_MEMORY;
1782 goto Exit;
1783 }
1784 mTracks.add(track);
1785
1786 sp<EffectChain> chain = getEffectChain_l(sessionId);
1787 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001788 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001789 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001790 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001791 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001792 }
1793 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001794
Glenn Kasten3acbd052012-02-28 10:39:56 -08001795 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1796 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1797 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1798 // so ask activity manager to do this on our behalf
1799 int err = requestPriority(callingPid, tid, 1);
1800 if (err != 0) {
1801 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1802 1, callingPid, tid, err);
1803 }
1804 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001805
Mathias Agopian65ab4712010-07-14 17:59:35 -07001806 lStatus = NO_ERROR;
1807
1808Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001809 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001810 *status = lStatus;
1811 }
1812 return track;
1813}
1814
Eric Laurente737cda2012-05-22 18:55:44 -07001815uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1816{
1817 if (mFastMixer != NULL) {
1818 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1819 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1820 }
1821 return latency;
1822}
1823
1824uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1825{
1826 return latency;
1827}
1828
Mathias Agopian65ab4712010-07-14 17:59:35 -07001829uint32_t AudioFlinger::PlaybackThread::latency() const
1830{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001831 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001832 return latency_l();
1833}
1834uint32_t AudioFlinger::PlaybackThread::latency_l() const
1835{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001836 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001837 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001838 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001839 return 0;
1840 }
1841}
1842
Glenn Kasten6637baa2012-01-09 09:40:36 -08001843void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001844{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001845 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001846 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001847}
1848
Glenn Kasten6637baa2012-01-09 09:40:36 -08001849void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001850{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001851 Mutex::Autolock _l(mLock);
1852 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853}
1854
Glenn Kasten6637baa2012-01-09 09:40:36 -08001855void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001857 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001858 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001859}
1860
Glenn Kasten6637baa2012-01-09 09:40:36 -08001861void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001862{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001863 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001864 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001865}
1866
Glenn Kastenfff6d712012-01-12 16:38:12 -08001867float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001868{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001869 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001870 return mStreamTypes[stream].volume;
1871}
1872
Mathias Agopian65ab4712010-07-14 17:59:35 -07001873// addTrack_l() must be called with ThreadBase::mLock held
1874status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1875{
1876 status_t status = ALREADY_EXISTS;
1877
1878 // set retry count for buffer fill
1879 track->mRetryCount = kMaxTrackStartupRetries;
1880 if (mActiveTracks.indexOf(track) < 0) {
1881 // the track is newly added, make sure it fills up all its
1882 // buffers before playing. This is to ensure the client will
1883 // effectively get the latency it requested.
1884 track->mFillingUpStatus = Track::FS_FILLING;
1885 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001886 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001887 mActiveTracks.add(track);
1888 if (track->mainBuffer() != mMixBuffer) {
1889 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1890 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001891 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001892 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001893 }
1894 }
1895
1896 status = NO_ERROR;
1897 }
1898
Steve Block3856b092011-10-20 11:56:00 +01001899 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001900 mWaitWorkCV.broadcast();
1901
1902 return status;
1903}
1904
1905// destroyTrack_l() must be called with ThreadBase::mLock held
1906void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1907{
1908 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001909 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001910 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001911 removeTrack_l(track);
1912 }
1913}
1914
1915void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1916{
Eric Laurent29864602012-05-08 18:57:51 -07001917 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001918 mTracks.remove(track);
1919 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001920 // redundant as track is about to be destroyed, for dumpsys only
1921 track->mName = -1;
1922 if (track->isFastTrack()) {
1923 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001924 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001925 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1926 mFastTrackAvailMask |= 1 << index;
1927 // redundant as track is about to be destroyed, for dumpsys only
1928 track->mFastIndex = -1;
1929 }
Eric Laurentb469b942011-05-09 12:09:06 -07001930 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1931 if (chain != 0) {
1932 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001933 }
1934}
1935
1936String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1937{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001938 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001939 char *s;
1940
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001941 Mutex::Autolock _l(mLock);
1942 if (initCheck() != NO_ERROR) {
1943 return out_s8;
1944 }
1945
Dima Zavin799a70e2011-04-18 16:57:27 -07001946 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001947 out_s8 = String8(s);
1948 free(s);
1949 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001950}
1951
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001952// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001953void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1954 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001955 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001956
Steve Block3856b092011-10-20 11:56:00 +01001957 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001958
1959 switch (event) {
1960 case AudioSystem::OUTPUT_OPENED:
1961 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001962 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001963 desc.samplingRate = mSampleRate;
1964 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001965 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001966 desc.latency = latency();
1967 param2 = &desc;
1968 break;
1969
1970 case AudioSystem::STREAM_CONFIG_CHANGED:
1971 param2 = &param;
1972 case AudioSystem::OUTPUT_CLOSED:
1973 default:
1974 break;
1975 }
1976 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1977}
1978
1979void AudioFlinger::PlaybackThread::readOutputParameters()
1980{
Dima Zavin799a70e2011-04-18 16:57:27 -07001981 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001982 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1983 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001984 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001985 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001986 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001987 if (mFrameCount & 15) {
1988 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1989 mFrameCount);
1990 }
1991
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001992 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07001993 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001994 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07001995 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07001996 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1997 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1998 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1999 maxNormalFrameCount = maxNormalFrameCount & ~15;
2000 if (maxNormalFrameCount < minNormalFrameCount) {
2001 maxNormalFrameCount = minNormalFrameCount;
2002 }
2003 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2004 if (multiplier <= 1.0) {
2005 multiplier = 1.0;
2006 } else if (multiplier <= 2.0) {
2007 if (2 * mFrameCount <= maxNormalFrameCount) {
2008 multiplier = 2.0;
2009 } else {
2010 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2011 }
2012 } else {
2013 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2014 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2015 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2016 // FIXME this rounding up should not be done if no HAL SRC
2017 uint32_t truncMult = (uint32_t) multiplier;
2018 if ((truncMult & 1)) {
2019 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2020 ++truncMult;
2021 }
2022 }
2023 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002024 }
Glenn Kasten58912562012-04-03 10:45:00 -07002025 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002026 mNormalFrameCount = multiplier * mFrameCount;
2027 // round up to nearest 16 frames to satisfy AudioMixer
2028 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002029 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002030
Glenn Kastene9dd0172012-01-27 18:08:45 -08002031 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002032 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2033 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002034
Eric Laurentde070132010-07-13 04:45:46 -07002035 // force reconfiguration of effect chains and engines to take new buffer size and audio
2036 // parameters into account
2037 // Note that mLock is not held when readOutputParameters() is called from the constructor
2038 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2039 // matter.
2040 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2041 Vector< sp<EffectChain> > effectChains = mEffectChains;
2042 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002043 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002044 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002045}
2046
Eric Laurente737cda2012-05-22 18:55:44 -07002047
Mathias Agopian65ab4712010-07-14 17:59:35 -07002048status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2049{
Glenn Kastena0d68332012-01-27 16:47:15 -08002050 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002051 return BAD_VALUE;
2052 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002053 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002054 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002055 return INVALID_OPERATION;
2056 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002057 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002058
Dima Zavin799a70e2011-04-18 16:57:27 -07002059 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002060}
2061
Eric Laurent39e94f82010-07-28 01:32:47 -07002062uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002063{
2064 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002065 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002066 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002067 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002068 }
2069
2070 for (size_t i = 0; i < mTracks.size(); ++i) {
2071 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002072 if (sessionId == track->sessionId() &&
2073 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002074 result |= TRACK_SESSION;
2075 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002076 }
2077 }
2078
Eric Laurent39e94f82010-07-28 01:32:47 -07002079 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002080}
2081
Eric Laurentde070132010-07-13 04:45:46 -07002082uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2083{
Dima Zavinfce7a472011-04-19 22:30:36 -07002084 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002085 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002086 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2087 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002088 }
2089 for (size_t i = 0; i < mTracks.size(); i++) {
2090 sp<Track> track = mTracks[i];
2091 if (sessionId == track->sessionId() &&
2092 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002093 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002094 }
2095 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002096 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002097}
2098
Mathias Agopian65ab4712010-07-14 17:59:35 -07002099
Glenn Kastenaed850d2012-01-26 09:46:34 -08002100AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002101{
2102 Mutex::Autolock _l(mLock);
2103 return mOutput;
2104}
2105
2106AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2107{
2108 Mutex::Autolock _l(mLock);
2109 AudioStreamOut *output = mOutput;
2110 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002111 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2112 // must push a NULL and wait for ack
2113 mOutputSink.clear();
2114 mPipeSink.clear();
2115 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002116 return output;
2117}
2118
2119// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002120audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002121{
2122 if (mOutput == NULL) {
2123 return NULL;
2124 }
2125 return &mOutput->stream->common;
2126}
2127
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002128uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002129{
Eric Laurentab9071b2012-06-04 13:45:29 -07002130 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002131}
2132
Eric Laurenta011e352012-03-29 15:51:43 -07002133status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2134{
2135 if (!isValidSyncEvent(event)) {
2136 return BAD_VALUE;
2137 }
2138
2139 Mutex::Autolock _l(mLock);
2140
2141 for (size_t i = 0; i < mTracks.size(); ++i) {
2142 sp<Track> track = mTracks[i];
2143 if (event->triggerSession() == track->sessionId()) {
2144 track->setSyncEvent(event);
2145 return NO_ERROR;
2146 }
2147 }
2148
2149 return NAME_NOT_FOUND;
2150}
2151
2152bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2153{
2154 switch (event->type()) {
2155 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2156 return true;
2157 default:
2158 break;
2159 }
2160 return false;
2161}
2162
Eric Laurent44a957f2012-05-15 15:26:05 -07002163void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2164{
2165 size_t count = tracksToRemove.size();
2166 if (CC_UNLIKELY(count)) {
2167 for (size_t i = 0 ; i < count ; i++) {
2168 const sp<Track>& track = tracksToRemove.itemAt(i);
2169 if ((track->sharedBuffer() != 0) &&
2170 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2171 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2172 }
2173 }
2174 }
2175
2176}
2177
Mathias Agopian65ab4712010-07-14 17:59:35 -07002178// ----------------------------------------------------------------------------
2179
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002180AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002181 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002182 : PlaybackThread(audioFlinger, output, id, device, type),
2183 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002184 // mFastMixer below
2185 mFastMixerFutex(0)
2186 // mOutputSink below
2187 // mPipeSink below
2188 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002189{
Glenn Kasten58912562012-04-03 10:45:00 -07002190 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002191 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002192 "mFrameCount=%d, mNormalFrameCount=%d",
2193 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2194 mNormalFrameCount);
2195 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2196
Mathias Agopian65ab4712010-07-14 17:59:35 -07002197 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002198 if (mChannelCount != FCC_2) {
2199 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002200 }
Glenn Kasten58912562012-04-03 10:45:00 -07002201
2202 // create an NBAIO sink for the HAL output stream, and negotiate
2203 mOutputSink = new AudioStreamOutSink(output->stream);
2204 size_t numCounterOffers = 0;
2205 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2206 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2207 ALOG_ASSERT(index == 0);
2208
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002209 // initialize fast mixer depending on configuration
2210 bool initFastMixer;
2211 switch (kUseFastMixer) {
2212 case FastMixer_Never:
2213 initFastMixer = false;
2214 break;
2215 case FastMixer_Always:
2216 initFastMixer = true;
2217 break;
2218 case FastMixer_Static:
2219 case FastMixer_Dynamic:
2220 initFastMixer = mFrameCount < mNormalFrameCount;
2221 break;
2222 }
2223 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002224
2225 // create a MonoPipe to connect our submix to FastMixer
2226 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002227 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2228 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2229 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2230 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002231 const NBAIO_Format offers[1] = {format};
2232 size_t numCounterOffers = 0;
2233 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2234 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002235 monoPipe->setAvgFrames((mScreenState & 1) ?
2236 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002237 mPipeSink = monoPipe;
2238
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002239#ifdef TEE_SINK_FRAMES
2240 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2241 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2242 numCounterOffers = 0;
2243 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2244 ALOG_ASSERT(index == 0);
2245 mTeeSink = teeSink;
2246 PipeReader *teeSource = new PipeReader(*teeSink);
2247 numCounterOffers = 0;
2248 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2249 ALOG_ASSERT(index == 0);
2250 mTeeSource = teeSource;
2251#endif
2252
Glenn Kasten58912562012-04-03 10:45:00 -07002253 // create fast mixer and configure it initially with just one fast track for our submix
2254 mFastMixer = new FastMixer();
2255 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002256#ifdef STATE_QUEUE_DUMP
2257 sq->setObserverDump(&mStateQueueObserverDump);
2258 sq->setMutatorDump(&mStateQueueMutatorDump);
2259#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002260 FastMixerState *state = sq->begin();
2261 FastTrack *fastTrack = &state->mFastTracks[0];
2262 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2263 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2264 fastTrack->mVolumeProvider = NULL;
2265 fastTrack->mGeneration++;
2266 state->mFastTracksGen++;
2267 state->mTrackMask = 1;
2268 // fast mixer will use the HAL output sink
2269 state->mOutputSink = mOutputSink.get();
2270 state->mOutputSinkGen++;
2271 state->mFrameCount = mFrameCount;
2272 state->mCommand = FastMixerState::COLD_IDLE;
2273 // already done in constructor initialization list
2274 //mFastMixerFutex = 0;
2275 state->mColdFutexAddr = &mFastMixerFutex;
2276 state->mColdGen++;
2277 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002278 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002279 sq->end();
2280 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2281
2282 // start the fast mixer
2283 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002284 pid_t tid = mFastMixer->getTid();
2285 int err = requestPriority(getpid_cached, tid, 2);
2286 if (err != 0) {
2287 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2288 2, getpid_cached, tid, err);
2289 }
Glenn Kasten58912562012-04-03 10:45:00 -07002290
Glenn Kastenc15d6652012-05-30 14:52:57 -07002291#ifdef AUDIO_WATCHDOG
2292 // create and start the watchdog
2293 mAudioWatchdog = new AudioWatchdog();
2294 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2295 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2296 tid = mAudioWatchdog->getTid();
2297 err = requestPriority(getpid_cached, tid, 1);
2298 if (err != 0) {
2299 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2300 1, getpid_cached, tid, err);
2301 }
2302#endif
2303
Glenn Kasten58912562012-04-03 10:45:00 -07002304 } else {
2305 mFastMixer = NULL;
2306 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002307
2308 switch (kUseFastMixer) {
2309 case FastMixer_Never:
2310 case FastMixer_Dynamic:
2311 mNormalSink = mOutputSink;
2312 break;
2313 case FastMixer_Always:
2314 mNormalSink = mPipeSink;
2315 break;
2316 case FastMixer_Static:
2317 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2318 break;
2319 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002320}
2321
2322AudioFlinger::MixerThread::~MixerThread()
2323{
Glenn Kasten58912562012-04-03 10:45:00 -07002324 if (mFastMixer != NULL) {
2325 FastMixerStateQueue *sq = mFastMixer->sq();
2326 FastMixerState *state = sq->begin();
2327 if (state->mCommand == FastMixerState::COLD_IDLE) {
2328 int32_t old = android_atomic_inc(&mFastMixerFutex);
2329 if (old == -1) {
2330 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2331 }
2332 }
2333 state->mCommand = FastMixerState::EXIT;
2334 sq->end();
2335 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2336 mFastMixer->join();
2337 // Though the fast mixer thread has exited, it's state queue is still valid.
2338 // We'll use that extract the final state which contains one remaining fast track
2339 // corresponding to our sub-mix.
2340 state = sq->begin();
2341 ALOG_ASSERT(state->mTrackMask == 1);
2342 FastTrack *fastTrack = &state->mFastTracks[0];
2343 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2344 delete fastTrack->mBufferProvider;
2345 sq->end(false /*didModify*/);
2346 delete mFastMixer;
Glenn Kastenc15d6652012-05-30 14:52:57 -07002347 if (mAudioWatchdog != 0) {
2348 mAudioWatchdog->requestExit();
2349 mAudioWatchdog->requestExitAndWait();
2350 mAudioWatchdog.clear();
2351 }
Glenn Kasten58912562012-04-03 10:45:00 -07002352 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002353 delete mAudioMixer;
2354}
2355
Glenn Kasten83efdd02012-02-24 07:21:32 -08002356class CpuStats {
2357public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002358 CpuStats();
2359 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002360#ifdef DEBUG_CPU_USAGE
2361private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002362 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2363 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2364
2365 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2366
2367 int mCpuNum; // thread's current CPU number
2368 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002369#endif
2370};
2371
Glenn Kasten190a46f2012-03-06 11:27:10 -08002372CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002373#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002374 : mCpuNum(-1), mCpukHz(-1)
2375#endif
2376{
2377}
2378
2379void CpuStats::sample(const String8 &title) {
2380#ifdef DEBUG_CPU_USAGE
2381 // get current thread's delta CPU time in wall clock ns
2382 double wcNs;
2383 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2384
2385 // record sample for wall clock statistics
2386 if (valid) {
2387 mWcStats.sample(wcNs);
2388 }
2389
2390 // get the current CPU number
2391 int cpuNum = sched_getcpu();
2392
2393 // get the current CPU frequency in kHz
2394 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2395
2396 // check if either CPU number or frequency changed
2397 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2398 mCpuNum = cpuNum;
2399 mCpukHz = cpukHz;
2400 // ignore sample for purposes of cycles
2401 valid = false;
2402 }
2403
2404 // if no change in CPU number or frequency, then record sample for cycle statistics
2405 if (valid && mCpukHz > 0) {
2406 double cycles = wcNs * cpukHz * 0.000001;
2407 mHzStats.sample(cycles);
2408 }
2409
2410 unsigned n = mWcStats.n();
2411 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002412 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002413 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002414 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2415 double perLoop = elapsed / (double) n;
2416 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002417 double perLoop1k = perLoop * 0.001;
2418 double mean = mWcStats.mean();
2419 double stddev = mWcStats.stddev();
2420 double minimum = mWcStats.minimum();
2421 double maximum = mWcStats.maximum();
2422 double meanCycles = mHzStats.mean();
2423 double stddevCycles = mHzStats.stddev();
2424 double minCycles = mHzStats.minimum();
2425 double maxCycles = mHzStats.maximum();
2426 mCpuUsage.resetElapsed();
2427 mWcStats.reset();
2428 mHzStats.reset();
2429 ALOGD("CPU usage for %s over past %.1f secs\n"
2430 " (%u mixer loops at %.1f mean ms per loop):\n"
2431 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2432 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2433 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2434 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002435 elapsed * .000000001, n, perLoop * .000001,
2436 mean * .001,
2437 stddev * .001,
2438 minimum * .001,
2439 maximum * .001,
2440 mean / perLoop100,
2441 stddev / perLoop100,
2442 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002443 maximum / perLoop100,
2444 meanCycles / perLoop1k,
2445 stddevCycles / perLoop1k,
2446 minCycles / perLoop1k,
2447 maxCycles / perLoop1k);
2448
Glenn Kasten83efdd02012-02-24 07:21:32 -08002449 }
2450 }
2451#endif
2452};
2453
Glenn Kasten37d825e2012-02-24 07:21:48 -08002454void AudioFlinger::PlaybackThread::checkSilentMode_l()
2455{
2456 if (!mMasterMute) {
2457 char value[PROPERTY_VALUE_MAX];
2458 if (property_get("ro.audio.silent", value, "0") > 0) {
2459 char *endptr;
2460 unsigned long ul = strtoul(value, &endptr, 0);
2461 if (*endptr == '\0' && ul != 0) {
2462 ALOGD("Silence is golden");
2463 // The setprop command will not allow a property to be changed after
2464 // the first time it is set, so we don't have to worry about un-muting.
2465 setMasterMute_l(true);
2466 }
2467 }
2468 }
2469}
2470
Glenn Kasten000f0e32012-03-01 17:10:56 -08002471bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002472{
2473 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002474
Glenn Kasten000f0e32012-03-01 17:10:56 -08002475 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002476
2477 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002478 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002479
Glenn Kasten000f0e32012-03-01 17:10:56 -08002480 // DUPLICATING
2481 // FIXME could this be made local to while loop?
2482 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002483
Glenn Kasten66fcab92012-02-24 14:59:21 -08002484 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002485 sleepTime = idleSleepTime;
2486
Glenn Kasten9f34a362012-03-20 16:46:41 -07002487 if (mType == MIXER) {
2488 sleepTimeShift = 0;
2489 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002490
Glenn Kasten83efdd02012-02-24 07:21:32 -08002491 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002492 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002493
Eric Laurentfeb0db62011-07-22 09:04:31 -07002494 acquireWakeLock();
2495
Mathias Agopian65ab4712010-07-14 17:59:35 -07002496 while (!exitPending())
2497 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002498 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002499
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002500 Vector< sp<EffectChain> > effectChains;
2501
Mathias Agopian65ab4712010-07-14 17:59:35 -07002502 processConfigEvents();
2503
Mathias Agopian65ab4712010-07-14 17:59:35 -07002504 { // scope for mLock
2505
2506 Mutex::Autolock _l(mLock);
2507
2508 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002509 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002510 }
2511
Glenn Kastenfa26a852012-03-06 11:28:04 -08002512 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002513
Mathias Agopian65ab4712010-07-14 17:59:35 -07002514 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002515 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002516 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002517 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002518
2519 threadLoop_standby();
2520
Mathias Agopian65ab4712010-07-14 17:59:35 -07002521 mStandby = true;
2522 mBytesWritten = 0;
2523 }
2524
Glenn Kasten3e074702012-02-28 18:40:35 -08002525 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002526 // we're about to wait, flush the binder command buffer
2527 IPCThreadState::self()->flushCommands();
2528
Glenn Kastenfa26a852012-03-06 11:28:04 -08002529 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002530
Mathias Agopian65ab4712010-07-14 17:59:35 -07002531 if (exitPending()) break;
2532
Eric Laurentfeb0db62011-07-22 09:04:31 -07002533 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002534 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002535 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002536 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002537 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002538 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002539
Eric Laurentda747442012-04-25 18:53:13 -07002540 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002541 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002542
Glenn Kasten37d825e2012-02-24 07:21:48 -08002543 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002544
Glenn Kasten000f0e32012-03-01 17:10:56 -08002545 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002546 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002547 if (mType == MIXER) {
2548 sleepTimeShift = 0;
2549 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002550
Mathias Agopian65ab4712010-07-14 17:59:35 -07002551 continue;
2552 }
2553 }
2554
Glenn Kasten81028042012-04-30 18:15:12 -07002555 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002556 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002557
2558 // prevent any changes in effect chain list and in each effect chain
2559 // during mixing and effect process as the audio buffers could be deleted
2560 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002561 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002562 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002563
Glenn Kastenfec279f2012-03-08 07:47:15 -08002564 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002565 threadLoop_mix();
2566 } else {
2567 threadLoop_sleepTime();
2568 }
2569
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002570 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002571 sleepTime = suspendSleepTimeUs();
2572 }
2573
2574 // only process effects if we're going to write
2575 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002576 for (size_t i = 0; i < effectChains.size(); i ++) {
2577 effectChains[i]->process_l();
2578 }
2579 }
2580
2581 // enable changes in effect chain
2582 unlockEffectChains(effectChains);
2583
2584 // sleepTime == 0 means we must write to audio hardware
2585 if (sleepTime == 0) {
2586
2587 threadLoop_write();
2588
2589if (mType == MIXER) {
2590 // write blocked detection
2591 nsecs_t now = systemTime();
2592 nsecs_t delta = now - mLastWriteTime;
2593 if (!mStandby && delta > maxPeriod) {
2594 mNumDelayedWrites++;
2595 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002596#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002597 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002598#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002599 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2600 ns2ms(delta), mNumDelayedWrites, this);
2601 lastWarning = now;
2602 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002603 }
2604}
2605
2606 mStandby = false;
2607 } else {
2608 usleep(sleepTime);
2609 }
2610
Glenn Kasten58912562012-04-03 10:45:00 -07002611 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002612 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002613 // same lock. This will also mutate and push a new fast mixer state.
2614 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002615 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002616
Glenn Kastenfa26a852012-03-06 11:28:04 -08002617 // FIXME I don't understand the need for this here;
2618 // it was in the original code but maybe the
2619 // assignment in saveOutputTracks() makes this unnecessary?
2620 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002621
2622 // Effect chains will be actually deleted here if they were removed from
2623 // mEffectChains list during mixing or effects processing
2624 effectChains.clear();
2625
2626 // FIXME Note that the above .clear() is no longer necessary since effectChains
2627 // is now local to this block, but will keep it for now (at least until merge done).
2628 }
2629
Glenn Kasten9f34a362012-03-20 16:46:41 -07002630 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2631 if (mType == MIXER || mType == DIRECT) {
2632 // put output stream into standby mode
2633 if (!mStandby) {
2634 mOutput->stream->common.standby(&mOutput->stream->common);
2635 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002636 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002637
2638 releaseWakeLock();
2639
2640 ALOGV("Thread %p type %d exiting", this, mType);
2641 return false;
2642}
2643
Glenn Kasten58912562012-04-03 10:45:00 -07002644void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2645{
Glenn Kasten58912562012-04-03 10:45:00 -07002646 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2647}
2648
2649void AudioFlinger::MixerThread::threadLoop_write()
2650{
2651 // FIXME we should only do one push per cycle; confirm this is true
2652 // Start the fast mixer if it's not already running
2653 if (mFastMixer != NULL) {
2654 FastMixerStateQueue *sq = mFastMixer->sq();
2655 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002656 if (state->mCommand != FastMixerState::MIX_WRITE &&
2657 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002658 if (state->mCommand == FastMixerState::COLD_IDLE) {
2659 int32_t old = android_atomic_inc(&mFastMixerFutex);
2660 if (old == -1) {
2661 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2662 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002663 if (mAudioWatchdog != 0) {
2664 mAudioWatchdog->resume();
2665 }
Glenn Kasten58912562012-04-03 10:45:00 -07002666 }
2667 state->mCommand = FastMixerState::MIX_WRITE;
2668 sq->end();
2669 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002670 if (kUseFastMixer == FastMixer_Dynamic) {
2671 mNormalSink = mPipeSink;
2672 }
Glenn Kasten58912562012-04-03 10:45:00 -07002673 } else {
2674 sq->end(false /*didModify*/);
2675 }
2676 }
2677 PlaybackThread::threadLoop_write();
2678}
2679
Glenn Kasten000f0e32012-03-01 17:10:56 -08002680// shared by MIXER and DIRECT, overridden by DUPLICATING
2681void AudioFlinger::PlaybackThread::threadLoop_write()
2682{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002683 // FIXME rewrite to reduce number of system calls
2684 mLastWriteTime = systemTime();
2685 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002686 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002687
Eric Laurent67c0a582012-05-01 19:31:12 -07002688 // If an NBAIO sink is present, use it to write the normal mixer's submix
2689 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002690#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002691 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002692#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002693 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002694#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002695 // update the setpoint when gScreenState changes
2696 uint32_t screenState = gScreenState;
2697 if (screenState != mScreenState) {
2698 mScreenState = screenState;
2699 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2700 if (pipe != NULL) {
2701 pipe->setAvgFrames((mScreenState & 1) ?
2702 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2703 }
2704 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002705 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002706#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002707 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002708#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002709 if (framesWritten > 0) {
2710 bytesWritten = framesWritten << mBitShift;
2711 } else {
2712 bytesWritten = framesWritten;
2713 }
2714 // otherwise use the HAL / AudioStreamOut directly
2715 } else {
2716 // Direct output thread.
2717 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002718 }
2719
Eric Laurent67c0a582012-05-01 19:31:12 -07002720 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002721 mNumWrites++;
2722 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002723}
2724
Glenn Kasten58912562012-04-03 10:45:00 -07002725void AudioFlinger::MixerThread::threadLoop_standby()
2726{
2727 // Idle the fast mixer if it's currently running
2728 if (mFastMixer != NULL) {
2729 FastMixerStateQueue *sq = mFastMixer->sq();
2730 FastMixerState *state = sq->begin();
2731 if (!(state->mCommand & FastMixerState::IDLE)) {
2732 state->mCommand = FastMixerState::COLD_IDLE;
2733 state->mColdFutexAddr = &mFastMixerFutex;
2734 state->mColdGen++;
2735 mFastMixerFutex = 0;
2736 sq->end();
2737 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2738 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002739 if (kUseFastMixer == FastMixer_Dynamic) {
2740 mNormalSink = mOutputSink;
2741 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002742 if (mAudioWatchdog != 0) {
2743 mAudioWatchdog->pause();
2744 }
Glenn Kasten58912562012-04-03 10:45:00 -07002745 } else {
2746 sq->end(false /*didModify*/);
2747 }
2748 }
2749 PlaybackThread::threadLoop_standby();
2750}
2751
Glenn Kasten000f0e32012-03-01 17:10:56 -08002752// shared by MIXER and DIRECT, overridden by DUPLICATING
2753void AudioFlinger::PlaybackThread::threadLoop_standby()
2754{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002755 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002756 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002757}
2758
2759void AudioFlinger::MixerThread::threadLoop_mix()
2760{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002761 // obtain the presentation timestamp of the next output buffer
2762 int64_t pts;
2763 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002764
Glenn Kasten952eeb22012-03-06 11:30:57 -08002765 if (NULL != mOutput->stream->get_next_write_timestamp) {
2766 status = mOutput->stream->get_next_write_timestamp(
2767 mOutput->stream, &pts);
2768 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002769
Glenn Kasten952eeb22012-03-06 11:30:57 -08002770 if (status != NO_ERROR) {
2771 pts = AudioBufferProvider::kInvalidPTS;
2772 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002773
Glenn Kasten952eeb22012-03-06 11:30:57 -08002774 // mix buffers...
2775 mAudioMixer->process(pts);
2776 // increase sleep time progressively when application underrun condition clears.
2777 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2778 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2779 // such that we would underrun the audio HAL.
2780 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2781 sleepTimeShift--;
2782 }
2783 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002784 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002785 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002786}
2787
2788void AudioFlinger::MixerThread::threadLoop_sleepTime()
2789{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002790 // If no tracks are ready, sleep once for the duration of an output
2791 // buffer size, then write 0s to the output
2792 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002793 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002794 sleepTime = activeSleepTime >> sleepTimeShift;
2795 if (sleepTime < kMinThreadSleepTimeUs) {
2796 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002797 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002798 // reduce sleep time in case of consecutive application underruns to avoid
2799 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2800 // duration we would end up writing less data than needed by the audio HAL if
2801 // the condition persists.
2802 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2803 sleepTimeShift++;
2804 }
2805 } else {
2806 sleepTime = idleSleepTime;
2807 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002808 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002809 memset (mMixBuffer, 0, mixBufferSize);
2810 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002811 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002812 }
2813 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002814}
2815
2816// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002817AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002818 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002819{
2820
Glenn Kasten29c23c32012-01-26 13:37:52 -08002821 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002822 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002823 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002824 size_t mixedTracks = 0;
2825 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002826 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002827 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002828 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002829
2830 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002831 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002832
Eric Laurent571d49c2010-08-11 05:20:11 -07002833 if (masterMute) {
2834 masterVolume = 0;
2835 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002836 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002837 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002838 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002839 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002840 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002841 masterVolume = (float)((v + (1 << 23)) >> 24);
2842 chain.clear();
2843 }
2844
Glenn Kasten288ed212012-04-25 17:52:27 -07002845 // prepare a new state to push
2846 FastMixerStateQueue *sq = NULL;
2847 FastMixerState *state = NULL;
2848 bool didModify = false;
2849 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2850 if (mFastMixer != NULL) {
2851 sq = mFastMixer->sq();
2852 state = sq->begin();
2853 }
2854
Mathias Agopian65ab4712010-07-14 17:59:35 -07002855 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002856 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002857 if (t == 0) continue;
2858
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002859 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002860 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002861
Glenn Kasten288ed212012-04-25 17:52:27 -07002862 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002863 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002864
2865 // It's theoretically possible (though unlikely) for a fast track to be created
2866 // and then removed within the same normal mix cycle. This is not a problem, as
2867 // the track never becomes active so it's fast mixer slot is never touched.
2868 // The converse, of removing an (active) track and then creating a new track
2869 // at the identical fast mixer slot within the same normal mix cycle,
2870 // is impossible because the slot isn't marked available until the end of each cycle.
2871 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002872 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2873 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002874 FastTrack *fastTrack = &state->mFastTracks[j];
2875
2876 // Determine whether the track is currently in underrun condition,
2877 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002878 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2879 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002880 uint32_t recentFull = (underruns.mBitFields.mFull -
2881 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2882 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2883 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2884 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2885 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2886 uint32_t recentUnderruns = recentPartial + recentEmpty;
2887 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002888 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002889 // or stopped which can occur when flush() is called while active
2890 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002891 track->mUnderrunCount += recentUnderruns;
2892 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002893
Glenn Kastend08f48c2012-05-01 18:14:02 -07002894 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002895 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002896 bool isActive = true;
2897 switch (track->mState) {
2898 case TrackBase::STOPPING_1:
2899 // track stays active in STOPPING_1 state until first underrun
2900 if (recentUnderruns > 0) {
2901 track->mState = TrackBase::STOPPING_2;
2902 }
2903 break;
2904 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002905 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002906 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002907 break;
2908 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002909 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002910 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002911 break;
2912 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002913 if (recentFull > 0 || recentPartial > 0) {
2914 // track has provided at least some frames recently: reset retry count
2915 track->mRetryCount = kMaxTrackRetries;
2916 }
2917 if (recentUnderruns == 0) {
2918 // no recent underruns: stay active
2919 break;
2920 }
2921 // there has recently been an underrun of some kind
2922 if (track->sharedBuffer() == 0) {
2923 // were any of the recent underruns "empty" (no frames available)?
2924 if (recentEmpty == 0) {
2925 // no, then ignore the partial underruns as they are allowed indefinitely
2926 break;
2927 }
2928 // there has recently been an "empty" underrun: decrement the retry counter
2929 if (--(track->mRetryCount) > 0) {
2930 break;
2931 }
2932 // indicate to client process that the track was disabled because of underrun;
2933 // it will then automatically call start() when data is available
2934 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2935 // remove from active list, but state remains ACTIVE [confusing but true]
2936 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002937 break;
2938 }
2939 // fall through
2940 case TrackBase::STOPPING_2:
2941 case TrackBase::PAUSED:
2942 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002943 case TrackBase::STOPPED:
2944 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07002945 // Check for presentation complete if track is inactive
2946 // We have consumed all the buffers of this track.
2947 // This would be incomplete if we auto-paused on underrun
2948 {
2949 size_t audioHALFrames =
2950 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2951 size_t framesWritten =
2952 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2953 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2954 // track stays in active list until presentation is complete
2955 break;
2956 }
2957 }
2958 if (track->isStopping_2()) {
2959 track->mState = TrackBase::STOPPED;
2960 }
2961 if (track->isStopped()) {
2962 // Can't reset directly, as fast mixer is still polling this track
2963 // track->reset();
2964 // So instead mark this track as needing to be reset after push with ack
2965 resetMask |= 1 << i;
2966 }
2967 isActive = false;
2968 break;
2969 case TrackBase::IDLE:
2970 default:
2971 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07002972 }
2973
2974 if (isActive) {
2975 // was it previously inactive?
2976 if (!(state->mTrackMask & (1 << j))) {
2977 ExtendedAudioBufferProvider *eabp = track;
2978 VolumeProvider *vp = track;
2979 fastTrack->mBufferProvider = eabp;
2980 fastTrack->mVolumeProvider = vp;
2981 fastTrack->mSampleRate = track->mSampleRate;
2982 fastTrack->mChannelMask = track->mChannelMask;
2983 fastTrack->mGeneration++;
2984 state->mTrackMask |= 1 << j;
2985 didModify = true;
2986 // no acknowledgement required for newly active tracks
2987 }
2988 // cache the combined master volume and stream type volume for fast mixer; this
2989 // lacks any synchronization or barrier so VolumeProvider may read a stale value
2990 track->mCachedVolume = track->isMuted() ?
2991 0 : masterVolume * mStreamTypes[track->streamType()].volume;
2992 ++fastTracks;
2993 } else {
2994 // was it previously active?
2995 if (state->mTrackMask & (1 << j)) {
2996 fastTrack->mBufferProvider = NULL;
2997 fastTrack->mGeneration++;
2998 state->mTrackMask &= ~(1 << j);
2999 didModify = true;
3000 // If any fast tracks were removed, we must wait for acknowledgement
3001 // because we're about to decrement the last sp<> on those tracks.
3002 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003003 } else {
3004 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003005 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003006 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003007 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003008 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003009 }
3010 continue;
3011 }
3012
3013 { // local variable scope to avoid goto warning
3014
Mathias Agopian65ab4712010-07-14 17:59:35 -07003015 audio_track_cblk_t* cblk = track->cblk();
3016
3017 // The first time a track is added we wait
3018 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003019 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003020 // make sure that we have enough frames to mix one full buffer.
3021 // enforce this condition only once to enable draining the buffer in case the client
3022 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003023 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003024 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003025 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003026 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003027 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003028 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003029 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003030 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003031 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003032 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003033 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003034 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003035 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3036 // the minimum track buffer size is normally twice the number of frames necessary
3037 // to fill one buffer and the resampler should not leave more than one buffer worth
3038 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003039 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003040 }
3041 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003042 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003043 !track->isPaused() && !track->isTerminated())
3044 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003045 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003046
3047 mixedTracks++;
3048
3049 // track->mainBuffer() != mMixBuffer means there is an effect chain
3050 // connected to the track
3051 chain.clear();
3052 if (track->mainBuffer() != mMixBuffer) {
3053 chain = getEffectChain_l(track->sessionId());
3054 // Delegate volume control to effect in track effect chain if needed
3055 if (chain != 0) {
3056 tracksWithEffect++;
3057 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003058 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003059 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003060 }
3061 }
3062
3063
3064 int param = AudioMixer::VOLUME;
3065 if (track->mFillingUpStatus == Track::FS_FILLED) {
3066 // no ramp for the first volume setting
3067 track->mFillingUpStatus = Track::FS_ACTIVE;
3068 if (track->mState == TrackBase::RESUMING) {
3069 track->mState = TrackBase::ACTIVE;
3070 param = AudioMixer::RAMP_VOLUME;
3071 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003072 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003073 } else if (cblk->server != 0) {
3074 // If the track is stopped before the first frame was mixed,
3075 // do not apply ramp
3076 param = AudioMixer::RAMP_VOLUME;
3077 }
3078
3079 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003080 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003081 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003082 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003083 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003084 if (track->isPausing()) {
3085 track->setPaused();
3086 }
3087 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003088
Mathias Agopian65ab4712010-07-14 17:59:35 -07003089 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003090 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003091 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003092 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003093 vl = vlr & 0xFFFF;
3094 vr = vlr >> 16;
3095 // track volumes come from shared memory, so can't be trusted and must be clamped
3096 if (vl > MAX_GAIN_INT) {
3097 ALOGV("Track left volume out of range: %04X", vl);
3098 vl = MAX_GAIN_INT;
3099 }
3100 if (vr > MAX_GAIN_INT) {
3101 ALOGV("Track right volume out of range: %04X", vr);
3102 vr = MAX_GAIN_INT;
3103 }
3104 // now apply the master volume and stream type volume
3105 vl = (uint32_t)(v * vl) << 12;
3106 vr = (uint32_t)(v * vr) << 12;
3107 // assuming master volume and stream type volume each go up to 1.0,
3108 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003109
Glenn Kasten05632a52012-01-03 14:22:33 -08003110 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3111 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003112 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003113 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003114 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003115 }
3116 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003117 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003118 // Delegate volume control to effect in track effect chain if needed
3119 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3120 // Do not ramp volume if volume is controlled by effect
3121 param = AudioMixer::VOLUME;
3122 track->mHasVolumeController = true;
3123 } else {
3124 // force no volume ramp when volume controller was just disabled or removed
3125 // from effect chain to avoid volume spike
3126 if (track->mHasVolumeController) {
3127 param = AudioMixer::VOLUME;
3128 }
3129 track->mHasVolumeController = false;
3130 }
3131
3132 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003133 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003134 vl = (vl + (1 << 11)) >> 12;
3135 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3136 vr = (vr + (1 << 11)) >> 12;
3137 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003138
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003139 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 -07003140
Mathias Agopian65ab4712010-07-14 17:59:35 -07003141 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003142 mAudioMixer->setBufferProvider(name, track);
3143 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003144
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003145 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3146 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3147 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003148 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003149 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003150 AudioMixer::TRACK,
3151 AudioMixer::FORMAT, (void *)track->format());
3152 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003153 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003154 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003155 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003156 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003157 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003158 AudioMixer::RESAMPLE,
3159 AudioMixer::SAMPLE_RATE,
3160 (void *)(cblk->sampleRate));
3161 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003162 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003163 AudioMixer::TRACK,
3164 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3165 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003166 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003167 AudioMixer::TRACK,
3168 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3169
3170 // reset retry count
3171 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003172
Eric Laurent27741442012-01-17 19:20:12 -08003173 // If one track is ready, set the mixer ready if:
3174 // - the mixer was not ready during previous round OR
3175 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003176 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003177 mixerStatus != MIXER_TRACKS_ENABLED) {
3178 mixerStatus = MIXER_TRACKS_READY;
3179 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003180 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003181 // clear effect chain input buffer if an active track underruns to avoid sending
3182 // previous audio buffer again to effects
3183 chain = getEffectChain_l(track->sessionId());
3184 if (chain != 0) {
3185 chain->clearInputBuffer();
3186 }
3187
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003188 //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 -07003189 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3190 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003191 // We have consumed all the buffers of this track.
3192 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003193 // TODO: use actual buffer filling status instead of latency when available from
3194 // audio HAL
3195 size_t audioHALFrames =
3196 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3197 size_t framesWritten =
3198 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3199 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003200 if (track->isStopped()) {
3201 track->reset();
3202 }
Eric Laurenta011e352012-03-29 15:51:43 -07003203 tracksToRemove->add(track);
3204 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003205 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003206 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003207 // No buffers for this track. Give it a few chances to
3208 // fill a buffer, then remove it from active list.
3209 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003210 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003211 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003212 // indicate to client process that the track was disabled because of underrun;
3213 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003214 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003215 // If one track is not ready, mark the mixer also not ready if:
3216 // - the mixer was ready during previous round OR
3217 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003218 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003219 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220 mixerStatus = MIXER_TRACKS_ENABLED;
3221 }
3222 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003223 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003224 }
Glenn Kasten58912562012-04-03 10:45:00 -07003225
3226 } // local variable scope to avoid goto warning
3227track_is_ready: ;
3228
Mathias Agopian65ab4712010-07-14 17:59:35 -07003229 }
3230
Glenn Kasten288ed212012-04-25 17:52:27 -07003231 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003232 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003233 if (didModify) {
3234 state->mFastTracksGen++;
3235 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3236 if (kUseFastMixer == FastMixer_Dynamic &&
3237 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3238 state->mCommand = FastMixerState::COLD_IDLE;
3239 state->mColdFutexAddr = &mFastMixerFutex;
3240 state->mColdGen++;
3241 mFastMixerFutex = 0;
3242 if (kUseFastMixer == FastMixer_Dynamic) {
3243 mNormalSink = mOutputSink;
3244 }
3245 // If we go into cold idle, need to wait for acknowledgement
3246 // so that fast mixer stops doing I/O.
3247 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003248 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003249 }
3250 sq->end();
3251 }
3252 if (sq != NULL) {
3253 sq->end(didModify);
3254 sq->push(block);
3255 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07003256 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3257 mAudioWatchdog->pause();
3258 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003259
3260 // Now perform the deferred reset on fast tracks that have stopped
3261 while (resetMask != 0) {
3262 size_t i = __builtin_ctz(resetMask);
3263 ALOG_ASSERT(i < count);
3264 resetMask &= ~(1 << i);
3265 sp<Track> t = mActiveTracks[i].promote();
3266 if (t == 0) continue;
3267 Track* track = t.get();
3268 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3269 track->reset();
3270 }
Glenn Kasten58912562012-04-03 10:45:00 -07003271
Mathias Agopian65ab4712010-07-14 17:59:35 -07003272 // remove all the tracks that need to be...
3273 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003274 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003275 for (size_t i=0 ; i<count ; i++) {
3276 const sp<Track>& track = tracksToRemove->itemAt(i);
3277 mActiveTracks.remove(track);
3278 if (track->mainBuffer() != mMixBuffer) {
3279 chain = getEffectChain_l(track->sessionId());
3280 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003281 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003282 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003283 }
3284 }
3285 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003286 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003287 }
3288 }
3289 }
3290
3291 // mix buffer must be cleared if all tracks are connected to an
3292 // effect chain as in this case the mixer will not write to
3293 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003294 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3295 // FIXME as a performance optimization, should remember previous zero status
3296 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003297 }
3298
Glenn Kasten58912562012-04-03 10:45:00 -07003299 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003300 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003301 if (fastTracks > 0) {
3302 mixerStatus = MIXER_TRACKS_READY;
3303 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003304 return mixerStatus;
3305}
3306
Glenn Kasten66fcab92012-02-24 14:59:21 -08003307/*
3308The derived values that are cached:
3309 - mixBufferSize from frame count * frame size
3310 - activeSleepTime from activeSleepTimeUs()
3311 - idleSleepTime from idleSleepTimeUs()
3312 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3313 - maxPeriod from frame count and sample rate (MIXER only)
3314
3315The parameters that affect these derived values are:
3316 - frame count
3317 - frame size
3318 - sample rate
3319 - device type: A2DP or not
3320 - device latency
3321 - format: PCM or not
3322 - active sleep time
3323 - idle sleep time
3324*/
3325
3326void AudioFlinger::PlaybackThread::cacheParameters_l()
3327{
Glenn Kasten58912562012-04-03 10:45:00 -07003328 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003329 activeSleepTime = activeSleepTimeUs();
3330 idleSleepTime = idleSleepTimeUs();
3331}
3332
Eric Laurent22167852012-06-20 12:26:32 -07003333void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003334{
Steve Block3856b092011-10-20 11:56:00 +01003335 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003336 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003337 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003338
Mathias Agopian65ab4712010-07-14 17:59:35 -07003339 size_t size = mTracks.size();
3340 for (size_t i = 0; i < size; i++) {
3341 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003342 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003343 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003344 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003345 }
3346 }
3347}
3348
Mathias Agopian65ab4712010-07-14 17:59:35 -07003349// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003350int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003351{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003352 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003353}
3354
3355// deleteTrackName_l() must be called with ThreadBase::mLock held
3356void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3357{
Steve Block3856b092011-10-20 11:56:00 +01003358 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003359 mAudioMixer->deleteTrackName(name);
3360}
3361
3362// checkForNewParameters_l() must be called with ThreadBase::mLock held
3363bool AudioFlinger::MixerThread::checkForNewParameters_l()
3364{
Glenn Kasten58912562012-04-03 10:45:00 -07003365 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3366 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003367 bool reconfig = false;
3368
3369 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003370
3371 if (mFastMixer != NULL) {
3372 FastMixerStateQueue *sq = mFastMixer->sq();
3373 FastMixerState *state = sq->begin();
3374 if (!(state->mCommand & FastMixerState::IDLE)) {
3375 previousCommand = state->mCommand;
3376 state->mCommand = FastMixerState::HOT_IDLE;
3377 sq->end();
3378 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3379 } else {
3380 sq->end(false /*didModify*/);
3381 }
3382 }
3383
Mathias Agopian65ab4712010-07-14 17:59:35 -07003384 status_t status = NO_ERROR;
3385 String8 keyValuePair = mNewParameters[0];
3386 AudioParameter param = AudioParameter(keyValuePair);
3387 int value;
3388
3389 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3390 reconfig = true;
3391 }
3392 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003393 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003394 status = BAD_VALUE;
3395 } else {
3396 reconfig = true;
3397 }
3398 }
3399 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003400 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003401 status = BAD_VALUE;
3402 } else {
3403 reconfig = true;
3404 }
3405 }
3406 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3407 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003408 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003409 // if frame count is changed after track creation
3410 if (!mTracks.isEmpty()) {
3411 status = INVALID_OPERATION;
3412 } else {
3413 reconfig = true;
3414 }
3415 }
3416 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003417#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003418 // when changing the audio output device, call addBatteryData to notify
3419 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003420 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003421 uint32_t params = 0;
3422 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003423 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003424 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3425 }
3426
3427 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003428 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003429 // check if any other device (except speaker) is on
3430 if (value & deviceWithoutSpeaker ) {
3431 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3432 }
3433
3434 if (params != 0) {
3435 addBatteryData(params);
3436 }
3437 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003438#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003439
Mathias Agopian65ab4712010-07-14 17:59:35 -07003440 // forward device change to effects that have requested to be
3441 // aware of attached audio device.
Glenn Kasten94479fd2012-07-09 15:39:54 -07003442 mDevice = (audio_devices_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003443 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003444 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003445 }
3446 }
3447
3448 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003449 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003450 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003451 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003452 mOutput->stream->common.standby(&mOutput->stream->common);
3453 mStandby = true;
3454 mBytesWritten = 0;
3455 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003456 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003457 }
3458 if (status == NO_ERROR && reconfig) {
3459 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003460 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3461 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003462 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003463 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003464 for (size_t i = 0; i < mTracks.size() ; i++) {
Glenn Kasten254af182012-07-03 14:59:05 -07003465 int name = getTrackName_l(mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003466 if (name < 0) break;
3467 mTracks[i]->mName = name;
3468 // limit track sample rate to 2 x new output sample rate
3469 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3470 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3471 }
3472 }
3473 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3474 }
3475 }
3476
3477 mNewParameters.removeAt(0);
3478
3479 mParamStatus = status;
3480 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003481 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3482 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003483 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003484 }
Glenn Kasten58912562012-04-03 10:45:00 -07003485
3486 if (!(previousCommand & FastMixerState::IDLE)) {
3487 ALOG_ASSERT(mFastMixer != NULL);
3488 FastMixerStateQueue *sq = mFastMixer->sq();
3489 FastMixerState *state = sq->begin();
3490 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3491 state->mCommand = previousCommand;
3492 sq->end();
3493 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3494 }
3495
Mathias Agopian65ab4712010-07-14 17:59:35 -07003496 return reconfig;
3497}
3498
3499status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3500{
3501 const size_t SIZE = 256;
3502 char buffer[SIZE];
3503 String8 result;
3504
3505 PlaybackThread::dumpInternals(fd, args);
3506
3507 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3508 result.append(buffer);
3509 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003510
3511 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3512 FastMixerDumpState copy = mFastMixerDumpState;
3513 copy.dump(fd);
3514
Glenn Kasten39993082012-05-31 13:40:27 -07003515#ifdef STATE_QUEUE_DUMP
3516 // Similar for state queue
3517 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3518 observerCopy.dump(fd);
3519 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3520 mutatorCopy.dump(fd);
3521#endif
3522
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003523 // Write the tee output to a .wav file
3524 NBAIO_Source *teeSource = mTeeSource.get();
3525 if (teeSource != NULL) {
3526 char teePath[64];
3527 struct timeval tv;
3528 gettimeofday(&tv, NULL);
3529 struct tm tm;
3530 localtime_r(&tv.tv_sec, &tm);
3531 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3532 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3533 if (teeFd >= 0) {
3534 char wavHeader[44];
3535 memcpy(wavHeader,
3536 "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",
3537 sizeof(wavHeader));
3538 NBAIO_Format format = teeSource->format();
3539 unsigned channelCount = Format_channelCount(format);
3540 ALOG_ASSERT(channelCount <= FCC_2);
3541 unsigned sampleRate = Format_sampleRate(format);
3542 wavHeader[22] = channelCount; // number of channels
3543 wavHeader[24] = sampleRate; // sample rate
3544 wavHeader[25] = sampleRate >> 8;
3545 wavHeader[32] = channelCount * 2; // block alignment
3546 write(teeFd, wavHeader, sizeof(wavHeader));
3547 size_t total = 0;
3548 bool firstRead = true;
3549 for (;;) {
3550#define TEE_SINK_READ 1024
3551 short buffer[TEE_SINK_READ * FCC_2];
3552 size_t count = TEE_SINK_READ;
3553 ssize_t actual = teeSource->read(buffer, count);
3554 bool wasFirstRead = firstRead;
3555 firstRead = false;
3556 if (actual <= 0) {
3557 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3558 continue;
3559 }
3560 break;
3561 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003562 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003563 write(teeFd, buffer, actual * channelCount * sizeof(short));
3564 total += actual;
3565 }
3566 lseek(teeFd, (off_t) 4, SEEK_SET);
3567 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3568 write(teeFd, &temp, sizeof(temp));
3569 lseek(teeFd, (off_t) 40, SEEK_SET);
3570 temp = total * channelCount * sizeof(short);
3571 write(teeFd, &temp, sizeof(temp));
3572 close(teeFd);
3573 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3574 } else {
3575 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3576 }
3577 }
3578
Glenn Kastenc15d6652012-05-30 14:52:57 -07003579 if (mAudioWatchdog != 0) {
3580 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3581 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3582 wdCopy.dump(fd);
3583 }
3584
Mathias Agopian65ab4712010-07-14 17:59:35 -07003585 return NO_ERROR;
3586}
3587
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003588uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003589{
Glenn Kasten58912562012-04-03 10:45:00 -07003590 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003591}
3592
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003593uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003594{
Glenn Kasten58912562012-04-03 10:45:00 -07003595 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003596}
3597
Glenn Kasten66fcab92012-02-24 14:59:21 -08003598void AudioFlinger::MixerThread::cacheParameters_l()
3599{
3600 PlaybackThread::cacheParameters_l();
3601
3602 // FIXME: Relaxed timing because of a certain device that can't meet latency
3603 // Should be reduced to 2x after the vendor fixes the driver issue
3604 // increase threshold again due to low power audio mode. The way this warning
3605 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003606 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003607}
3608
Mathias Agopian65ab4712010-07-14 17:59:35 -07003609// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003610AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3611 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003612 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003613 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003614{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003615}
3616
3617AudioFlinger::DirectOutputThread::~DirectOutputThread()
3618{
3619}
3620
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003621AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3622 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003623)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003624{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003625 sp<Track> trackToRemove;
3626
Glenn Kastenfec279f2012-03-08 07:47:15 -08003627 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003628
Glenn Kasten952eeb22012-03-06 11:30:57 -08003629 // find out which tracks need to be processed
3630 if (mActiveTracks.size() != 0) {
3631 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003632 // The track died recently
3633 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003634
Glenn Kasten952eeb22012-03-06 11:30:57 -08003635 Track* const track = t.get();
3636 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003637
Glenn Kasten952eeb22012-03-06 11:30:57 -08003638 // The first time a track is added we wait
3639 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003640 uint32_t minFrames;
3641 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3642 minFrames = mNormalFrameCount;
3643 } else {
3644 minFrames = 1;
3645 }
3646 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003647 !track->isPaused() && !track->isTerminated())
3648 {
3649 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003650
Glenn Kasten952eeb22012-03-06 11:30:57 -08003651 if (track->mFillingUpStatus == Track::FS_FILLED) {
3652 track->mFillingUpStatus = Track::FS_ACTIVE;
3653 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003654 if (track->mState == TrackBase::RESUMING) {
3655 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003656 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003657 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003658
Glenn Kasten952eeb22012-03-06 11:30:57 -08003659 // compute volume for this track
3660 float left, right;
3661 if (track->isMuted() || mMasterMute || track->isPausing() ||
3662 mStreamTypes[track->streamType()].mute) {
3663 left = right = 0;
3664 if (track->isPausing()) {
3665 track->setPaused();
3666 }
3667 } else {
3668 float typeVolume = mStreamTypes[track->streamType()].volume;
3669 float v = mMasterVolume * typeVolume;
3670 uint32_t vlr = cblk->getVolumeLR();
3671 float v_clamped = v * (vlr & 0xFFFF);
3672 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3673 left = v_clamped/MAX_GAIN;
3674 v_clamped = v * (vlr >> 16);
3675 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3676 right = v_clamped/MAX_GAIN;
3677 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003678
Glenn Kasten952eeb22012-03-06 11:30:57 -08003679 if (left != mLeftVolFloat || right != mRightVolFloat) {
3680 mLeftVolFloat = left;
3681 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003682
Glenn Kasten952eeb22012-03-06 11:30:57 -08003683 // Convert volumes from float to 8.24
3684 uint32_t vl = (uint32_t)(left * (1 << 24));
3685 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003686
Glenn Kasten952eeb22012-03-06 11:30:57 -08003687 // Delegate volume control to effect in track effect chain if needed
3688 // only one effect chain can be present on DirectOutputThread, so if
3689 // there is one, the track is connected to it
3690 if (!mEffectChains.isEmpty()) {
3691 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003692 mEffectChains[0]->setVolume_l(&vl, &vr);
3693 left = (float)vl / (1 << 24);
3694 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003695 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003696 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003697 }
3698
3699 // reset retry count
3700 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003701 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003702 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003703 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003704 // clear effect chain input buffer if an active track underruns to avoid sending
3705 // previous audio buffer again to effects
3706 if (!mEffectChains.isEmpty()) {
3707 mEffectChains[0]->clearInputBuffer();
3708 }
3709
Glenn Kasten952eeb22012-03-06 11:30:57 -08003710 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurent67c0a582012-05-01 19:31:12 -07003711 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3712 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003713 // We have consumed all the buffers of this track.
3714 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003715 // TODO: implement behavior for compressed audio
3716 size_t audioHALFrames =
3717 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3718 size_t framesWritten =
3719 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3720 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003721 if (track->isStopped()) {
3722 track->reset();
3723 }
Eric Laurenta011e352012-03-29 15:51:43 -07003724 trackToRemove = track;
3725 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003726 } else {
3727 // No buffers for this track. Give it a few chances to
3728 // fill a buffer, then remove it from active list.
3729 if (--(track->mRetryCount) <= 0) {
3730 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3731 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003732 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003733 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003734 }
3735 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003736 }
3737 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003738
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003739 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003740 // remove all the tracks that need to be...
3741 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003742 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003743 mActiveTracks.remove(trackToRemove);
3744 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003745 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003746 trackToRemove->sessionId());
3747 mEffectChains[0]->decActiveTrackCnt();
3748 }
3749 if (trackToRemove->isTerminated()) {
3750 removeTrack_l(trackToRemove);
3751 }
3752 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003753
Glenn Kastenfec279f2012-03-08 07:47:15 -08003754 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003755}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003756
Glenn Kasten000f0e32012-03-01 17:10:56 -08003757void AudioFlinger::DirectOutputThread::threadLoop_mix()
3758{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003759 AudioBufferProvider::Buffer buffer;
3760 size_t frameCount = mFrameCount;
3761 int8_t *curBuf = (int8_t *)mMixBuffer;
3762 // output audio to hardware
3763 while (frameCount) {
3764 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003765 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003766 if (CC_UNLIKELY(buffer.raw == NULL)) {
3767 memset(curBuf, 0, frameCount * mFrameSize);
3768 break;
3769 }
3770 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3771 frameCount -= buffer.frameCount;
3772 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003773 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003774 }
3775 sleepTime = 0;
3776 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003777 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003778
Glenn Kasten000f0e32012-03-01 17:10:56 -08003779}
3780
3781void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3782{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003783 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003784 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003785 sleepTime = activeSleepTime;
3786 } else {
3787 sleepTime = idleSleepTime;
3788 }
3789 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003790 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003791 sleepTime = 0;
3792 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003793}
3794
3795// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003796int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003797{
3798 return 0;
3799}
3800
3801// deleteTrackName_l() must be called with ThreadBase::mLock held
3802void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3803{
3804}
3805
3806// checkForNewParameters_l() must be called with ThreadBase::mLock held
3807bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3808{
3809 bool reconfig = false;
3810
3811 while (!mNewParameters.isEmpty()) {
3812 status_t status = NO_ERROR;
3813 String8 keyValuePair = mNewParameters[0];
3814 AudioParameter param = AudioParameter(keyValuePair);
3815 int value;
3816
3817 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3818 // do not accept frame count changes if tracks are open as the track buffer
3819 // size depends on frame count and correct behavior would not be garantied
3820 // if frame count is changed after track creation
3821 if (!mTracks.isEmpty()) {
3822 status = INVALID_OPERATION;
3823 } else {
3824 reconfig = true;
3825 }
3826 }
3827 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003828 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003829 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003830 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003831 mOutput->stream->common.standby(&mOutput->stream->common);
3832 mStandby = true;
3833 mBytesWritten = 0;
3834 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003835 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003836 }
3837 if (status == NO_ERROR && reconfig) {
3838 readOutputParameters();
3839 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3840 }
3841 }
3842
3843 mNewParameters.removeAt(0);
3844
3845 mParamStatus = status;
3846 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003847 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3848 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003849 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003850 }
3851 return reconfig;
3852}
3853
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003854uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003855{
3856 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003857 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003858 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003859 } else {
3860 time = 10000;
3861 }
3862 return time;
3863}
3864
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003865uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003866{
3867 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003868 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003869 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003870 } else {
3871 time = 10000;
3872 }
3873 return time;
3874}
3875
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003876uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003877{
3878 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003879 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003880 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3881 } else {
3882 time = 10000;
3883 }
3884 return time;
3885}
3886
Glenn Kasten66fcab92012-02-24 14:59:21 -08003887void AudioFlinger::DirectOutputThread::cacheParameters_l()
3888{
3889 PlaybackThread::cacheParameters_l();
3890
3891 // use shorter standby delay as on normal output to release
3892 // hardware resources as soon as possible
3893 standbyDelay = microseconds(activeSleepTime*2);
3894}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003895
Mathias Agopian65ab4712010-07-14 17:59:35 -07003896// ----------------------------------------------------------------------------
3897
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003898AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003899 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003900 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3901 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003902{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003903 addOutputTrack(mainThread);
3904}
3905
3906AudioFlinger::DuplicatingThread::~DuplicatingThread()
3907{
3908 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3909 mOutputTracks[i]->destroy();
3910 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003911}
3912
Glenn Kasten000f0e32012-03-01 17:10:56 -08003913void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003914{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003915 // mix buffers...
3916 if (outputsReady(outputTracks)) {
3917 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3918 } else {
3919 memset(mMixBuffer, 0, mixBufferSize);
3920 }
3921 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003922 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003923 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003924}
3925
3926void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3927{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003928 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003929 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003930 sleepTime = activeSleepTime;
3931 } else {
3932 sleepTime = idleSleepTime;
3933 }
3934 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003935 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3936 writeFrames = mNormalFrameCount;
3937 memset(mMixBuffer, 0, mixBufferSize);
3938 } else {
3939 // flush remaining overflow buffers in output tracks
3940 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003941 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003942 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003943 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003944}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003945
Glenn Kasten000f0e32012-03-01 17:10:56 -08003946void AudioFlinger::DuplicatingThread::threadLoop_write()
3947{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003948 for (size_t i = 0; i < outputTracks.size(); i++) {
3949 outputTracks[i]->write(mMixBuffer, writeFrames);
3950 }
3951 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003952}
Glenn Kasten688a6402012-02-29 07:57:06 -08003953
Glenn Kasten000f0e32012-03-01 17:10:56 -08003954void AudioFlinger::DuplicatingThread::threadLoop_standby()
3955{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003956 // DuplicatingThread implements standby by stopping all tracks
3957 for (size_t i = 0; i < outputTracks.size(); i++) {
3958 outputTracks[i]->stop();
3959 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003960}
3961
Glenn Kastenfa26a852012-03-06 11:28:04 -08003962void AudioFlinger::DuplicatingThread::saveOutputTracks()
3963{
3964 outputTracks = mOutputTracks;
3965}
3966
3967void AudioFlinger::DuplicatingThread::clearOutputTracks()
3968{
3969 outputTracks.clear();
3970}
3971
Mathias Agopian65ab4712010-07-14 17:59:35 -07003972void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3973{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003974 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003975 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07003976 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003977 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003978 this,
3979 mSampleRate,
3980 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003981 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003982 frameCount);
3983 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003984 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003985 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003986 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003987 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003988 }
3989}
3990
3991void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3992{
3993 Mutex::Autolock _l(mLock);
3994 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003995 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003996 mOutputTracks[i]->destroy();
3997 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003998 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003999 return;
4000 }
4001 }
Steve Block3856b092011-10-20 11:56:00 +01004002 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004003}
4004
Glenn Kasten438b0362012-03-06 11:24:48 -08004005// caller must hold mLock
4006void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004007{
4008 mWaitTimeMs = UINT_MAX;
4009 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4010 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004011 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004012 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4013 if (waitTimeMs < mWaitTimeMs) {
4014 mWaitTimeMs = waitTimeMs;
4015 }
4016 }
4017 }
4018}
4019
4020
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004021bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004022{
4023 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004024 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004025 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004026 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004027 return false;
4028 }
4029 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004030 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004031 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004032 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004033 return false;
4034 }
4035 }
4036 return true;
4037}
4038
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004039uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004040{
4041 return (mWaitTimeMs * 1000) / 2;
4042}
4043
Glenn Kasten66fcab92012-02-24 14:59:21 -08004044void AudioFlinger::DuplicatingThread::cacheParameters_l()
4045{
4046 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4047 updateWaitTime_l();
4048
4049 MixerThread::cacheParameters_l();
4050}
4051
Mathias Agopian65ab4712010-07-14 17:59:35 -07004052// ----------------------------------------------------------------------------
4053
4054// TrackBase constructor must be called with AudioFlinger::mLock held
4055AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004056 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004057 const sp<Client>& client,
4058 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004059 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004060 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004061 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004062 const sp<IMemory>& sharedBuffer,
4063 int sessionId)
4064 : RefBase(),
4065 mThread(thread),
4066 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004067 mCblk(NULL),
4068 // mBuffer
4069 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004070 mFrameCount(0),
4071 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004072 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004073 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004074 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004075 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004076 // mChannelCount
4077 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004078{
Steve Block3856b092011-10-20 11:56:00 +01004079 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004080
Steve Blockb8a80522011-12-20 16:23:08 +00004081 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004082 size_t size = sizeof(audio_track_cblk_t);
4083 uint8_t channelCount = popcount(channelMask);
4084 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4085 if (sharedBuffer == 0) {
4086 size += bufferSize;
4087 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004088
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004089 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004090 mCblkMemory = client->heap()->allocate(size);
4091 if (mCblkMemory != 0) {
4092 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004093 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004094 new(mCblk) audio_track_cblk_t();
4095 // clear all buffers
4096 mCblk->frameCount = frameCount;
4097 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004098// uncomment the following lines to quickly test 32-bit wraparound
4099// mCblk->user = 0xffff0000;
4100// mCblk->server = 0xffff0000;
4101// mCblk->userBase = 0xffff0000;
4102// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004103 mChannelCount = channelCount;
4104 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004105 if (sharedBuffer == 0) {
4106 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4107 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4108 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004109 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004110 mCblk->flags = CBLK_UNDERRUN_ON;
4111 } else {
4112 mBuffer = sharedBuffer->pointer();
4113 }
4114 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4115 }
4116 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004117 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004118 client->heap()->dump("AudioTrack");
4119 return;
4120 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004121 } else {
4122 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004123 // construct the shared structure in-place.
4124 new(mCblk) audio_track_cblk_t();
4125 // clear all buffers
4126 mCblk->frameCount = frameCount;
4127 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004128// uncomment the following lines to quickly test 32-bit wraparound
4129// mCblk->user = 0xffff0000;
4130// mCblk->server = 0xffff0000;
4131// mCblk->userBase = 0xffff0000;
4132// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004133 mChannelCount = channelCount;
4134 mChannelMask = channelMask;
4135 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4136 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4137 // Force underrun condition to avoid false underrun callback until first data is
4138 // written to buffer (other flags are cleared)
4139 mCblk->flags = CBLK_UNDERRUN_ON;
4140 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004141 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004142}
4143
4144AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4145{
Glenn Kastena0d68332012-01-27 16:47:15 -08004146 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004147 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004148 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004149 } else {
4150 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004151 }
4152 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004153 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004154 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004155 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004156 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004157 // If the client's reference count drops to zero, the associated destructor
4158 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4159 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004160 mClient.clear();
4161 }
4162}
4163
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004164// AudioBufferProvider interface
4165// getNextBuffer() = 0;
4166// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004167void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4168{
Glenn Kastene0feee32011-12-13 11:53:26 -08004169 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004170 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004171 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004172 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004173 buffer->frameCount = 0;
4174}
4175
4176bool AudioFlinger::ThreadBase::TrackBase::step() {
4177 bool result;
4178 audio_track_cblk_t* cblk = this->cblk();
4179
4180 result = cblk->stepServer(mFrameCount);
4181 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004182 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004183 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004184 }
4185 return result;
4186}
4187
4188void AudioFlinger::ThreadBase::TrackBase::reset() {
4189 audio_track_cblk_t* cblk = this->cblk();
4190
4191 cblk->user = 0;
4192 cblk->server = 0;
4193 cblk->userBase = 0;
4194 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004195 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004196 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004197}
4198
Mathias Agopian65ab4712010-07-14 17:59:35 -07004199int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4200 return (int)mCblk->sampleRate;
4201}
4202
Mathias Agopian65ab4712010-07-14 17:59:35 -07004203void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4204 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004205 size_t frameSize = cblk->frameSize;
4206 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4207 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004208
4209 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004210 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4211 "TrackBase::getBuffer buffer out of range:\n"
4212 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4213 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004214 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004215 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004216
4217 return bufferStart;
4218}
4219
Eric Laurenta011e352012-03-29 15:51:43 -07004220status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4221{
4222 mSyncEvents.add(event);
4223 return NO_ERROR;
4224}
4225
Mathias Agopian65ab4712010-07-14 17:59:35 -07004226// ----------------------------------------------------------------------------
4227
4228// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4229AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004230 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004231 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004232 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004233 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004234 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004235 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004236 int frameCount,
4237 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004238 int sessionId,
4239 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004240 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004241 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004242 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004243 // mRetryCount initialized later when needed
4244 mSharedBuffer(sharedBuffer),
4245 mStreamType(streamType),
4246 mName(-1), // see note below
4247 mMainBuffer(thread->mixBuffer()),
4248 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004249 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004250 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004251 mFlags(flags),
4252 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004253 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004254 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004255{
4256 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004257 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4258 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004259 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004260 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Glenn Kasten254af182012-07-03 14:59:05 -07004261 mName = thread->getTrackName_l(channelMask);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004262 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004263 if (mName < 0) {
4264 ALOGE("no more track names available");
4265 return;
4266 }
4267 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004268 if (flags & IAudioFlinger::TRACK_FAST) {
4269 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4270 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4271 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004272 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004273 // FIXME This is too eager. We allocate a fast track index before the
4274 // fast track becomes active. Since fast tracks are a scarce resource,
4275 // this means we are potentially denying other more important fast tracks from
4276 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004277 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004278 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004279 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004280 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004281 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004282 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004283 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004284 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004285}
4286
4287AudioFlinger::PlaybackThread::Track::~Track()
4288{
Steve Block3856b092011-10-20 11:56:00 +01004289 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004290 sp<ThreadBase> thread = mThread.promote();
4291 if (thread != 0) {
4292 Mutex::Autolock _l(thread->mLock);
4293 mState = TERMINATED;
4294 }
4295}
4296
4297void AudioFlinger::PlaybackThread::Track::destroy()
4298{
4299 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4300 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004301 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004302 // we must acquire a strong reference on this Track before locking mLock
4303 // here so that the destructor is called only when exiting this function.
4304 // On the other hand, as long as Track::destroy() is only called by
4305 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4306 // this Track with its member mTrack.
4307 sp<Track> keep(this);
4308 { // scope for mLock
4309 sp<ThreadBase> thread = mThread.promote();
4310 if (thread != 0) {
4311 if (!isOutputTrack()) {
4312 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004313 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004314
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004315#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004316 // to track the speaker usage
4317 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004318#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004319 }
4320 AudioSystem::releaseOutput(thread->id());
4321 }
4322 Mutex::Autolock _l(thread->mLock);
4323 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4324 playbackThread->destroyTrack_l(this);
4325 }
4326 }
4327}
4328
Glenn Kasten288ed212012-04-25 17:52:27 -07004329/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4330{
Glenn Kastene213c862012-04-25 13:46:15 -07004331 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 -07004332 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004333}
4334
Mathias Agopian65ab4712010-07-14 17:59:35 -07004335void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4336{
Glenn Kasten83d86532012-01-17 14:39:34 -08004337 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004338 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004339 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004340 } else {
4341 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4342 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004343 track_state state = mState;
4344 char stateChar;
4345 switch (state) {
4346 case IDLE:
4347 stateChar = 'I';
4348 break;
4349 case TERMINATED:
4350 stateChar = 'T';
4351 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004352 case STOPPING_1:
4353 stateChar = 's';
4354 break;
4355 case STOPPING_2:
4356 stateChar = '5';
4357 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004358 case STOPPED:
4359 stateChar = 'S';
4360 break;
4361 case RESUMING:
4362 stateChar = 'R';
4363 break;
4364 case ACTIVE:
4365 stateChar = 'A';
4366 break;
4367 case PAUSING:
4368 stateChar = 'p';
4369 break;
4370 case PAUSED:
4371 stateChar = 'P';
4372 break;
Eric Laurent29864602012-05-08 18:57:51 -07004373 case FLUSHED:
4374 stateChar = 'F';
4375 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004376 default:
4377 stateChar = '?';
4378 break;
4379 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004380 char nowInUnderrun;
4381 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4382 case UNDERRUN_FULL:
4383 nowInUnderrun = ' ';
4384 break;
4385 case UNDERRUN_PARTIAL:
4386 nowInUnderrun = '<';
4387 break;
4388 case UNDERRUN_EMPTY:
4389 nowInUnderrun = '*';
4390 break;
4391 default:
4392 nowInUnderrun = '?';
4393 break;
4394 }
Glenn Kastene213c862012-04-25 13:46:15 -07004395 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4396 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004397 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004398 mStreamType,
4399 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004400 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004401 mSessionId,
4402 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004403 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004404 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004405 mMute,
4406 mFillingUpStatus,
4407 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004408 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4409 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004410 mCblk->server,
4411 mCblk->user,
4412 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004413 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004414 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004415 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004416 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004417}
4418
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004419// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004420status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004421 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004422{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004423 audio_track_cblk_t* cblk = this->cblk();
4424 uint32_t framesReady;
4425 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004426
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004427 // Check if last stepServer failed, try to step now
4428 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004429 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4430 // Since the fast mixer is higher priority than client callback thread,
4431 // it does not result in priority inversion for client.
4432 // But a non-blocking solution would be preferable to avoid
4433 // fast mixer being unable to tryLock(), and
4434 // to avoid the extra context switches if the client wakes up,
4435 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004436 if (!step()) goto getNextBuffer_exit;
4437 ALOGV("stepServer recovered");
4438 mStepServerFailed = false;
4439 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004440
Glenn Kasten288ed212012-04-25 17:52:27 -07004441 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004442 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004443
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004444 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004445 uint32_t s = cblk->server;
4446 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4447
4448 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4449 if (framesReq > framesReady) {
4450 framesReq = framesReady;
4451 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004452 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004453 framesReq = bufferEnd - s;
4454 }
4455
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004456 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004457 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004458 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004459 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004460
4461getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004462 buffer->raw = NULL;
4463 buffer->frameCount = 0;
4464 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4465 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004466}
4467
Glenn Kasten288ed212012-04-25 17:52:27 -07004468// Note that framesReady() takes a mutex on the control block using tryLock().
4469// This could result in priority inversion if framesReady() is called by the normal mixer,
4470// as the normal mixer thread runs at lower
4471// priority than the client's callback thread: there is a short window within framesReady()
4472// during which the normal mixer could be preempted, and the client callback would block.
4473// Another problem can occur if framesReady() is called by the fast mixer:
4474// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4475// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4476size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004477 return mCblk->framesReady();
4478}
4479
Glenn Kasten288ed212012-04-25 17:52:27 -07004480// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004481bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004482 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004483
John Grossman4ff14ba2012-02-08 16:37:41 -08004484 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004485 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4486 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004487 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004488 return true;
4489 }
4490 return false;
4491}
4492
Glenn Kasten3acbd052012-02-28 10:39:56 -08004493status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004494 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004495{
4496 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004497 ALOGV("start(%d), calling pid %d session %d",
4498 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004499
Mathias Agopian65ab4712010-07-14 17:59:35 -07004500 sp<ThreadBase> thread = mThread.promote();
4501 if (thread != 0) {
4502 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004503 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004504 // here the track could be either new, or restarted
4505 // in both cases "unstop" the track
4506 if (mState == PAUSED) {
4507 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004508 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004509 } else {
4510 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004511 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004512 }
4513
4514 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4515 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004516 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004517 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004518
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004519#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004520 // to track the speaker usage
4521 if (status == NO_ERROR) {
4522 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4523 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004524#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004525 }
4526 if (status == NO_ERROR) {
4527 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4528 playbackThread->addTrack_l(this);
4529 } else {
4530 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004531 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004532 }
4533 } else {
4534 status = BAD_VALUE;
4535 }
4536 return status;
4537}
4538
4539void AudioFlinger::PlaybackThread::Track::stop()
4540{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004541 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004542 sp<ThreadBase> thread = mThread.promote();
4543 if (thread != 0) {
4544 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004545 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004546 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004547 // If the track is not active (PAUSED and buffers full), flush buffers
4548 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4549 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4550 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004551 mState = STOPPED;
4552 } else if (!isFastTrack()) {
4553 mState = STOPPED;
4554 } else {
4555 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4556 // and then to STOPPED and reset() when presentation is complete
4557 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004558 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004559 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004560 }
4561 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4562 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004563 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004564 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004565
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004566#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004567 // to track the speaker usage
4568 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004569#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004570 }
4571 }
4572}
4573
4574void AudioFlinger::PlaybackThread::Track::pause()
4575{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004576 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004577 sp<ThreadBase> thread = mThread.promote();
4578 if (thread != 0) {
4579 Mutex::Autolock _l(thread->mLock);
4580 if (mState == ACTIVE || mState == RESUMING) {
4581 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004582 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004583 if (!isOutputTrack()) {
4584 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004585 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004586 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004587
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004588#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004589 // to track the speaker usage
4590 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004591#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004592 }
4593 }
4594 }
4595}
4596
4597void AudioFlinger::PlaybackThread::Track::flush()
4598{
Steve Block3856b092011-10-20 11:56:00 +01004599 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004600 sp<ThreadBase> thread = mThread.promote();
4601 if (thread != 0) {
4602 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004603 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4604 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004605 return;
4606 }
4607 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004608 // FLUSHED state
4609 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004610 // do not reset the track if it is still in the process of being stopped or paused.
4611 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004612 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004613 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004614 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4615 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4616 reset();
4617 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004618 }
4619}
4620
4621void AudioFlinger::PlaybackThread::Track::reset()
4622{
4623 // Do not reset twice to avoid discarding data written just after a flush and before
4624 // the audioflinger thread detects the track is stopped.
4625 if (!mResetDone) {
4626 TrackBase::reset();
4627 // Force underrun condition to avoid false underrun callback until first data is
4628 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004629 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4630 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004631 mFillingUpStatus = FS_FILLING;
4632 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004633 if (mState == FLUSHED) {
4634 mState = IDLE;
4635 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004636 }
4637}
4638
4639void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4640{
4641 mMute = muted;
4642}
4643
Mathias Agopian65ab4712010-07-14 17:59:35 -07004644status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4645{
4646 status_t status = DEAD_OBJECT;
4647 sp<ThreadBase> thread = mThread.promote();
4648 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004649 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004650 sp<AudioFlinger> af = mClient->audioFlinger();
4651
4652 Mutex::Autolock _l(af->mLock);
4653
4654 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004655
Eric Laurent109347d2012-07-02 12:31:03 -07004656 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004657 Mutex::Autolock _dl(playbackThread->mLock);
4658 Mutex::Autolock _sl(srcThread->mLock);
4659 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4660 if (chain == 0) {
4661 return INVALID_OPERATION;
4662 }
4663
4664 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4665 if (effect == 0) {
4666 return INVALID_OPERATION;
4667 }
4668 srcThread->removeEffect_l(effect);
4669 playbackThread->addEffect_l(effect);
4670 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4671 if (effect->state() == EffectModule::ACTIVE ||
4672 effect->state() == EffectModule::STOPPING) {
4673 effect->start();
4674 }
4675
4676 sp<EffectChain> dstChain = effect->chain().promote();
4677 if (dstChain == 0) {
4678 srcThread->addEffect_l(effect);
4679 return INVALID_OPERATION;
4680 }
4681 AudioSystem::unregisterEffect(effect->id());
4682 AudioSystem::registerEffect(&effect->desc(),
4683 srcThread->id(),
4684 dstChain->strategy(),
4685 AUDIO_SESSION_OUTPUT_MIX,
4686 effect->id());
4687 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004688 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004689 }
4690 return status;
4691}
4692
4693void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4694{
4695 mAuxEffectId = EffectId;
4696 mAuxBuffer = buffer;
4697}
4698
Eric Laurenta011e352012-03-29 15:51:43 -07004699bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4700 size_t audioHalFrames)
4701{
4702 // a track is considered presented when the total number of frames written to audio HAL
4703 // corresponds to the number of frames written when presentationComplete() is called for the
4704 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4705 if (mPresentationCompleteFrames == 0) {
4706 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4707 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4708 mPresentationCompleteFrames, audioHalFrames);
4709 }
4710 if (framesWritten >= mPresentationCompleteFrames) {
4711 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4712 mSessionId, framesWritten);
4713 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004714 return true;
4715 }
4716 return false;
4717}
4718
4719void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4720{
4721 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4722 if (mSyncEvents[i]->type() == type) {
4723 mSyncEvents[i]->trigger();
4724 mSyncEvents.removeAt(i);
4725 i--;
4726 }
4727 }
4728}
4729
Glenn Kasten58912562012-04-03 10:45:00 -07004730// implement VolumeBufferProvider interface
4731
4732uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4733{
4734 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4735 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4736 uint32_t vlr = mCblk->getVolumeLR();
4737 uint32_t vl = vlr & 0xFFFF;
4738 uint32_t vr = vlr >> 16;
4739 // track volumes come from shared memory, so can't be trusted and must be clamped
4740 if (vl > MAX_GAIN_INT) {
4741 vl = MAX_GAIN_INT;
4742 }
4743 if (vr > MAX_GAIN_INT) {
4744 vr = MAX_GAIN_INT;
4745 }
4746 // now apply the cached master volume and stream type volume;
4747 // this is trusted but lacks any synchronization or barrier so may be stale
4748 float v = mCachedVolume;
4749 vl *= v;
4750 vr *= v;
4751 // re-combine into U4.16
4752 vlr = (vr << 16) | (vl & 0xFFFF);
4753 // FIXME look at mute, pause, and stop flags
4754 return vlr;
4755}
Eric Laurenta011e352012-03-29 15:51:43 -07004756
Eric Laurent29864602012-05-08 18:57:51 -07004757status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4758{
4759 if (mState == TERMINATED || mState == PAUSED ||
4760 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4761 (mState == STOPPED)))) {
4762 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4763 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4764 event->cancel();
4765 return INVALID_OPERATION;
4766 }
4767 TrackBase::setSyncEvent(event);
4768 return NO_ERROR;
4769}
4770
John Grossman4ff14ba2012-02-08 16:37:41 -08004771// timed audio tracks
4772
4773sp<AudioFlinger::PlaybackThread::TimedTrack>
4774AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004775 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004776 const sp<Client>& client,
4777 audio_stream_type_t streamType,
4778 uint32_t sampleRate,
4779 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004780 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004781 int frameCount,
4782 const sp<IMemory>& sharedBuffer,
4783 int sessionId) {
4784 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004785 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004786
Glenn Kastena0356762012-03-19 10:38:51 -07004787 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004788 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4789 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004790}
4791
4792AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004793 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004794 const sp<Client>& client,
4795 audio_stream_type_t streamType,
4796 uint32_t sampleRate,
4797 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004798 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004799 int frameCount,
4800 const sp<IMemory>& sharedBuffer,
4801 int sessionId)
4802 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004803 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004804 mQueueHeadInFlight(false),
4805 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004806 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004807 mTimedSilenceBuffer(NULL),
4808 mTimedSilenceBufferSize(0),
4809 mTimedAudioOutputOnTime(false),
4810 mMediaTimeTransformValid(false)
4811{
4812 LocalClock lc;
4813 mLocalTimeFreq = lc.getLocalFreq();
4814
4815 mLocalTimeToSampleTransform.a_zero = 0;
4816 mLocalTimeToSampleTransform.b_zero = 0;
4817 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4818 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4819 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4820 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004821
4822 mMediaTimeToSampleTransform.a_zero = 0;
4823 mMediaTimeToSampleTransform.b_zero = 0;
4824 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4825 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4826 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4827 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004828}
4829
4830AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4831 mClient->releaseTimedTrack();
4832 delete [] mTimedSilenceBuffer;
4833}
4834
4835status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4836 size_t size, sp<IMemory>* buffer) {
4837
4838 Mutex::Autolock _l(mTimedBufferQueueLock);
4839
4840 trimTimedBufferQueue_l();
4841
4842 // lazily initialize the shared memory heap for timed buffers
4843 if (mTimedMemoryDealer == NULL) {
4844 const int kTimedBufferHeapSize = 512 << 10;
4845
4846 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4847 "AudioFlingerTimed");
4848 if (mTimedMemoryDealer == NULL)
4849 return NO_MEMORY;
4850 }
4851
4852 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4853 if (newBuffer == NULL) {
4854 newBuffer = mTimedMemoryDealer->allocate(size);
4855 if (newBuffer == NULL)
4856 return NO_MEMORY;
4857 }
4858
4859 *buffer = newBuffer;
4860 return NO_ERROR;
4861}
4862
4863// caller must hold mTimedBufferQueueLock
4864void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4865 int64_t mediaTimeNow;
4866 {
4867 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4868 if (!mMediaTimeTransformValid)
4869 return;
4870
4871 int64_t targetTimeNow;
4872 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4873 ? mCCHelper.getCommonTime(&targetTimeNow)
4874 : mCCHelper.getLocalTime(&targetTimeNow);
4875
4876 if (OK != res)
4877 return;
4878
4879 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4880 &mediaTimeNow)) {
4881 return;
4882 }
4883 }
4884
John Grossman1c345192012-03-27 14:00:17 -07004885 size_t trimEnd;
4886 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004887 int64_t bufEnd;
4888
John Grossmanc95cfbb2012-04-12 11:53:11 -07004889 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4890 // We have a next buffer. Just use its PTS as the PTS of the frame
4891 // following the last frame in this buffer. If the stream is sparse
4892 // (ie, there are deliberate gaps left in the stream which should be
4893 // filled with silence by the TimedAudioTrack), then this can result
4894 // in one extra buffer being left un-trimmed when it could have
4895 // been. In general, this is not typical, and we would rather
4896 // optimized away the TS calculation below for the more common case
4897 // where PTSes are contiguous.
4898 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4899 } else {
4900 // We have no next buffer. Compute the PTS of the frame following
4901 // the last frame in this buffer by computing the duration of of
4902 // this frame in media time units and adding it to the PTS of the
4903 // buffer.
4904 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4905 / mCblk->frameSize;
4906
4907 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4908 &bufEnd)) {
4909 ALOGE("Failed to convert frame count of %lld to media time"
4910 " duration" " (scale factor %d/%u) in %s",
4911 frameCount,
4912 mMediaTimeToSampleTransform.a_to_b_numer,
4913 mMediaTimeToSampleTransform.a_to_b_denom,
4914 __PRETTY_FUNCTION__);
4915 break;
4916 }
4917 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004918 }
John Grossman9fbdee12012-03-26 17:51:46 -07004919
4920 if (bufEnd > mediaTimeNow)
4921 break;
4922
4923 // Is the buffer we want to use in the middle of a mix operation right
4924 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4925 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004926 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004927 mTrimQueueHeadOnRelease = true;
4928 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004929 }
4930
John Grossman9fbdee12012-03-26 17:51:46 -07004931 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004932 if (trimStart < trimEnd) {
4933 // Update the bookkeeping for framesReady()
4934 for (size_t i = trimStart; i < trimEnd; ++i) {
4935 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4936 }
4937
4938 // Now actually remove the buffers from the queue.
4939 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004940 }
4941}
4942
John Grossman1c345192012-03-27 14:00:17 -07004943void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4944 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004945 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4946 "%s called (reason \"%s\"), but timed buffer queue has no"
4947 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004948
4949 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4950 mTimedBufferQueue.removeAt(0);
4951}
4952
4953void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4954 const TimedBuffer& buf,
4955 const char* logTag) {
4956 uint32_t bufBytes = buf.buffer()->size();
4957 uint32_t consumedAlready = buf.position();
4958
Eric Laurentb388e532012-04-14 13:32:48 -07004959 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004960 "Bad bookkeeping while updating frames pending. Timed buffer is"
4961 " only %u bytes long, but claims to have consumed %u"
4962 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004963 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004964
4965 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004966 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4967 "Bad bookkeeping while updating frames pending. Should have at"
4968 " least %u queued frames, but we think we have only %u. (update"
4969 " reason: \"%s\")",
4970 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004971
4972 mFramesPendingInQueue -= bufFrames;
4973}
4974
John Grossman4ff14ba2012-02-08 16:37:41 -08004975status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4976 const sp<IMemory>& buffer, int64_t pts) {
4977
4978 {
4979 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4980 if (!mMediaTimeTransformValid)
4981 return INVALID_OPERATION;
4982 }
4983
4984 Mutex::Autolock _l(mTimedBufferQueueLock);
4985
John Grossman1c345192012-03-27 14:00:17 -07004986 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4987 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004988 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4989
4990 return NO_ERROR;
4991}
4992
4993status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4994 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4995
John Grossman1c345192012-03-27 14:00:17 -07004996 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4997 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4998 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08004999
5000 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5001 target == TimedAudioTrack::COMMON_TIME)) {
5002 return BAD_VALUE;
5003 }
5004
5005 Mutex::Autolock lock(mMediaTimeTransformLock);
5006 mMediaTimeTransform = xform;
5007 mMediaTimeTransformTarget = target;
5008 mMediaTimeTransformValid = true;
5009
5010 return NO_ERROR;
5011}
5012
5013#define min(a, b) ((a) < (b) ? (a) : (b))
5014
5015// implementation of getNextBuffer for tracks whose buffers have timestamps
5016status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5017 AudioBufferProvider::Buffer* buffer, int64_t pts)
5018{
5019 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005020 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005021 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005022 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005023 return INVALID_OPERATION;
5024 }
5025
John Grossman4ff14ba2012-02-08 16:37:41 -08005026 Mutex::Autolock _l(mTimedBufferQueueLock);
5027
John Grossman9fbdee12012-03-26 17:51:46 -07005028 ALOG_ASSERT(!mQueueHeadInFlight,
5029 "getNextBuffer called without releaseBuffer!");
5030
John Grossman4ff14ba2012-02-08 16:37:41 -08005031 while (true) {
5032
5033 // if we have no timed buffers, then fail
5034 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005035 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005036 buffer->frameCount = 0;
5037 return NOT_ENOUGH_DATA;
5038 }
5039
5040 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5041
5042 // calculate the PTS of the head of the timed buffer queue expressed in
5043 // local time
5044 int64_t headLocalPTS;
5045 {
5046 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5047
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005048 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005049
5050 if (mMediaTimeTransform.a_to_b_denom == 0) {
5051 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005052 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005053 return NO_ERROR;
5054 }
5055
5056 int64_t transformedPTS;
5057 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5058 &transformedPTS)) {
5059 // the transform failed. this shouldn't happen, but if it does
5060 // then just drop this buffer
5061 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005062 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005063 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005064 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005065 return NO_ERROR;
5066 }
5067
5068 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5069 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5070 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005071 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005072 buffer->frameCount = 0;
5073 return INVALID_OPERATION;
5074 }
5075 } else {
5076 headLocalPTS = transformedPTS;
5077 }
5078 }
5079
5080 // adjust the head buffer's PTS to reflect the portion of the head buffer
5081 // that has already been consumed
5082 int64_t effectivePTS = headLocalPTS +
5083 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5084
5085 // Calculate the delta in samples between the head of the input buffer
5086 // queue and the start of the next output buffer that will be written.
5087 // If the transformation fails because of over or underflow, it means
5088 // that the sample's position in the output stream is so far out of
5089 // whack that it should just be dropped.
5090 int64_t sampleDelta;
5091 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5092 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005093 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5094 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005095 continue;
5096 }
5097 if (!mLocalTimeToSampleTransform.doForwardTransform(
5098 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005099 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005100 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005101 continue;
5102 }
5103
John Grossman1c345192012-03-27 14:00:17 -07005104 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5105 " sampleDelta=[%d.%08x]",
5106 head.pts(), head.position(), pts,
5107 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5108 + (sampleDelta >> 32)),
5109 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005110
5111 // if the delta between the ideal placement for the next input sample and
5112 // the current output position is within this threshold, then we will
5113 // concatenate the next input samples to the previous output
5114 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005115 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005116
5117 // if this is the first buffer of audio that we're emitting from this track
5118 // then it should be almost exactly on time.
5119 const int64_t kSampleStartupThreshold = 1LL << 32;
5120
5121 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005122 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005123 // the next input is close enough to being on time, so concatenate it
5124 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005125 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005126
John Grossman1c345192012-03-27 14:00:17 -07005127 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5128 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005129 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005130 }
5131
5132 // Looks like our output is not on time. Reset our on timed status.
5133 // Next time we mix samples from our input queue, then should be within
5134 // the StartupThreshold.
5135 mTimedAudioOutputOnTime = false;
5136 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005137 // the gap between the current output position and the proper start of
5138 // the next input sample is too big, so fill it with silence
5139 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5140
John Grossman9fbdee12012-03-26 17:51:46 -07005141 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005142 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5143 return NO_ERROR;
5144 } else {
5145 // the next input sample is late
5146 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5147 size_t onTimeSamplePosition =
5148 head.position() + lateFrames * mCblk->frameSize;
5149
5150 if (onTimeSamplePosition > head.buffer()->size()) {
5151 // all the remaining samples in the head are too late, so
5152 // drop it and move on
5153 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005154 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005155 continue;
5156 } else {
5157 // skip over the late samples
5158 head.setPosition(onTimeSamplePosition);
5159
5160 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005161 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005162
5163 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5164 return NO_ERROR;
5165 }
5166 }
5167 }
5168}
5169
5170// Yield samples from the timed buffer queue head up to the given output
5171// buffer's capacity.
5172//
5173// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005174void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005175 AudioBufferProvider::Buffer* buffer) {
5176
5177 const TimedBuffer& head = mTimedBufferQueue[0];
5178
5179 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5180 head.position());
5181
5182 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5183 mCblk->frameSize);
5184 size_t framesRequested = buffer->frameCount;
5185 buffer->frameCount = min(framesLeftInHead, framesRequested);
5186
John Grossman9fbdee12012-03-26 17:51:46 -07005187 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005188 mTimedAudioOutputOnTime = true;
5189}
5190
5191// Yield samples of silence up to the given output buffer's capacity
5192//
5193// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005194void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005195 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5196
5197 // lazily allocate a buffer filled with silence
5198 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5199 delete [] mTimedSilenceBuffer;
5200 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5201 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5202 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5203 }
5204
5205 buffer->raw = mTimedSilenceBuffer;
5206 size_t framesRequested = buffer->frameCount;
5207 buffer->frameCount = min(numFrames, framesRequested);
5208
5209 mTimedAudioOutputOnTime = false;
5210}
5211
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005212// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005213void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5214 AudioBufferProvider::Buffer* buffer) {
5215
5216 Mutex::Autolock _l(mTimedBufferQueueLock);
5217
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005218 // If the buffer which was just released is part of the buffer at the head
5219 // of the queue, be sure to update the amt of the buffer which has been
5220 // consumed. If the buffer being returned is not part of the head of the
5221 // queue, its either because the buffer is part of the silence buffer, or
5222 // because the head of the timed queue was trimmed after the mixer called
5223 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005224 if (buffer->raw == mTimedSilenceBuffer) {
5225 ALOG_ASSERT(!mQueueHeadInFlight,
5226 "Queue head in flight during release of silence buffer!");
5227 goto done;
5228 }
5229
5230 ALOG_ASSERT(mQueueHeadInFlight,
5231 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5232 " head in flight.");
5233
5234 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005235 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005236
5237 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005238 void* end = reinterpret_cast<void*>(
5239 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5240 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005241
John Grossman9fbdee12012-03-26 17:51:46 -07005242 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5243 "released buffer not within the head of the timed buffer"
5244 " queue; qHead = [%p, %p], released buffer = %p",
5245 start, end, buffer->raw);
5246
5247 head.setPosition(head.position() +
5248 (buffer->frameCount * mCblk->frameSize));
5249 mQueueHeadInFlight = false;
5250
John Grossman1c345192012-03-27 14:00:17 -07005251 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5252 "Bad bookkeeping during releaseBuffer! Should have at"
5253 " least %u queued frames, but we think we have only %u",
5254 buffer->frameCount, mFramesPendingInQueue);
5255
5256 mFramesPendingInQueue -= buffer->frameCount;
5257
John Grossman9fbdee12012-03-26 17:51:46 -07005258 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5259 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005260 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005261 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005262 }
John Grossman9fbdee12012-03-26 17:51:46 -07005263 } else {
5264 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5265 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005266 }
5267
John Grossman9fbdee12012-03-26 17:51:46 -07005268done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005269 buffer->raw = 0;
5270 buffer->frameCount = 0;
5271}
5272
Glenn Kasten288ed212012-04-25 17:52:27 -07005273size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005274 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005275 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005276}
5277
5278AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5279 : mPTS(0), mPosition(0) {}
5280
5281AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5282 const sp<IMemory>& buffer, int64_t pts)
5283 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5284
Mathias Agopian65ab4712010-07-14 17:59:35 -07005285// ----------------------------------------------------------------------------
5286
5287// RecordTrack constructor must be called with AudioFlinger::mLock held
5288AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005289 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005290 const sp<Client>& client,
5291 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005292 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005293 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005294 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005295 int sessionId)
5296 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005297 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005298 mOverflow(false)
5299{
5300 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005301 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5302 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5303 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5304 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5305 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5306 } else {
5307 mCblk->frameSize = sizeof(int8_t);
5308 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005309 }
5310}
5311
5312AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5313{
5314 sp<ThreadBase> thread = mThread.promote();
5315 if (thread != 0) {
5316 AudioSystem::releaseInput(thread->id());
5317 }
5318}
5319
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005320// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005321status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005322{
5323 audio_track_cblk_t* cblk = this->cblk();
5324 uint32_t framesAvail;
5325 uint32_t framesReq = buffer->frameCount;
5326
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005327 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005328 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005329 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005330 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005331 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005332 }
5333
5334 framesAvail = cblk->framesAvailable_l();
5335
Glenn Kastenf6b16782011-12-15 09:51:17 -08005336 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005337 uint32_t s = cblk->server;
5338 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5339
5340 if (framesReq > framesAvail) {
5341 framesReq = framesAvail;
5342 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005343 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005344 framesReq = bufferEnd - s;
5345 }
5346
5347 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005348 buffer->frameCount = framesReq;
5349 return NO_ERROR;
5350 }
5351
5352getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005353 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005354 buffer->frameCount = 0;
5355 return NOT_ENOUGH_DATA;
5356}
5357
Glenn Kasten3acbd052012-02-28 10:39:56 -08005358status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005359 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005360{
5361 sp<ThreadBase> thread = mThread.promote();
5362 if (thread != 0) {
5363 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005364 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005365 } else {
5366 return BAD_VALUE;
5367 }
5368}
5369
5370void AudioFlinger::RecordThread::RecordTrack::stop()
5371{
5372 sp<ThreadBase> thread = mThread.promote();
5373 if (thread != 0) {
5374 RecordThread *recordThread = (RecordThread *)thread.get();
5375 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005376 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005377 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005378 // read from buffer
5379 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005380 }
5381}
5382
5383void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5384{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005385 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005386 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005387 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005388 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005389 mSessionId,
5390 mFrameCount,
5391 mState,
5392 mCblk->sampleRate,
5393 mCblk->server,
5394 mCblk->user);
5395}
5396
5397
5398// ----------------------------------------------------------------------------
5399
5400AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005401 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005402 DuplicatingThread *sourceThread,
5403 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005404 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005405 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005406 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005407 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5408 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005409 mActive(false), mSourceThread(sourceThread)
5410{
5411
Mathias Agopian65ab4712010-07-14 17:59:35 -07005412 if (mCblk != NULL) {
5413 mCblk->flags |= CBLK_DIRECTION_OUT;
5414 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005415 mOutBuffer.frameCount = 0;
5416 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005417 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005418 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5419 mCblk, mBuffer, mCblk->buffers,
5420 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005421 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005422 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005423 }
5424}
5425
5426AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5427{
5428 clearBufferQueue();
5429}
5430
Glenn Kasten3acbd052012-02-28 10:39:56 -08005431status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005432 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005433{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005434 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005435 if (status != NO_ERROR) {
5436 return status;
5437 }
5438
5439 mActive = true;
5440 mRetryCount = 127;
5441 return status;
5442}
5443
5444void AudioFlinger::PlaybackThread::OutputTrack::stop()
5445{
5446 Track::stop();
5447 clearBufferQueue();
5448 mOutBuffer.frameCount = 0;
5449 mActive = false;
5450}
5451
5452bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5453{
5454 Buffer *pInBuffer;
5455 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005456 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005457 bool outputBufferFull = false;
5458 inBuffer.frameCount = frames;
5459 inBuffer.i16 = data;
5460
5461 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5462
5463 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005464 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005465 sp<ThreadBase> thread = mThread.promote();
5466 if (thread != 0) {
5467 MixerThread *mixerThread = (MixerThread *)thread.get();
5468 if (mCblk->frameCount > frames){
5469 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5470 uint32_t startFrames = (mCblk->frameCount - frames);
5471 pInBuffer = new Buffer;
5472 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5473 pInBuffer->frameCount = startFrames;
5474 pInBuffer->i16 = pInBuffer->mBuffer;
5475 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5476 mBufferQueue.add(pInBuffer);
5477 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005478 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005479 }
5480 }
5481 }
5482 }
5483
5484 while (waitTimeLeftMs) {
5485 // First write pending buffers, then new data
5486 if (mBufferQueue.size()) {
5487 pInBuffer = mBufferQueue.itemAt(0);
5488 } else {
5489 pInBuffer = &inBuffer;
5490 }
5491
5492 if (pInBuffer->frameCount == 0) {
5493 break;
5494 }
5495
5496 if (mOutBuffer.frameCount == 0) {
5497 mOutBuffer.frameCount = pInBuffer->frameCount;
5498 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005499 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005500 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005501 outputBufferFull = true;
5502 break;
5503 }
5504 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5505 if (waitTimeLeftMs >= waitTimeMs) {
5506 waitTimeLeftMs -= waitTimeMs;
5507 } else {
5508 waitTimeLeftMs = 0;
5509 }
5510 }
5511
5512 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5513 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5514 mCblk->stepUser(outFrames);
5515 pInBuffer->frameCount -= outFrames;
5516 pInBuffer->i16 += outFrames * channelCount;
5517 mOutBuffer.frameCount -= outFrames;
5518 mOutBuffer.i16 += outFrames * channelCount;
5519
5520 if (pInBuffer->frameCount == 0) {
5521 if (mBufferQueue.size()) {
5522 mBufferQueue.removeAt(0);
5523 delete [] pInBuffer->mBuffer;
5524 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005525 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005526 } else {
5527 break;
5528 }
5529 }
5530 }
5531
5532 // If we could not write all frames, allocate a buffer and queue it for next time.
5533 if (inBuffer.frameCount) {
5534 sp<ThreadBase> thread = mThread.promote();
5535 if (thread != 0 && !thread->standby()) {
5536 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5537 pInBuffer = new Buffer;
5538 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5539 pInBuffer->frameCount = inBuffer.frameCount;
5540 pInBuffer->i16 = pInBuffer->mBuffer;
5541 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5542 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005543 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005544 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005545 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005546 }
5547 }
5548 }
5549
5550 // Calling write() with a 0 length buffer, means that no more data will be written:
5551 // If no more buffers are pending, fill output track buffer to make sure it is started
5552 // by output mixer.
5553 if (frames == 0 && mBufferQueue.size() == 0) {
5554 if (mCblk->user < mCblk->frameCount) {
5555 frames = mCblk->frameCount - mCblk->user;
5556 pInBuffer = new Buffer;
5557 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5558 pInBuffer->frameCount = frames;
5559 pInBuffer->i16 = pInBuffer->mBuffer;
5560 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5561 mBufferQueue.add(pInBuffer);
5562 } else if (mActive) {
5563 stop();
5564 }
5565 }
5566
5567 return outputBufferFull;
5568}
5569
5570status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5571{
5572 int active;
5573 status_t result;
5574 audio_track_cblk_t* cblk = mCblk;
5575 uint32_t framesReq = buffer->frameCount;
5576
Steve Block3856b092011-10-20 11:56:00 +01005577// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005578 buffer->frameCount = 0;
5579
5580 uint32_t framesAvail = cblk->framesAvailable();
5581
5582
5583 if (framesAvail == 0) {
5584 Mutex::Autolock _l(cblk->lock);
5585 goto start_loop_here;
5586 while (framesAvail == 0) {
5587 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005588 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005589 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005590 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005591 }
5592 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5593 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005594 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005595 }
5596 // read the server count again
5597 start_loop_here:
5598 framesAvail = cblk->framesAvailable_l();
5599 }
5600 }
5601
5602// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005603// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005604// }
5605
5606 if (framesReq > framesAvail) {
5607 framesReq = framesAvail;
5608 }
5609
5610 uint32_t u = cblk->user;
5611 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5612
Marco Nelissena1472d92012-03-30 14:36:54 -07005613 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005614 framesReq = bufferEnd - u;
5615 }
5616
5617 buffer->frameCount = framesReq;
5618 buffer->raw = (void *)cblk->buffer(u);
5619 return NO_ERROR;
5620}
5621
5622
5623void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5624{
5625 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005626
5627 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005628 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005629 delete [] pBuffer->mBuffer;
5630 delete pBuffer;
5631 }
5632 mBufferQueue.clear();
5633}
5634
5635// ----------------------------------------------------------------------------
5636
5637AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5638 : RefBase(),
5639 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005640 // 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 -07005641 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005642 mPid(pid),
5643 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005644{
5645 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5646}
5647
5648// Client destructor must be called with AudioFlinger::mLock held
5649AudioFlinger::Client::~Client()
5650{
5651 mAudioFlinger->removeClient_l(mPid);
5652}
5653
Glenn Kasten435dbe62012-01-30 10:15:48 -08005654sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005655{
5656 return mMemoryDealer;
5657}
5658
John Grossman4ff14ba2012-02-08 16:37:41 -08005659// Reserve one of the limited slots for a timed audio track associated
5660// with this client
5661bool AudioFlinger::Client::reserveTimedTrack()
5662{
5663 const int kMaxTimedTracksPerClient = 4;
5664
5665 Mutex::Autolock _l(mTimedTrackLock);
5666
5667 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5668 ALOGW("can not create timed track - pid %d has exceeded the limit",
5669 mPid);
5670 return false;
5671 }
5672
5673 mTimedTrackCount++;
5674 return true;
5675}
5676
5677// Release a slot for a timed audio track
5678void AudioFlinger::Client::releaseTimedTrack()
5679{
5680 Mutex::Autolock _l(mTimedTrackLock);
5681 mTimedTrackCount--;
5682}
5683
Mathias Agopian65ab4712010-07-14 17:59:35 -07005684// ----------------------------------------------------------------------------
5685
5686AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5687 const sp<IAudioFlingerClient>& client,
5688 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005689 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005690{
5691}
5692
5693AudioFlinger::NotificationClient::~NotificationClient()
5694{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005695}
5696
5697void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5698{
5699 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005700 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005701}
5702
5703// ----------------------------------------------------------------------------
5704
5705AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5706 : BnAudioTrack(),
5707 mTrack(track)
5708{
5709}
5710
5711AudioFlinger::TrackHandle::~TrackHandle() {
5712 // just stop the track on deletion, associated resources
5713 // will be freed from the main thread once all pending buffers have
5714 // been played. Unless it's not in the active track list, in which
5715 // case we free everything now...
5716 mTrack->destroy();
5717}
5718
Glenn Kasten90716c52012-01-26 13:40:12 -08005719sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5720 return mTrack->getCblk();
5721}
5722
Glenn Kasten3acbd052012-02-28 10:39:56 -08005723status_t AudioFlinger::TrackHandle::start() {
5724 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005725}
5726
5727void AudioFlinger::TrackHandle::stop() {
5728 mTrack->stop();
5729}
5730
5731void AudioFlinger::TrackHandle::flush() {
5732 mTrack->flush();
5733}
5734
5735void AudioFlinger::TrackHandle::mute(bool e) {
5736 mTrack->mute(e);
5737}
5738
5739void AudioFlinger::TrackHandle::pause() {
5740 mTrack->pause();
5741}
5742
Mathias Agopian65ab4712010-07-14 17:59:35 -07005743status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5744{
5745 return mTrack->attachAuxEffect(EffectId);
5746}
5747
John Grossman4ff14ba2012-02-08 16:37:41 -08005748status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5749 sp<IMemory>* buffer) {
5750 if (!mTrack->isTimedTrack())
5751 return INVALID_OPERATION;
5752
5753 PlaybackThread::TimedTrack* tt =
5754 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5755 return tt->allocateTimedBuffer(size, buffer);
5756}
5757
5758status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5759 int64_t pts) {
5760 if (!mTrack->isTimedTrack())
5761 return INVALID_OPERATION;
5762
5763 PlaybackThread::TimedTrack* tt =
5764 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5765 return tt->queueTimedBuffer(buffer, pts);
5766}
5767
5768status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5769 const LinearTransform& xform, int target) {
5770
5771 if (!mTrack->isTimedTrack())
5772 return INVALID_OPERATION;
5773
5774 PlaybackThread::TimedTrack* tt =
5775 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5776 return tt->setMediaTimeTransform(
5777 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5778}
5779
Mathias Agopian65ab4712010-07-14 17:59:35 -07005780status_t AudioFlinger::TrackHandle::onTransact(
5781 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5782{
5783 return BnAudioTrack::onTransact(code, data, reply, flags);
5784}
5785
5786// ----------------------------------------------------------------------------
5787
5788sp<IAudioRecord> AudioFlinger::openRecord(
5789 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005790 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005791 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005792 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005793 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005794 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005795 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07005796 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005797 int *sessionId,
5798 status_t *status)
5799{
5800 sp<RecordThread::RecordTrack> recordTrack;
5801 sp<RecordHandle> recordHandle;
5802 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005803 status_t lStatus;
5804 RecordThread *thread;
5805 size_t inFrameCount;
5806 int lSessionId;
5807
5808 // check calling permissions
5809 if (!recordingAllowed()) {
5810 lStatus = PERMISSION_DENIED;
5811 goto Exit;
5812 }
5813
5814 // add client to list
5815 { // scope for mLock
5816 Mutex::Autolock _l(mLock);
5817 thread = checkRecordThread_l(input);
5818 if (thread == NULL) {
5819 lStatus = BAD_VALUE;
5820 goto Exit;
5821 }
5822
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005823 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005824
5825 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005826 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005827 lSessionId = *sessionId;
5828 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005829 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005830 if (sessionId != NULL) {
5831 *sessionId = lSessionId;
5832 }
5833 }
5834 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07005835 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
5836 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005837 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005838 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005839 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5840 // destructor is called by the TrackBase destructor with mLock held
5841 client.clear();
5842 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005843 goto Exit;
5844 }
5845
5846 // return to handle to client
5847 recordHandle = new RecordHandle(recordTrack);
5848 lStatus = NO_ERROR;
5849
5850Exit:
5851 if (status) {
5852 *status = lStatus;
5853 }
5854 return recordHandle;
5855}
5856
5857// ----------------------------------------------------------------------------
5858
5859AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5860 : BnAudioRecord(),
5861 mRecordTrack(recordTrack)
5862{
5863}
5864
5865AudioFlinger::RecordHandle::~RecordHandle() {
5866 stop();
5867}
5868
Glenn Kasten90716c52012-01-26 13:40:12 -08005869sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5870 return mRecordTrack->getCblk();
5871}
5872
Glenn Kasten3acbd052012-02-28 10:39:56 -08005873status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005874 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005875 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005876}
5877
5878void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005879 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005880 mRecordTrack->stop();
5881}
5882
Mathias Agopian65ab4712010-07-14 17:59:35 -07005883status_t AudioFlinger::RecordHandle::onTransact(
5884 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5885{
5886 return BnAudioRecord::onTransact(code, data, reply, flags);
5887}
5888
5889// ----------------------------------------------------------------------------
5890
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005891AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5892 AudioStreamIn *input,
5893 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07005894 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005895 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005896 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005897 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005898 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5899 // mRsmpInIndex and mInputBytes set by readInputParameters()
Glenn Kasten254af182012-07-03 14:59:05 -07005900 mReqChannelCount(popcount(channelMask)),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005901 mReqSampleRate(sampleRate)
5902 // mBytesRead is only meaningful while active, and so is cleared in start()
5903 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005904{
Glenn Kasten480b4682012-02-28 12:30:08 -08005905 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005906
Mathias Agopian65ab4712010-07-14 17:59:35 -07005907 readInputParameters();
5908}
5909
5910
5911AudioFlinger::RecordThread::~RecordThread()
5912{
5913 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005914 delete mResampler;
5915 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005916}
5917
5918void AudioFlinger::RecordThread::onFirstRef()
5919{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005920 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005921}
5922
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005923status_t AudioFlinger::RecordThread::readyToRun()
5924{
5925 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005926 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005927 return status;
5928}
5929
Mathias Agopian65ab4712010-07-14 17:59:35 -07005930bool AudioFlinger::RecordThread::threadLoop()
5931{
5932 AudioBufferProvider::Buffer buffer;
5933 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005934 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005935
Eric Laurent44d98482010-09-30 16:12:31 -07005936 nsecs_t lastWarning = 0;
5937
Eric Laurentfeb0db62011-07-22 09:04:31 -07005938 acquireWakeLock();
5939
Mathias Agopian65ab4712010-07-14 17:59:35 -07005940 // start recording
5941 while (!exitPending()) {
5942
5943 processConfigEvents();
5944
5945 { // scope for mLock
5946 Mutex::Autolock _l(mLock);
5947 checkForNewParameters_l();
5948 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5949 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005950 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005951 mStandby = true;
5952 }
5953
5954 if (exitPending()) break;
5955
Eric Laurentfeb0db62011-07-22 09:04:31 -07005956 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005957 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005958 // go to sleep
5959 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005960 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005961 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005962 continue;
5963 }
5964 if (mActiveTrack != 0) {
5965 if (mActiveTrack->mState == TrackBase::PAUSING) {
5966 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005967 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005968 mStandby = true;
5969 }
5970 mActiveTrack.clear();
5971 mStartStopCond.broadcast();
5972 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5973 if (mReqChannelCount != mActiveTrack->channelCount()) {
5974 mActiveTrack.clear();
5975 mStartStopCond.broadcast();
5976 } else if (mBytesRead != 0) {
5977 // record start succeeds only if first read from audio input
5978 // succeeds
5979 if (mBytesRead > 0) {
5980 mActiveTrack->mState = TrackBase::ACTIVE;
5981 } else {
5982 mActiveTrack.clear();
5983 }
5984 mStartStopCond.broadcast();
5985 }
5986 mStandby = false;
5987 }
5988 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005989 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005990 }
5991
5992 if (mActiveTrack != 0) {
5993 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5994 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005995 unlockEffectChains(effectChains);
5996 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005997 continue;
5998 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005999 for (size_t i = 0; i < effectChains.size(); i ++) {
6000 effectChains[i]->process_l();
6001 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006002
Mathias Agopian65ab4712010-07-14 17:59:35 -07006003 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006004 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006005 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006006 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006007 // no resampling
6008 while (framesOut) {
6009 size_t framesIn = mFrameCount - mRsmpInIndex;
6010 if (framesIn) {
6011 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6012 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6013 if (framesIn > framesOut)
6014 framesIn = framesOut;
6015 mRsmpInIndex += framesIn;
6016 framesOut -= framesIn;
6017 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006018 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006019 memcpy(dst, src, framesIn * mFrameSize);
6020 } else {
6021 int16_t *src16 = (int16_t *)src;
6022 int16_t *dst16 = (int16_t *)dst;
6023 if (mChannelCount == 1) {
6024 while (framesIn--) {
6025 *dst16++ = *src16;
6026 *dst16++ = *src16++;
6027 }
6028 } else {
6029 while (framesIn--) {
6030 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
6031 src16 += 2;
6032 }
6033 }
6034 }
6035 }
6036 if (framesOut && mFrameCount == mRsmpInIndex) {
6037 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006038 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006039 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006040 framesOut = 0;
6041 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006042 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006043 mRsmpInIndex = 0;
6044 }
6045 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006046 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006047 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6048 // Force input into standby so that it tries to
6049 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006050 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006051 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006052 }
6053 mRsmpInIndex = mFrameCount;
6054 framesOut = 0;
6055 buffer.frameCount = 0;
6056 }
6057 }
6058 }
6059 } else {
6060 // resampling
6061
6062 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6063 // alter output frame count as if we were expecting stereo samples
6064 if (mChannelCount == 1 && mReqChannelCount == 1) {
6065 framesOut >>= 1;
6066 }
6067 mResampler->resample(mRsmpOutBuffer, framesOut, this);
6068 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6069 // are 32 bit aligned which should be always true.
6070 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006071 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006072 // the resampler always outputs stereo samples: do post stereo to mono conversion
6073 int16_t *src = (int16_t *)mRsmpOutBuffer;
6074 int16_t *dst = buffer.i16;
6075 while (framesOut--) {
6076 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
6077 src += 2;
6078 }
6079 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006080 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006081 }
6082
6083 }
Eric Laurenta011e352012-03-29 15:51:43 -07006084 if (mFramestoDrop == 0) {
6085 mActiveTrack->releaseBuffer(&buffer);
6086 } else {
6087 if (mFramestoDrop > 0) {
6088 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006089 if (mFramestoDrop <= 0) {
6090 clearSyncStartEvent();
6091 }
6092 } else {
6093 mFramestoDrop += buffer.frameCount;
6094 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6095 mSyncStartEvent->isCancelled()) {
6096 ALOGW("Synced record %s, session %d, trigger session %d",
6097 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6098 mActiveTrack->sessionId(),
6099 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6100 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006101 }
6102 }
6103 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006104 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006105 }
6106 // client isn't retrieving buffers fast enough
6107 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006108 if (!mActiveTrack->setOverflow()) {
6109 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006110 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006111 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006112 lastWarning = now;
6113 }
6114 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006115 // Release the processor for a while before asking for a new buffer.
6116 // This will give the application more chance to read from the buffer and
6117 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006118 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006119 }
6120 }
Eric Laurentec437d82011-07-26 20:54:46 -07006121 // enable changes in effect chain
6122 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006123 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006124 }
6125
6126 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006127 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006128 }
6129 mActiveTrack.clear();
6130
6131 mStartStopCond.broadcast();
6132
Eric Laurentfeb0db62011-07-22 09:04:31 -07006133 releaseWakeLock();
6134
Steve Block3856b092011-10-20 11:56:00 +01006135 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006136 return false;
6137}
6138
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006139
6140sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6141 const sp<AudioFlinger::Client>& client,
6142 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006143 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006144 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006145 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006146 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006147 IAudioFlinger::track_flags_t flags,
6148 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006149 status_t *status)
6150{
6151 sp<RecordTrack> track;
6152 status_t lStatus;
6153
6154 lStatus = initCheck();
6155 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006156 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006157 goto Exit;
6158 }
6159
Glenn Kasten1879fff2012-07-11 15:36:59 -07006160 // FIXME use flags and tid similar to createTrack_l()
6161
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006162 { // scope for mLock
6163 Mutex::Autolock _l(mLock);
6164
6165 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006166 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006167
Glenn Kasten7378ca52012-01-20 13:44:40 -08006168 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006169 lStatus = NO_MEMORY;
6170 goto Exit;
6171 }
6172
6173 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006174 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6175 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006176 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006177 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6178 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006179 }
6180 lStatus = NO_ERROR;
6181
6182Exit:
6183 if (status) {
6184 *status = lStatus;
6185 }
6186 return track;
6187}
6188
Eric Laurenta011e352012-03-29 15:51:43 -07006189status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006190 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006191 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006192{
Glenn Kasten58912562012-04-03 10:45:00 -07006193 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006194 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006195 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006196
6197 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006198 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006199 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6200 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6201 triggerSession,
6202 recordTrack->sessionId(),
6203 syncStartEventCallback,
6204 this);
Eric Laurent29864602012-05-08 18:57:51 -07006205 // Sync event can be cancelled by the trigger session if the track is not in a
6206 // compatible state in which case we start record immediately
6207 if (mSyncStartEvent->isCancelled()) {
6208 clearSyncStartEvent();
6209 } else {
6210 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6211 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6212 }
Eric Laurenta011e352012-03-29 15:51:43 -07006213 }
6214
Mathias Agopian65ab4712010-07-14 17:59:35 -07006215 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006216 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006217 if (mActiveTrack != 0) {
6218 if (recordTrack != mActiveTrack.get()) {
6219 status = -EBUSY;
6220 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6221 mActiveTrack->mState = TrackBase::ACTIVE;
6222 }
6223 return status;
6224 }
6225
6226 recordTrack->mState = TrackBase::IDLE;
6227 mActiveTrack = recordTrack;
6228 mLock.unlock();
6229 status_t status = AudioSystem::startInput(mId);
6230 mLock.lock();
6231 if (status != NO_ERROR) {
6232 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006233 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006234 return status;
6235 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006236 mRsmpInIndex = mFrameCount;
6237 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006238 if (mResampler != NULL) {
6239 mResampler->reset();
6240 }
6241 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006242 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006243 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006244 mWaitWorkCV.signal();
6245 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006246 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006247 mActiveTrack.clear();
6248 status = INVALID_OPERATION;
6249 goto startError;
6250 }
6251 mStartStopCond.wait(mLock);
6252 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006253 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006254 status = BAD_VALUE;
6255 goto startError;
6256 }
Steve Block3856b092011-10-20 11:56:00 +01006257 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006258 return status;
6259 }
6260startError:
6261 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006262 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006263 return status;
6264}
6265
Eric Laurenta011e352012-03-29 15:51:43 -07006266void AudioFlinger::RecordThread::clearSyncStartEvent()
6267{
6268 if (mSyncStartEvent != 0) {
6269 mSyncStartEvent->cancel();
6270 }
6271 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006272 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006273}
6274
6275void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6276{
6277 sp<SyncEvent> strongEvent = event.promote();
6278
6279 if (strongEvent != 0) {
6280 RecordThread *me = (RecordThread *)strongEvent->cookie();
6281 me->handleSyncStartEvent(strongEvent);
6282 }
6283}
6284
6285void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6286{
Eric Laurent29864602012-05-08 18:57:51 -07006287 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006288 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6289 // from audio HAL
6290 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006291 }
6292}
6293
Mathias Agopian65ab4712010-07-14 17:59:35 -07006294void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006295 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006296 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006297 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006298 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006299 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6300 mActiveTrack->mState = TrackBase::PAUSING;
6301 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006302 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006303 return;
6304 }
6305 mStartStopCond.wait(mLock);
6306 // if we have been restarted, recordTrack == mActiveTrack.get() here
6307 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6308 mLock.unlock();
6309 AudioSystem::stopInput(mId);
6310 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006311 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006312 }
6313 }
6314 }
6315}
6316
Eric Laurenta011e352012-03-29 15:51:43 -07006317bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6318{
6319 return false;
6320}
6321
6322status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6323{
6324 if (!isValidSyncEvent(event)) {
6325 return BAD_VALUE;
6326 }
6327
6328 Mutex::Autolock _l(mLock);
6329
6330 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6331 mTrack->setSyncEvent(event);
6332 return NO_ERROR;
6333 }
6334 return NAME_NOT_FOUND;
6335}
6336
Mathias Agopian65ab4712010-07-14 17:59:35 -07006337status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6338{
6339 const size_t SIZE = 256;
6340 char buffer[SIZE];
6341 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006342
6343 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6344 result.append(buffer);
6345
6346 if (mActiveTrack != 0) {
6347 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006348 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006349 mActiveTrack->dump(buffer, SIZE);
6350 result.append(buffer);
6351
6352 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6353 result.append(buffer);
6354 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6355 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006356 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006357 result.append(buffer);
6358 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6359 result.append(buffer);
6360 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6361 result.append(buffer);
6362
6363
6364 } else {
6365 result.append("No record client\n");
6366 }
6367 write(fd, result.string(), result.size());
6368
6369 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006370 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006371
6372 return NO_ERROR;
6373}
6374
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006375// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006376status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006377{
6378 size_t framesReq = buffer->frameCount;
6379 size_t framesReady = mFrameCount - mRsmpInIndex;
6380 int channelCount;
6381
6382 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006383 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006384 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006385 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006386 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6387 // Force input into standby so that it tries to
6388 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006389 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006390 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006391 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006392 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006393 buffer->frameCount = 0;
6394 return NOT_ENOUGH_DATA;
6395 }
6396 mRsmpInIndex = 0;
6397 framesReady = mFrameCount;
6398 }
6399
6400 if (framesReq > framesReady) {
6401 framesReq = framesReady;
6402 }
6403
6404 if (mChannelCount == 1 && mReqChannelCount == 2) {
6405 channelCount = 1;
6406 } else {
6407 channelCount = 2;
6408 }
6409 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6410 buffer->frameCount = framesReq;
6411 return NO_ERROR;
6412}
6413
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006414// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006415void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6416{
6417 mRsmpInIndex += buffer->frameCount;
6418 buffer->frameCount = 0;
6419}
6420
6421bool AudioFlinger::RecordThread::checkForNewParameters_l()
6422{
6423 bool reconfig = false;
6424
6425 while (!mNewParameters.isEmpty()) {
6426 status_t status = NO_ERROR;
6427 String8 keyValuePair = mNewParameters[0];
6428 AudioParameter param = AudioParameter(keyValuePair);
6429 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006430 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006431 int reqSamplingRate = mReqSampleRate;
6432 int reqChannelCount = mReqChannelCount;
6433
6434 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6435 reqSamplingRate = value;
6436 reconfig = true;
6437 }
6438 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006439 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006440 reconfig = true;
6441 }
6442 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006443 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006444 reconfig = true;
6445 }
6446 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6447 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006448 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006449 // if frame count is changed after track creation
6450 if (mActiveTrack != 0) {
6451 status = INVALID_OPERATION;
6452 } else {
6453 reconfig = true;
6454 }
6455 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006456 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6457 // forward device change to effects that have requested to be
6458 // aware of attached audio device.
6459 for (size_t i = 0; i < mEffectChains.size(); i++) {
6460 mEffectChains[i]->setDevice_l(value);
6461 }
6462 // store input device and output device but do not forward output device to audio HAL.
6463 // Note that status is ignored by the caller for output device
6464 // (see AudioFlinger::setParameters()
Glenn Kasten94479fd2012-07-09 15:39:54 -07006465 uint32_t /*audio_devices_t*/ newDevice = mDevice;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006466 if (value & AUDIO_DEVICE_OUT_ALL) {
Glenn Kasten01542f22012-07-02 12:46:15 -07006467 newDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006468 status = BAD_VALUE;
6469 } else {
Glenn Kasten01542f22012-07-02 12:46:15 -07006470 newDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006471 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6472 if (mTrack != NULL) {
6473 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006474 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006475 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6476 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6477 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006478 }
Glenn Kasten01542f22012-07-02 12:46:15 -07006479 newDevice |= value;
Glenn Kasten94479fd2012-07-09 15:39:54 -07006480 mDevice = (audio_devices_t) newDevice; // since mDevice is read by other threads, only write to it once
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006481 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006482 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006483 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006484 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006485 mInput->stream->common.standby(&mInput->stream->common);
6486 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6487 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006488 }
6489 if (reconfig) {
6490 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006491 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006492 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006493 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006494 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6495 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006496 status = NO_ERROR;
6497 }
6498 if (status == NO_ERROR) {
6499 readInputParameters();
6500 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6501 }
6502 }
6503 }
6504
6505 mNewParameters.removeAt(0);
6506
6507 mParamStatus = status;
6508 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006509 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6510 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006511 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006512 }
6513 return reconfig;
6514}
6515
6516String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6517{
Dima Zavinfce7a472011-04-19 22:30:36 -07006518 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006519 String8 out_s8 = String8();
6520
6521 Mutex::Autolock _l(mLock);
6522 if (initCheck() != NO_ERROR) {
6523 return out_s8;
6524 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006525
Dima Zavin799a70e2011-04-18 16:57:27 -07006526 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006527 out_s8 = String8(s);
6528 free(s);
6529 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006530}
6531
6532void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6533 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006534 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006535
6536 switch (event) {
6537 case AudioSystem::INPUT_OPENED:
6538 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006539 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006540 desc.samplingRate = mSampleRate;
6541 desc.format = mFormat;
6542 desc.frameCount = mFrameCount;
6543 desc.latency = 0;
6544 param2 = &desc;
6545 break;
6546
6547 case AudioSystem::INPUT_CLOSED:
6548 default:
6549 break;
6550 }
6551 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6552}
6553
6554void AudioFlinger::RecordThread::readInputParameters()
6555{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006556 delete mRsmpInBuffer;
6557 // mRsmpInBuffer is always assigned a new[] below
6558 delete mRsmpOutBuffer;
6559 mRsmpOutBuffer = NULL;
6560 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006561 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006562
Dima Zavin799a70e2011-04-18 16:57:27 -07006563 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006564 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6565 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006566 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006567 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006568 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006569 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006570 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006571 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6572
Glenn Kasten53d76db2012-03-08 12:32:47 -08006573 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006574 {
6575 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006576 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6577 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006578 if (mChannelCount == 1 && mReqChannelCount == 2) {
6579 channelCount = 1;
6580 } else {
6581 channelCount = 2;
6582 }
6583 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6584 mResampler->setSampleRate(mSampleRate);
6585 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6586 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6587
6588 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6589 if (mChannelCount == 1 && mReqChannelCount == 1) {
6590 mFrameCount >>= 1;
6591 }
6592
6593 }
6594 mRsmpInIndex = mFrameCount;
6595}
6596
6597unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6598{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006599 Mutex::Autolock _l(mLock);
6600 if (initCheck() != NO_ERROR) {
6601 return 0;
6602 }
6603
Dima Zavin799a70e2011-04-18 16:57:27 -07006604 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006605}
6606
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006607uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6608{
6609 Mutex::Autolock _l(mLock);
6610 uint32_t result = 0;
6611 if (getEffectChain_l(sessionId) != 0) {
6612 result = EFFECT_SESSION;
6613 }
6614
6615 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6616 result |= TRACK_SESSION;
6617 }
6618
6619 return result;
6620}
6621
Eric Laurent59bd0da2011-08-01 09:52:20 -07006622AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6623{
6624 Mutex::Autolock _l(mLock);
6625 return mTrack;
6626}
6627
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006628AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6629{
6630 Mutex::Autolock _l(mLock);
6631 AudioStreamIn *input = mInput;
6632 mInput = NULL;
6633 return input;
6634}
6635
6636// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006637audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006638{
6639 if (mInput == NULL) {
6640 return NULL;
6641 }
6642 return &mInput->stream->common;
6643}
6644
6645
Mathias Agopian65ab4712010-07-14 17:59:35 -07006646// ----------------------------------------------------------------------------
6647
Eric Laurenta4c5a552012-03-29 10:12:40 -07006648audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6649{
6650 if (!settingsAllowed()) {
6651 return 0;
6652 }
6653 Mutex::Autolock _l(mLock);
6654 return loadHwModule_l(name);
6655}
6656
6657// loadHwModule_l() must be called with AudioFlinger::mLock held
6658audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6659{
6660 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6661 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6662 ALOGW("loadHwModule() module %s already loaded", name);
6663 return mAudioHwDevs.keyAt(i);
6664 }
6665 }
6666
Eric Laurenta4c5a552012-03-29 10:12:40 -07006667 audio_hw_device_t *dev;
6668
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006669 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006670 if (rc) {
6671 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6672 return 0;
6673 }
6674
6675 mHardwareStatus = AUDIO_HW_INIT;
6676 rc = dev->init_check(dev);
6677 mHardwareStatus = AUDIO_HW_IDLE;
6678 if (rc) {
6679 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6680 return 0;
6681 }
6682
6683 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6684 (NULL != dev->set_master_volume)) {
6685 AutoMutex lock(mHardwareLock);
6686 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6687 dev->set_master_volume(dev, mMasterVolume);
6688 mHardwareStatus = AUDIO_HW_IDLE;
6689 }
6690
6691 audio_module_handle_t handle = nextUniqueId();
6692 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6693
6694 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006695 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006696
6697 return handle;
6698
6699}
6700
6701audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6702 audio_devices_t *pDevices,
6703 uint32_t *pSamplingRate,
6704 audio_format_t *pFormat,
6705 audio_channel_mask_t *pChannelMask,
6706 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006707 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006708{
6709 status_t status;
6710 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006711 struct audio_config config = {
6712 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6713 channel_mask: pChannelMask ? *pChannelMask : 0,
6714 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6715 };
6716 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006717 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006718
Eric Laurenta4c5a552012-03-29 10:12:40 -07006719 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6720 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006721 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006722 config.sample_rate,
6723 config.format,
6724 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006725 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006726
6727 if (pDevices == NULL || *pDevices == 0) {
6728 return 0;
6729 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006730
Mathias Agopian65ab4712010-07-14 17:59:35 -07006731 Mutex::Autolock _l(mLock);
6732
Eric Laurenta4c5a552012-03-29 10:12:40 -07006733 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006734 if (outHwDev == NULL)
6735 return 0;
6736
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006737 audio_io_handle_t id = nextUniqueId();
6738
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006739 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006740
6741 status = outHwDev->open_output_stream(outHwDev,
6742 id,
6743 *pDevices,
6744 (audio_output_flags_t)flags,
6745 &config,
6746 &outStream);
6747
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006748 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006749 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006750 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006751 config.sample_rate,
6752 config.format,
6753 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006754 status);
6755
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006756 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006757 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006758
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006759 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006760 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6761 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006762 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006763 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006764 } else {
6765 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006766 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006767 }
6768 mPlaybackThreads.add(id, thread);
6769
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006770 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6771 if (pFormat != NULL) *pFormat = config.format;
6772 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006773 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006774
6775 // notify client processes of the new output creation
6776 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006777
6778 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006779 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006780 ALOGI("Using module %d has the primary audio interface", module);
6781 mPrimaryHardwareDev = outHwDev;
6782
6783 AutoMutex lock(mHardwareLock);
6784 mHardwareStatus = AUDIO_HW_SET_MODE;
6785 outHwDev->set_mode(outHwDev, mMode);
6786
6787 // Determine the level of master volume support the primary audio HAL has,
6788 // and set the initial master volume at the same time.
6789 float initialVolume = 1.0;
6790 mMasterVolumeSupportLvl = MVS_NONE;
6791
6792 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6793 if ((NULL != outHwDev->get_master_volume) &&
6794 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6795 mMasterVolumeSupportLvl = MVS_FULL;
6796 } else {
6797 mMasterVolumeSupportLvl = MVS_SETONLY;
6798 initialVolume = 1.0;
6799 }
6800
6801 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6802 if ((NULL == outHwDev->set_master_volume) ||
6803 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6804 mMasterVolumeSupportLvl = MVS_NONE;
6805 }
6806 // now that we have a primary device, initialize master volume on other devices
6807 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6808 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6809
6810 if ((dev != mPrimaryHardwareDev) &&
6811 (NULL != dev->set_master_volume)) {
6812 dev->set_master_volume(dev, initialVolume);
6813 }
6814 }
6815 mHardwareStatus = AUDIO_HW_IDLE;
6816 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6817 ? initialVolume
6818 : 1.0;
6819 mMasterVolume = initialVolume;
6820 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006821 return id;
6822 }
6823
6824 return 0;
6825}
6826
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006827audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6828 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006829{
6830 Mutex::Autolock _l(mLock);
6831 MixerThread *thread1 = checkMixerThread_l(output1);
6832 MixerThread *thread2 = checkMixerThread_l(output2);
6833
6834 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006835 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006836 return 0;
6837 }
6838
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006839 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006840 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6841 thread->addOutputTrack(thread2);
6842 mPlaybackThreads.add(id, thread);
6843 // notify client processes of the new output creation
6844 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6845 return id;
6846}
6847
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006848status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006849{
6850 // keep strong reference on the playback thread so that
6851 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006852 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006853 {
6854 Mutex::Autolock _l(mLock);
6855 thread = checkPlaybackThread_l(output);
6856 if (thread == NULL) {
6857 return BAD_VALUE;
6858 }
6859
Steve Block3856b092011-10-20 11:56:00 +01006860 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006861
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006862 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006863 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006864 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006865 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6866 dupThread->removeOutputTrack((MixerThread *)thread.get());
6867 }
6868 }
6869 }
Glenn Kastena1117922012-01-26 10:53:32 -08006870 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006871 mPlaybackThreads.removeItem(output);
6872 }
6873 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006874 // The thread entity (active unit of execution) is no longer running here,
6875 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006876
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006877 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006878 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006879 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006880 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006881 out->hwDev->close_output_stream(out->hwDev, out->stream);
6882 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006883 }
6884 return NO_ERROR;
6885}
6886
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006887status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006888{
6889 Mutex::Autolock _l(mLock);
6890 PlaybackThread *thread = checkPlaybackThread_l(output);
6891
6892 if (thread == NULL) {
6893 return BAD_VALUE;
6894 }
6895
Steve Block3856b092011-10-20 11:56:00 +01006896 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006897 thread->suspend();
6898
6899 return NO_ERROR;
6900}
6901
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006902status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006903{
6904 Mutex::Autolock _l(mLock);
6905 PlaybackThread *thread = checkPlaybackThread_l(output);
6906
6907 if (thread == NULL) {
6908 return BAD_VALUE;
6909 }
6910
Steve Block3856b092011-10-20 11:56:00 +01006911 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006912
6913 thread->restore();
6914
6915 return NO_ERROR;
6916}
6917
Eric Laurenta4c5a552012-03-29 10:12:40 -07006918audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6919 audio_devices_t *pDevices,
6920 uint32_t *pSamplingRate,
6921 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07006922 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006923{
6924 status_t status;
6925 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006926 struct audio_config config = {
6927 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6928 channel_mask: pChannelMask ? *pChannelMask : 0,
6929 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6930 };
6931 uint32_t reqSamplingRate = config.sample_rate;
6932 audio_format_t reqFormat = config.format;
6933 audio_channel_mask_t reqChannels = config.channel_mask;
6934 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006935 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006936
6937 if (pDevices == NULL || *pDevices == 0) {
6938 return 0;
6939 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006940
Mathias Agopian65ab4712010-07-14 17:59:35 -07006941 Mutex::Autolock _l(mLock);
6942
Eric Laurenta4c5a552012-03-29 10:12:40 -07006943 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006944 if (inHwDev == NULL)
6945 return 0;
6946
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006947 audio_io_handle_t id = nextUniqueId();
6948
6949 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006950 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006951 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006952 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006953 config.sample_rate,
6954 config.format,
6955 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006956 status);
6957
6958 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6959 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6960 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006961 if (status == BAD_VALUE &&
6962 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6963 (config.sample_rate <= 2 * reqSamplingRate) &&
6964 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07006965 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006966 inStream = NULL;
6967 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006968 }
6969
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006970 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006971 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6972
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006973 // Start record thread
6974 // RecorThread require both input and output device indication to forward to audio
6975 // pre processing modules
6976 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6977 thread = new RecordThread(this,
6978 input,
6979 reqSamplingRate,
6980 reqChannels,
6981 id,
6982 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006983 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006984 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006985 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006986 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006987 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006988
Dima Zavin799a70e2011-04-18 16:57:27 -07006989 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006990
6991 // notify client processes of the new input creation
6992 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
6993 return id;
6994 }
6995
6996 return 0;
6997}
6998
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006999status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007000{
7001 // keep strong reference on the record thread so that
7002 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007003 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007004 {
7005 Mutex::Autolock _l(mLock);
7006 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007007 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007008 return BAD_VALUE;
7009 }
7010
Steve Block3856b092011-10-20 11:56:00 +01007011 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007012 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007013 mRecordThreads.removeItem(input);
7014 }
7015 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007016 // The thread entity (active unit of execution) is no longer running here,
7017 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007018
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007019 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007020 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007021 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07007022 in->hwDev->close_input_stream(in->hwDev, in->stream);
7023 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007024
7025 return NO_ERROR;
7026}
7027
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007028status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007029{
7030 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007031 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007032
7033 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7034 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007035 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007036 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007037
7038 return NO_ERROR;
7039}
7040
7041
7042int AudioFlinger::newAudioSessionId()
7043{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007044 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007045}
7046
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007047void AudioFlinger::acquireAudioSessionId(int audioSession)
7048{
7049 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007050 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007051 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007052 size_t num = mAudioSessionRefs.size();
7053 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007054 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007055 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7056 ref->mCnt++;
7057 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007058 return;
7059 }
7060 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007061 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7062 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007063}
7064
7065void AudioFlinger::releaseAudioSessionId(int audioSession)
7066{
7067 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007068 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007069 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007070 size_t num = mAudioSessionRefs.size();
7071 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007072 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007073 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7074 ref->mCnt--;
7075 ALOGV(" decremented refcount to %d", ref->mCnt);
7076 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007077 mAudioSessionRefs.removeAt(i);
7078 delete ref;
7079 purgeStaleEffects_l();
7080 }
7081 return;
7082 }
7083 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007084 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007085}
7086
7087void AudioFlinger::purgeStaleEffects_l() {
7088
Steve Block3856b092011-10-20 11:56:00 +01007089 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007090
7091 Vector< sp<EffectChain> > chains;
7092
7093 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7094 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7095 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7096 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007097 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7098 chains.push(ec);
7099 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007100 }
7101 }
7102 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7103 sp<RecordThread> t = mRecordThreads.valueAt(i);
7104 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7105 sp<EffectChain> ec = t->mEffectChains[j];
7106 chains.push(ec);
7107 }
7108 }
7109
7110 for (size_t i = 0; i < chains.size(); i++) {
7111 sp<EffectChain> ec = chains[i];
7112 int sessionid = ec->sessionId();
7113 sp<ThreadBase> t = ec->mThread.promote();
7114 if (t == 0) {
7115 continue;
7116 }
7117 size_t numsessionrefs = mAudioSessionRefs.size();
7118 bool found = false;
7119 for (size_t k = 0; k < numsessionrefs; k++) {
7120 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007121 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007122 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007123 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007124 found = true;
7125 break;
7126 }
7127 }
7128 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007129 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007130 // remove all effects from the chain
7131 while (ec->mEffects.size()) {
7132 sp<EffectModule> effect = ec->mEffects[0];
7133 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007134 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007135 if (effect->purgeHandles()) {
7136 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007137 }
7138 AudioSystem::unregisterEffect(effect->id());
7139 }
7140 }
7141 }
7142 return;
7143}
7144
Mathias Agopian65ab4712010-07-14 17:59:35 -07007145// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007146AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007147{
Glenn Kastena1117922012-01-26 10:53:32 -08007148 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007149}
7150
7151// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007152AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007153{
7154 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007155 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007156}
7157
7158// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007159AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007160{
Glenn Kastena1117922012-01-26 10:53:32 -08007161 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007162}
7163
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007164uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007165{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007166 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007167}
7168
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007169AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007170{
7171 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7172 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007173 AudioStreamOut *output = thread->getOutput();
7174 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007175 return thread;
7176 }
7177 }
7178 return NULL;
7179}
7180
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007181uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007182{
7183 PlaybackThread *thread = primaryPlaybackThread_l();
7184
7185 if (thread == NULL) {
7186 return 0;
7187 }
7188
7189 return thread->device();
7190}
7191
Eric Laurenta011e352012-03-29 15:51:43 -07007192sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7193 int triggerSession,
7194 int listenerSession,
7195 sync_event_callback_t callBack,
7196 void *cookie)
7197{
7198 Mutex::Autolock _l(mLock);
7199
7200 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7201 status_t playStatus = NAME_NOT_FOUND;
7202 status_t recStatus = NAME_NOT_FOUND;
7203 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7204 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7205 if (playStatus == NO_ERROR) {
7206 return event;
7207 }
7208 }
7209 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7210 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7211 if (recStatus == NO_ERROR) {
7212 return event;
7213 }
7214 }
7215 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7216 mPendingSyncEvents.add(event);
7217 } else {
7218 ALOGV("createSyncEvent() invalid event %d", event->type());
7219 event.clear();
7220 }
7221 return event;
7222}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007223
Mathias Agopian65ab4712010-07-14 17:59:35 -07007224// ----------------------------------------------------------------------------
7225// Effect management
7226// ----------------------------------------------------------------------------
7227
7228
Glenn Kastenf587ba52012-01-26 16:25:10 -08007229status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007230{
7231 Mutex::Autolock _l(mLock);
7232 return EffectQueryNumberEffects(numEffects);
7233}
7234
Glenn Kastenf587ba52012-01-26 16:25:10 -08007235status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007236{
7237 Mutex::Autolock _l(mLock);
7238 return EffectQueryEffect(index, descriptor);
7239}
7240
Glenn Kasten5e92a782012-01-30 07:40:52 -08007241status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007242 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007243{
7244 Mutex::Autolock _l(mLock);
7245 return EffectGetDescriptor(pUuid, descriptor);
7246}
7247
7248
Mathias Agopian65ab4712010-07-14 17:59:35 -07007249sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7250 effect_descriptor_t *pDesc,
7251 const sp<IEffectClient>& effectClient,
7252 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007253 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007254 int sessionId,
7255 status_t *status,
7256 int *id,
7257 int *enabled)
7258{
7259 status_t lStatus = NO_ERROR;
7260 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007261 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007262
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007263 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007264 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007265
7266 if (pDesc == NULL) {
7267 lStatus = BAD_VALUE;
7268 goto Exit;
7269 }
7270
Eric Laurent84e9a102010-09-23 16:10:16 -07007271 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007272 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007273 lStatus = PERMISSION_DENIED;
7274 goto Exit;
7275 }
7276
Dima Zavinfce7a472011-04-19 22:30:36 -07007277 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007278 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007279 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007280 lStatus = PERMISSION_DENIED;
7281 goto Exit;
7282 }
7283
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007284 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007285 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007286 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007287 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007288 lStatus = BAD_VALUE;
7289 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007290 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007291 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007292 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007293 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007294 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007295 }
7296 }
7297
Mathias Agopian65ab4712010-07-14 17:59:35 -07007298 {
7299 Mutex::Autolock _l(mLock);
7300
Mathias Agopian65ab4712010-07-14 17:59:35 -07007301
7302 if (!EffectIsNullUuid(&pDesc->uuid)) {
7303 // if uuid is specified, request effect descriptor
7304 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7305 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007306 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007307 goto Exit;
7308 }
7309 } else {
7310 // if uuid is not specified, look for an available implementation
7311 // of the required type in effect factory
7312 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007313 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007314 lStatus = BAD_VALUE;
7315 goto Exit;
7316 }
7317 uint32_t numEffects = 0;
7318 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007319 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007320 bool found = false;
7321
7322 lStatus = EffectQueryNumberEffects(&numEffects);
7323 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007324 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007325 goto Exit;
7326 }
7327 for (uint32_t i = 0; i < numEffects; i++) {
7328 lStatus = EffectQueryEffect(i, &desc);
7329 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007330 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007331 continue;
7332 }
7333 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7334 // If matching type found save effect descriptor. If the session is
7335 // 0 and the effect is not auxiliary, continue enumeration in case
7336 // an auxiliary version of this effect type is available
7337 found = true;
7338 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07007339 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007340 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7341 break;
7342 }
7343 }
7344 }
7345 if (!found) {
7346 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007347 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007348 goto Exit;
7349 }
7350 // For same effect type, chose auxiliary version over insert version if
7351 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007352 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007353 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7354 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7355 }
7356 }
7357
7358 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007359 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007360 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7361 lStatus = INVALID_OPERATION;
7362 goto Exit;
7363 }
7364
Eric Laurent59255e42011-07-27 19:49:51 -07007365 // check recording permission for visualizer
7366 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7367 !recordingAllowed()) {
7368 lStatus = PERMISSION_DENIED;
7369 goto Exit;
7370 }
7371
Mathias Agopian65ab4712010-07-14 17:59:35 -07007372 // return effect descriptor
7373 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7374
7375 // If output is not specified try to find a matching audio session ID in one of the
7376 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007377 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7378 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007379 // Note: io is never 0 when creating an effect on an input
7380 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007381 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007382 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7383 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007384 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007385 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007386 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007387 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007388 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007389 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7390 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7391 io = mRecordThreads.keyAt(i);
7392 break;
7393 }
7394 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007395 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007396 // If no output thread contains the requested session ID, default to
7397 // first output. The effect chain will be moved to the correct output
7398 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007399 if (io == 0 && mPlaybackThreads.size()) {
7400 io = mPlaybackThreads.keyAt(0);
7401 }
Steve Block3856b092011-10-20 11:56:00 +01007402 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007403 }
7404 ThreadBase *thread = checkRecordThread_l(io);
7405 if (thread == NULL) {
7406 thread = checkPlaybackThread_l(io);
7407 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007408 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007409 lStatus = BAD_VALUE;
7410 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007411 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007412 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007413
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007414 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007415
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007416 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007417 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7418 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007419 if (handle != 0 && id != NULL) {
7420 *id = handle->id();
7421 }
7422 }
7423
7424Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007425 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007426 *status = lStatus;
7427 }
7428 return handle;
7429}
7430
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007431status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7432 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007433{
Steve Block3856b092011-10-20 11:56:00 +01007434 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007435 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007436 Mutex::Autolock _l(mLock);
7437 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007438 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007439 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007440 }
Eric Laurentde070132010-07-13 04:45:46 -07007441 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7442 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007443 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007444 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007445 }
Eric Laurentde070132010-07-13 04:45:46 -07007446 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7447 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007448 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007449 return BAD_VALUE;
7450 }
7451
7452 Mutex::Autolock _dl(dstThread->mLock);
7453 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007454 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007455
Mathias Agopian65ab4712010-07-14 17:59:35 -07007456 return NO_ERROR;
7457}
7458
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007459// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007460status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007461 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007462 AudioFlinger::PlaybackThread *dstThread,
7463 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007464{
Steve Block3856b092011-10-20 11:56:00 +01007465 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007466 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007467
Eric Laurent59255e42011-07-27 19:49:51 -07007468 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007469 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007470 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007471 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007472 return INVALID_OPERATION;
7473 }
7474
Eric Laurent39e94f82010-07-28 01:32:47 -07007475 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007476 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007477 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007478 // removed.
7479 srcThread->removeEffectChain_l(chain);
7480
7481 // transfer all effects one by one so that new effect chain is created on new thread with
7482 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007483 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007484 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007485 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007486 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7487 while (effect != 0) {
7488 srcThread->removeEffect_l(effect);
7489 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007490 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7491 if (effect->state() == EffectModule::ACTIVE ||
7492 effect->state() == EffectModule::STOPPING) {
7493 effect->start();
7494 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007495 // if the move request is not received from audio policy manager, the effect must be
7496 // re-registered with the new strategy and output
7497 if (dstChain == 0) {
7498 dstChain = effect->chain().promote();
7499 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007500 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007501 srcThread->addEffect_l(effect);
7502 return NO_INIT;
7503 }
7504 strategy = dstChain->strategy();
7505 }
7506 if (reRegister) {
7507 AudioSystem::unregisterEffect(effect->id());
7508 AudioSystem::registerEffect(&effect->desc(),
7509 dstOutput,
7510 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007511 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007512 effect->id());
7513 }
Eric Laurentde070132010-07-13 04:45:46 -07007514 effect = chain->getEffectFromId_l(0);
7515 }
7516
7517 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007518}
7519
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007520
Mathias Agopian65ab4712010-07-14 17:59:35 -07007521// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007522sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007523 const sp<AudioFlinger::Client>& client,
7524 const sp<IEffectClient>& effectClient,
7525 int32_t priority,
7526 int sessionId,
7527 effect_descriptor_t *desc,
7528 int *enabled,
7529 status_t *status
7530 )
7531{
7532 sp<EffectModule> effect;
7533 sp<EffectHandle> handle;
7534 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007535 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007536 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007537 bool effectCreated = false;
7538 bool effectRegistered = false;
7539
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007540 lStatus = initCheck();
7541 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007542 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007543 goto Exit;
7544 }
7545
7546 // Do not allow effects with session ID 0 on direct output or duplicating threads
7547 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007548 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007549 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007550 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007551 lStatus = BAD_VALUE;
7552 goto Exit;
7553 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007554 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007555 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007556 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007557 desc->name, desc->flags, mType);
7558 lStatus = BAD_VALUE;
7559 goto Exit;
7560 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007561
Steve Block3856b092011-10-20 11:56:00 +01007562 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007563
7564 { // scope for mLock
7565 Mutex::Autolock _l(mLock);
7566
7567 // check for existing effect chain with the requested audio session
7568 chain = getEffectChain_l(sessionId);
7569 if (chain == 0) {
7570 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007571 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007572 chain = new EffectChain(this, sessionId);
7573 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007574 chain->setStrategy(getStrategyForSession_l(sessionId));
7575 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007576 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007577 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007578 }
7579
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007580 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007581
7582 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007583 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007584 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007585 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007586 if (lStatus != NO_ERROR) {
7587 goto Exit;
7588 }
7589 effectRegistered = true;
7590 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007591 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007592 lStatus = effect->status();
7593 if (lStatus != NO_ERROR) {
7594 goto Exit;
7595 }
Eric Laurentcab11242010-07-15 12:50:15 -07007596 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007597 if (lStatus != NO_ERROR) {
7598 goto Exit;
7599 }
7600 effectCreated = true;
7601
7602 effect->setDevice(mDevice);
7603 effect->setMode(mAudioFlinger->getMode());
7604 }
7605 // create effect handle and connect it to effect module
7606 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007607 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007608 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007609 *enabled = (int)effect->isEnabled();
7610 }
7611 }
7612
7613Exit:
7614 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007615 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007616 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007617 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007618 }
7619 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007620 AudioSystem::unregisterEffect(effect->id());
7621 }
7622 if (chainCreated) {
7623 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007624 }
7625 handle.clear();
7626 }
7627
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007628 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007629 *status = lStatus;
7630 }
7631 return handle;
7632}
7633
Eric Laurent717e1282012-06-29 16:36:52 -07007634sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7635{
7636 Mutex::Autolock _l(mLock);
7637 return getEffect_l(sessionId, effectId);
7638}
7639
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007640sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7641{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007642 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007643 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007644}
7645
Eric Laurentde070132010-07-13 04:45:46 -07007646// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7647// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007648status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007649{
7650 // check for existing effect chain with the requested audio session
7651 int sessionId = effect->sessionId();
7652 sp<EffectChain> chain = getEffectChain_l(sessionId);
7653 bool chainCreated = false;
7654
7655 if (chain == 0) {
7656 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007657 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007658 chain = new EffectChain(this, sessionId);
7659 addEffectChain_l(chain);
7660 chain->setStrategy(getStrategyForSession_l(sessionId));
7661 chainCreated = true;
7662 }
Steve Block3856b092011-10-20 11:56:00 +01007663 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007664
7665 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007666 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007667 this, effect->desc().name, chain.get());
7668 return BAD_VALUE;
7669 }
7670
7671 status_t status = chain->addEffect_l(effect);
7672 if (status != NO_ERROR) {
7673 if (chainCreated) {
7674 removeEffectChain_l(chain);
7675 }
7676 return status;
7677 }
7678
7679 effect->setDevice(mDevice);
7680 effect->setMode(mAudioFlinger->getMode());
7681 return NO_ERROR;
7682}
7683
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007684void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007685
Steve Block3856b092011-10-20 11:56:00 +01007686 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007687 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007688 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7689 detachAuxEffect_l(effect->id());
7690 }
7691
7692 sp<EffectChain> chain = effect->chain().promote();
7693 if (chain != 0) {
7694 // remove effect chain if removing last effect
7695 if (chain->removeEffect_l(effect) == 0) {
7696 removeEffectChain_l(chain);
7697 }
7698 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007699 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007700 }
7701}
7702
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007703void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007704 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007705{
7706 effectChains = mEffectChains;
7707 for (size_t i = 0; i < mEffectChains.size(); i++) {
7708 mEffectChains[i]->lock();
7709 }
7710}
7711
7712void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007713 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007714{
7715 for (size_t i = 0; i < effectChains.size(); i++) {
7716 effectChains[i]->unlock();
7717 }
7718}
7719
7720sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7721{
7722 Mutex::Autolock _l(mLock);
7723 return getEffectChain_l(sessionId);
7724}
7725
7726sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7727{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007728 size_t size = mEffectChains.size();
7729 for (size_t i = 0; i < size; i++) {
7730 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007731 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007732 }
7733 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007734 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007735}
7736
Glenn Kastenf78aee72012-01-04 11:00:47 -08007737void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007738{
7739 Mutex::Autolock _l(mLock);
7740 size_t size = mEffectChains.size();
7741 for (size_t i = 0; i < size; i++) {
7742 mEffectChains[i]->setMode_l(mode);
7743 }
7744}
7745
7746void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007747 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007748 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007749
Mathias Agopian65ab4712010-07-14 17:59:35 -07007750 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007751 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007752 // delete the effect module if removing last handle on it
7753 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007754 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007755 removeEffect_l(effect);
7756 AudioSystem::unregisterEffect(effect->id());
7757 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007758 }
7759}
7760
7761status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7762{
7763 int session = chain->sessionId();
7764 int16_t *buffer = mMixBuffer;
7765 bool ownsBuffer = false;
7766
Steve Block3856b092011-10-20 11:56:00 +01007767 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007768 if (session > 0) {
7769 // Only one effect chain can be present in direct output thread and it uses
7770 // the mix buffer as input
7771 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007772 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007773 buffer = new int16_t[numSamples];
7774 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007775 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007776 ownsBuffer = true;
7777 }
7778
7779 // Attach all tracks with same session ID to this chain.
7780 for (size_t i = 0; i < mTracks.size(); ++i) {
7781 sp<Track> track = mTracks[i];
7782 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007783 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007784 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007785 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007786 }
7787 }
7788
7789 // indicate all active tracks in the chain
7790 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7791 sp<Track> track = mActiveTracks[i].promote();
7792 if (track == 0) continue;
7793 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007794 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007795 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007796 }
7797 }
7798 }
7799
7800 chain->setInBuffer(buffer, ownsBuffer);
7801 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007802 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007803 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007804 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7805 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007806 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007807 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7808 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007809 // Effect chain for other sessions are inserted at beginning of effect
7810 // chains list to be processed before output mix effects. Relative order between other
7811 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007812 size_t size = mEffectChains.size();
7813 size_t i = 0;
7814 for (i = 0; i < size; i++) {
7815 if (mEffectChains[i]->sessionId() < session) break;
7816 }
7817 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007818 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007819
7820 return NO_ERROR;
7821}
7822
7823size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7824{
7825 int session = chain->sessionId();
7826
Steve Block3856b092011-10-20 11:56:00 +01007827 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007828
7829 for (size_t i = 0; i < mEffectChains.size(); i++) {
7830 if (chain == mEffectChains[i]) {
7831 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007832 // detach all active tracks from the chain
7833 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7834 sp<Track> track = mActiveTracks[i].promote();
7835 if (track == 0) continue;
7836 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007837 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007838 chain.get(), session);
7839 chain->decActiveTrackCnt();
7840 }
7841 }
7842
Mathias Agopian65ab4712010-07-14 17:59:35 -07007843 // detach all tracks with same session ID from this chain
7844 for (size_t i = 0; i < mTracks.size(); ++i) {
7845 sp<Track> track = mTracks[i];
7846 if (session == track->sessionId()) {
7847 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007848 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007849 }
7850 }
Eric Laurentde070132010-07-13 04:45:46 -07007851 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007852 }
7853 }
7854 return mEffectChains.size();
7855}
7856
Eric Laurentde070132010-07-13 04:45:46 -07007857status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7858 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007859{
7860 Mutex::Autolock _l(mLock);
7861 return attachAuxEffect_l(track, EffectId);
7862}
7863
Eric Laurentde070132010-07-13 04:45:46 -07007864status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7865 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007866{
7867 status_t status = NO_ERROR;
7868
7869 if (EffectId == 0) {
7870 track->setAuxBuffer(0, NULL);
7871 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007872 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7873 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007874 if (effect != 0) {
7875 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7876 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7877 } else {
7878 status = INVALID_OPERATION;
7879 }
7880 } else {
7881 status = BAD_VALUE;
7882 }
7883 }
7884 return status;
7885}
7886
7887void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7888{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007889 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007890 sp<Track> track = mTracks[i];
7891 if (track->auxEffectId() == effectId) {
7892 attachAuxEffect_l(track, 0);
7893 }
7894 }
7895}
7896
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007897status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7898{
7899 // only one chain per input thread
7900 if (mEffectChains.size() != 0) {
7901 return INVALID_OPERATION;
7902 }
Steve Block3856b092011-10-20 11:56:00 +01007903 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007904
7905 chain->setInBuffer(NULL);
7906 chain->setOutBuffer(NULL);
7907
Eric Laurent59255e42011-07-27 19:49:51 -07007908 checkSuspendOnAddEffectChain_l(chain);
7909
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007910 mEffectChains.add(chain);
7911
7912 return NO_ERROR;
7913}
7914
7915size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7916{
Steve Block3856b092011-10-20 11:56:00 +01007917 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007918 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007919 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7920 chain.get(), mEffectChains.size(), this);
7921 if (mEffectChains.size() == 1) {
7922 mEffectChains.removeAt(0);
7923 }
7924 return 0;
7925}
7926
Mathias Agopian65ab4712010-07-14 17:59:35 -07007927// ----------------------------------------------------------------------------
7928// EffectModule implementation
7929// ----------------------------------------------------------------------------
7930
7931#undef LOG_TAG
7932#define LOG_TAG "AudioFlinger::EffectModule"
7933
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007934AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007935 const wp<AudioFlinger::EffectChain>& chain,
7936 effect_descriptor_t *desc,
7937 int id,
7938 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07007939 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
7940 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
7941 // mDescriptor is set below
7942 // mConfig is set by configure() and not used before then
7943 mEffectInterface(NULL),
7944 mStatus(NO_INIT), mState(IDLE),
7945 // mMaxDisableWaitCnt is set by configure() and not used before then
7946 // mDisableWaitCnt is set by process() and updateState() and not used before then
7947 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007948{
Steve Block3856b092011-10-20 11:56:00 +01007949 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007950 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007951 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007952 return;
7953 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007954
7955 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7956
7957 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007958 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007959
7960 if (mStatus != NO_ERROR) {
7961 return;
7962 }
7963 lStatus = init();
7964 if (lStatus < 0) {
7965 mStatus = lStatus;
7966 goto Error;
7967 }
7968
Steve Block3856b092011-10-20 11:56:00 +01007969 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007970 return;
7971Error:
7972 EffectRelease(mEffectInterface);
7973 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007974 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007975}
7976
7977AudioFlinger::EffectModule::~EffectModule()
7978{
Steve Block3856b092011-10-20 11:56:00 +01007979 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007980 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007981 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7982 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7983 sp<ThreadBase> thread = mThread.promote();
7984 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007985 audio_stream_t *stream = thread->stream();
7986 if (stream != NULL) {
7987 stream->remove_audio_effect(stream, mEffectInterface);
7988 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007989 }
7990 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007991 // release effect engine
7992 EffectRelease(mEffectInterface);
7993 }
7994}
7995
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007996status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007997{
7998 status_t status;
7999
8000 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008001 int priority = handle->priority();
8002 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008003 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008004 size_t i;
8005 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008006 EffectHandle *h = mHandles[i];
8007 if (h == NULL || h->destroyed_l()) continue;
8008 // first non destroyed handle is considered in control
8009 if (controlHandle == NULL)
8010 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008011 if (h->priority() <= priority) break;
8012 }
8013 // if inserted in first place, move effect control from previous owner to this handle
8014 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008015 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008016 if (controlHandle != NULL) {
8017 enabled = controlHandle->enabled();
8018 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008019 }
Eric Laurent59255e42011-07-27 19:49:51 -07008020 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008021 status = NO_ERROR;
8022 } else {
8023 status = ALREADY_EXISTS;
8024 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008025 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008026 mHandles.insertAt(handle, i);
8027 return status;
8028}
8029
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008030size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008031{
8032 Mutex::Autolock _l(mLock);
8033 size_t size = mHandles.size();
8034 size_t i;
8035 for (i = 0; i < size; i++) {
8036 if (mHandles[i] == handle) break;
8037 }
8038 if (i == size) {
8039 return size;
8040 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008041 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008042
Mathias Agopian65ab4712010-07-14 17:59:35 -07008043 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008044 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008045 if (i == 0) {
8046 EffectHandle *h = controlHandle_l();
8047 if (h != NULL) {
8048 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008049 }
8050 }
8051
Eric Laurentec437d82011-07-26 20:54:46 -07008052 // Prevent calls to process() and other functions on effect interface from now on.
8053 // The effect engine will be released by the destructor when the last strong reference on
8054 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008055 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008056 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008057 }
8058
Mathias Agopian65ab4712010-07-14 17:59:35 -07008059 return size;
8060}
8061
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008062// must be called with EffectModule::mLock held
8063AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008064{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008065 // the first valid handle in the list has control over the module
8066 for (size_t i = 0; i < mHandles.size(); i++) {
8067 EffectHandle *h = mHandles[i];
8068 if (h != NULL && !h->destroyed_l()) {
8069 return h;
8070 }
8071 }
8072
8073 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008074}
8075
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008076size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008077{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008078 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008079 // keep a strong reference on this EffectModule to avoid calling the
8080 // destructor before we exit
8081 sp<EffectModule> keep(this);
8082 {
8083 sp<ThreadBase> thread = mThread.promote();
8084 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008085 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008086 }
8087 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008088 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008089}
8090
8091void AudioFlinger::EffectModule::updateState() {
8092 Mutex::Autolock _l(mLock);
8093
8094 switch (mState) {
8095 case RESTART:
8096 reset_l();
8097 // FALL THROUGH
8098
8099 case STARTING:
8100 // clear auxiliary effect input buffer for next accumulation
8101 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8102 memset(mConfig.inputCfg.buffer.raw,
8103 0,
8104 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8105 }
8106 start_l();
8107 mState = ACTIVE;
8108 break;
8109 case STOPPING:
8110 stop_l();
8111 mDisableWaitCnt = mMaxDisableWaitCnt;
8112 mState = STOPPED;
8113 break;
8114 case STOPPED:
8115 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8116 // turn off sequence.
8117 if (--mDisableWaitCnt == 0) {
8118 reset_l();
8119 mState = IDLE;
8120 }
8121 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008122 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008123 break;
8124 }
8125}
8126
8127void AudioFlinger::EffectModule::process()
8128{
8129 Mutex::Autolock _l(mLock);
8130
Eric Laurentec437d82011-07-26 20:54:46 -07008131 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008132 mConfig.inputCfg.buffer.raw == NULL ||
8133 mConfig.outputCfg.buffer.raw == NULL) {
8134 return;
8135 }
8136
Eric Laurent8f45bd72010-08-31 13:50:07 -07008137 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008138 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8139 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008140 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008141 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008142 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008143 }
8144
8145 // do the actual processing in the effect engine
8146 int ret = (*mEffectInterface)->process(mEffectInterface,
8147 &mConfig.inputCfg.buffer,
8148 &mConfig.outputCfg.buffer);
8149
8150 // force transition to IDLE state when engine is ready
8151 if (mState == STOPPED && ret == -ENODATA) {
8152 mDisableWaitCnt = 1;
8153 }
8154
8155 // clear auxiliary effect input buffer for next accumulation
8156 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008157 memset(mConfig.inputCfg.buffer.raw, 0,
8158 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008159 }
8160 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008161 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8162 // If an insert effect is idle and input buffer is different from output buffer,
8163 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008164 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008165 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008166 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8167 int16_t *in = mConfig.inputCfg.buffer.s16;
8168 int16_t *out = mConfig.outputCfg.buffer.s16;
8169 for (size_t i = 0; i < frameCnt; i++) {
8170 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008171 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008172 }
8173 }
8174}
8175
8176void AudioFlinger::EffectModule::reset_l()
8177{
8178 if (mEffectInterface == NULL) {
8179 return;
8180 }
8181 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8182}
8183
8184status_t AudioFlinger::EffectModule::configure()
8185{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008186 if (mEffectInterface == NULL) {
8187 return NO_INIT;
8188 }
8189
8190 sp<ThreadBase> thread = mThread.promote();
8191 if (thread == 0) {
8192 return DEAD_OBJECT;
8193 }
8194
8195 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07008196 audio_channel_mask_t channelMask = thread->channelMask();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008197
8198 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008199 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008200 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07008201 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008202 }
Glenn Kasten254af182012-07-03 14:59:05 -07008203 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07008204 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8205 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008206 mConfig.inputCfg.samplingRate = thread->sampleRate();
8207 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8208 mConfig.inputCfg.bufferProvider.cookie = NULL;
8209 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8210 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8211 mConfig.outputCfg.bufferProvider.cookie = NULL;
8212 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8213 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8214 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8215 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008216 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008217 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008218 // - in other sessions:
8219 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8220 // other effect: overwrites output buffer: input buffer == output buffer
8221 // Auxiliary effect:
8222 // accumulates in output buffer: input buffer != output buffer
8223 // Therefore: accumulate <=> input buffer != output buffer
8224 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8225 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8226 } else {
8227 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8228 }
8229 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8230 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8231 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8232 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8233
Steve Block3856b092011-10-20 11:56:00 +01008234 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008235 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8236
Mathias Agopian65ab4712010-07-14 17:59:35 -07008237 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008238 uint32_t size = sizeof(int);
8239 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008240 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008241 sizeof(effect_config_t),
8242 &mConfig,
8243 &size,
8244 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008245 if (status == 0) {
8246 status = cmdStatus;
8247 }
8248
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008249 if (status == 0 &&
8250 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8251 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8252 effect_param_t *p = (effect_param_t *)buf32;
8253
8254 p->psize = sizeof(uint32_t);
8255 p->vsize = sizeof(uint32_t);
8256 size = sizeof(int);
8257 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8258
8259 uint32_t latency = 0;
8260 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8261 if (pbt != NULL) {
8262 latency = pbt->latency_l();
8263 }
8264
8265 *((int32_t *)p->data + 1)= latency;
8266 (*mEffectInterface)->command(mEffectInterface,
8267 EFFECT_CMD_SET_PARAM,
8268 sizeof(effect_param_t) + 8,
8269 &buf32,
8270 &size,
8271 &cmdStatus);
8272 }
8273
Mathias Agopian65ab4712010-07-14 17:59:35 -07008274 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8275 (1000 * mConfig.outputCfg.buffer.frameCount);
8276
8277 return status;
8278}
8279
8280status_t AudioFlinger::EffectModule::init()
8281{
8282 Mutex::Autolock _l(mLock);
8283 if (mEffectInterface == NULL) {
8284 return NO_INIT;
8285 }
8286 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008287 uint32_t size = sizeof(status_t);
8288 status_t status = (*mEffectInterface)->command(mEffectInterface,
8289 EFFECT_CMD_INIT,
8290 0,
8291 NULL,
8292 &size,
8293 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008294 if (status == 0) {
8295 status = cmdStatus;
8296 }
8297 return status;
8298}
8299
Eric Laurentec35a142011-10-05 17:42:25 -07008300status_t AudioFlinger::EffectModule::start()
8301{
8302 Mutex::Autolock _l(mLock);
8303 return start_l();
8304}
8305
Mathias Agopian65ab4712010-07-14 17:59:35 -07008306status_t AudioFlinger::EffectModule::start_l()
8307{
8308 if (mEffectInterface == NULL) {
8309 return NO_INIT;
8310 }
8311 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008312 uint32_t size = sizeof(status_t);
8313 status_t status = (*mEffectInterface)->command(mEffectInterface,
8314 EFFECT_CMD_ENABLE,
8315 0,
8316 NULL,
8317 &size,
8318 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008319 if (status == 0) {
8320 status = cmdStatus;
8321 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008322 if (status == 0 &&
8323 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8324 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8325 sp<ThreadBase> thread = mThread.promote();
8326 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008327 audio_stream_t *stream = thread->stream();
8328 if (stream != NULL) {
8329 stream->add_audio_effect(stream, mEffectInterface);
8330 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008331 }
8332 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008333 return status;
8334}
8335
Eric Laurentec437d82011-07-26 20:54:46 -07008336status_t AudioFlinger::EffectModule::stop()
8337{
8338 Mutex::Autolock _l(mLock);
8339 return stop_l();
8340}
8341
Mathias Agopian65ab4712010-07-14 17:59:35 -07008342status_t AudioFlinger::EffectModule::stop_l()
8343{
8344 if (mEffectInterface == NULL) {
8345 return NO_INIT;
8346 }
8347 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008348 uint32_t size = sizeof(status_t);
8349 status_t status = (*mEffectInterface)->command(mEffectInterface,
8350 EFFECT_CMD_DISABLE,
8351 0,
8352 NULL,
8353 &size,
8354 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008355 if (status == 0) {
8356 status = cmdStatus;
8357 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008358 if (status == 0 &&
8359 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8360 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8361 sp<ThreadBase> thread = mThread.promote();
8362 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008363 audio_stream_t *stream = thread->stream();
8364 if (stream != NULL) {
8365 stream->remove_audio_effect(stream, mEffectInterface);
8366 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008367 }
8368 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008369 return status;
8370}
8371
Eric Laurent25f43952010-07-28 05:40:18 -07008372status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8373 uint32_t cmdSize,
8374 void *pCmdData,
8375 uint32_t *replySize,
8376 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008377{
8378 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008379// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008380
Eric Laurentec437d82011-07-26 20:54:46 -07008381 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008382 return NO_INIT;
8383 }
Eric Laurent25f43952010-07-28 05:40:18 -07008384 status_t status = (*mEffectInterface)->command(mEffectInterface,
8385 cmdCode,
8386 cmdSize,
8387 pCmdData,
8388 replySize,
8389 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008390 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008391 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008392 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008393 EffectHandle *h = mHandles[i];
8394 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008395 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8396 }
8397 }
8398 }
8399 return status;
8400}
8401
8402status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8403{
8404 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008405 return setEnabled_l(enabled);
8406}
8407
8408// must be called with EffectModule::mLock held
8409status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8410{
8411
Steve Block3856b092011-10-20 11:56:00 +01008412 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008413
8414 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008415 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8416 if (enabled && status != NO_ERROR) {
8417 return status;
8418 }
8419
Mathias Agopian65ab4712010-07-14 17:59:35 -07008420 switch (mState) {
8421 // going from disabled to enabled
8422 case IDLE:
8423 mState = STARTING;
8424 break;
8425 case STOPPED:
8426 mState = RESTART;
8427 break;
8428 case STOPPING:
8429 mState = ACTIVE;
8430 break;
8431
8432 // going from enabled to disabled
8433 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008434 mState = STOPPED;
8435 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008436 case STARTING:
8437 mState = IDLE;
8438 break;
8439 case ACTIVE:
8440 mState = STOPPING;
8441 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008442 case DESTROYED:
8443 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008444 }
8445 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008446 EffectHandle *h = mHandles[i];
8447 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008448 h->setEnabled(enabled);
8449 }
8450 }
8451 }
8452 return NO_ERROR;
8453}
8454
Glenn Kastenc59c0042012-02-02 14:06:11 -08008455bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008456{
8457 switch (mState) {
8458 case RESTART:
8459 case STARTING:
8460 case ACTIVE:
8461 return true;
8462 case IDLE:
8463 case STOPPING:
8464 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008465 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008466 default:
8467 return false;
8468 }
8469}
8470
Glenn Kastenc59c0042012-02-02 14:06:11 -08008471bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008472{
8473 switch (mState) {
8474 case RESTART:
8475 case ACTIVE:
8476 case STOPPING:
8477 case STOPPED:
8478 return true;
8479 case IDLE:
8480 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008481 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008482 default:
8483 return false;
8484 }
8485}
8486
Mathias Agopian65ab4712010-07-14 17:59:35 -07008487status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8488{
8489 Mutex::Autolock _l(mLock);
8490 status_t status = NO_ERROR;
8491
8492 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8493 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008494 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008495 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8496 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008497 status_t cmdStatus;
8498 uint32_t volume[2];
8499 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008500 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008501 volume[0] = *left;
8502 volume[1] = *right;
8503 if (controller) {
8504 pVolume = volume;
8505 }
Eric Laurent25f43952010-07-28 05:40:18 -07008506 status = (*mEffectInterface)->command(mEffectInterface,
8507 EFFECT_CMD_SET_VOLUME,
8508 size,
8509 volume,
8510 &size,
8511 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008512 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8513 *left = volume[0];
8514 *right = volume[1];
8515 }
8516 }
8517 return status;
8518}
8519
8520status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8521{
8522 Mutex::Autolock _l(mLock);
8523 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008524 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8525 // audio pre processing modules on RecordThread can receive both output and
8526 // input device indication in the same call
8527 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8528 if (dev) {
8529 status_t cmdStatus;
8530 uint32_t size = sizeof(status_t);
8531
8532 status = (*mEffectInterface)->command(mEffectInterface,
8533 EFFECT_CMD_SET_DEVICE,
8534 sizeof(uint32_t),
8535 &dev,
8536 &size,
8537 &cmdStatus);
8538 if (status == NO_ERROR) {
8539 status = cmdStatus;
8540 }
8541 }
8542 dev = device & AUDIO_DEVICE_IN_ALL;
8543 if (dev) {
8544 status_t cmdStatus;
8545 uint32_t size = sizeof(status_t);
8546
8547 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8548 EFFECT_CMD_SET_INPUT_DEVICE,
8549 sizeof(uint32_t),
8550 &dev,
8551 &size,
8552 &cmdStatus);
8553 if (status2 == NO_ERROR) {
8554 status2 = cmdStatus;
8555 }
8556 if (status == NO_ERROR) {
8557 status = status2;
8558 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008559 }
8560 }
8561 return status;
8562}
8563
Glenn Kastenf78aee72012-01-04 11:00:47 -08008564status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008565{
8566 Mutex::Autolock _l(mLock);
8567 status_t status = NO_ERROR;
8568 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008569 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008570 uint32_t size = sizeof(status_t);
8571 status = (*mEffectInterface)->command(mEffectInterface,
8572 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008573 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008574 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008575 &size,
8576 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008577 if (status == NO_ERROR) {
8578 status = cmdStatus;
8579 }
8580 }
8581 return status;
8582}
8583
Eric Laurent59255e42011-07-27 19:49:51 -07008584void AudioFlinger::EffectModule::setSuspended(bool suspended)
8585{
8586 Mutex::Autolock _l(mLock);
8587 mSuspended = suspended;
8588}
Glenn Kastena3a85482012-01-04 11:01:11 -08008589
8590bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008591{
8592 Mutex::Autolock _l(mLock);
8593 return mSuspended;
8594}
8595
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008596bool AudioFlinger::EffectModule::purgeHandles()
8597{
8598 bool enabled = false;
8599 Mutex::Autolock _l(mLock);
8600 for (size_t i = 0; i < mHandles.size(); i++) {
8601 EffectHandle *handle = mHandles[i];
8602 if (handle != NULL && !handle->destroyed_l()) {
8603 handle->effect().clear();
8604 if (handle->hasControl()) {
8605 enabled = handle->enabled();
8606 }
8607 }
8608 }
8609 return enabled;
8610}
8611
Mathias Agopian65ab4712010-07-14 17:59:35 -07008612status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8613{
8614 const size_t SIZE = 256;
8615 char buffer[SIZE];
8616 String8 result;
8617
8618 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8619 result.append(buffer);
8620
8621 bool locked = tryLock(mLock);
8622 // failed to lock - AudioFlinger is probably deadlocked
8623 if (!locked) {
8624 result.append("\t\tCould not lock Fx mutex:\n");
8625 }
8626
8627 result.append("\t\tSession Status State Engine:\n");
8628 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8629 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8630 result.append(buffer);
8631
8632 result.append("\t\tDescriptor:\n");
8633 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8634 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8635 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8636 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8637 result.append(buffer);
8638 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8639 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8640 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8641 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8642 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008643 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008644 mDescriptor.apiVersion,
8645 mDescriptor.flags);
8646 result.append(buffer);
8647 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8648 mDescriptor.name);
8649 result.append(buffer);
8650 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8651 mDescriptor.implementor);
8652 result.append(buffer);
8653
8654 result.append("\t\t- Input configuration:\n");
8655 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8656 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8657 (uint32_t)mConfig.inputCfg.buffer.raw,
8658 mConfig.inputCfg.buffer.frameCount,
8659 mConfig.inputCfg.samplingRate,
8660 mConfig.inputCfg.channels,
8661 mConfig.inputCfg.format);
8662 result.append(buffer);
8663
8664 result.append("\t\t- Output 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.outputCfg.buffer.raw,
8668 mConfig.outputCfg.buffer.frameCount,
8669 mConfig.outputCfg.samplingRate,
8670 mConfig.outputCfg.channels,
8671 mConfig.outputCfg.format);
8672 result.append(buffer);
8673
8674 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8675 result.append(buffer);
8676 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8677 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008678 EffectHandle *handle = mHandles[i];
8679 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008680 handle->dump(buffer, SIZE);
8681 result.append(buffer);
8682 }
8683 }
8684
8685 result.append("\n");
8686
8687 write(fd, result.string(), result.length());
8688
8689 if (locked) {
8690 mLock.unlock();
8691 }
8692
8693 return NO_ERROR;
8694}
8695
8696// ----------------------------------------------------------------------------
8697// EffectHandle implementation
8698// ----------------------------------------------------------------------------
8699
8700#undef LOG_TAG
8701#define LOG_TAG "AudioFlinger::EffectHandle"
8702
8703AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8704 const sp<AudioFlinger::Client>& client,
8705 const sp<IEffectClient>& effectClient,
8706 int32_t priority)
8707 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008708 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008709 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008710{
Steve Block3856b092011-10-20 11:56:00 +01008711 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008712
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008713 if (client == 0) {
8714 return;
8715 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008716 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8717 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8718 if (mCblkMemory != 0) {
8719 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8720
Glenn Kastena0d68332012-01-27 16:47:15 -08008721 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008722 new(mCblk) effect_param_cblk_t();
8723 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008724 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008725 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008726 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008727 return;
8728 }
8729}
8730
8731AudioFlinger::EffectHandle::~EffectHandle()
8732{
Steve Block3856b092011-10-20 11:56:00 +01008733 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008734
8735 if (mEffect == 0) {
8736 mDestroyed = true;
8737 return;
8738 }
8739 mEffect->lock();
8740 mDestroyed = true;
8741 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008742 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008743}
8744
8745status_t AudioFlinger::EffectHandle::enable()
8746{
Steve Block3856b092011-10-20 11:56:00 +01008747 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008748 if (!mHasControl) return INVALID_OPERATION;
8749 if (mEffect == 0) return DEAD_OBJECT;
8750
Eric Laurentdb7c0792011-08-10 10:37:50 -07008751 if (mEnabled) {
8752 return NO_ERROR;
8753 }
8754
Eric Laurent59255e42011-07-27 19:49:51 -07008755 mEnabled = true;
8756
8757 sp<ThreadBase> thread = mEffect->thread().promote();
8758 if (thread != 0) {
8759 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8760 }
8761
8762 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8763 if (mEffect->suspended()) {
8764 return NO_ERROR;
8765 }
8766
Eric Laurentdb7c0792011-08-10 10:37:50 -07008767 status_t status = mEffect->setEnabled(true);
8768 if (status != NO_ERROR) {
8769 if (thread != 0) {
8770 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8771 }
8772 mEnabled = false;
8773 }
8774 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008775}
8776
8777status_t AudioFlinger::EffectHandle::disable()
8778{
Steve Block3856b092011-10-20 11:56:00 +01008779 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008780 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008781 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008782
Eric Laurentdb7c0792011-08-10 10:37:50 -07008783 if (!mEnabled) {
8784 return NO_ERROR;
8785 }
Eric Laurent59255e42011-07-27 19:49:51 -07008786 mEnabled = false;
8787
8788 if (mEffect->suspended()) {
8789 return NO_ERROR;
8790 }
8791
8792 status_t status = mEffect->setEnabled(false);
8793
8794 sp<ThreadBase> thread = mEffect->thread().promote();
8795 if (thread != 0) {
8796 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8797 }
8798
8799 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008800}
8801
8802void AudioFlinger::EffectHandle::disconnect()
8803{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008804 disconnect(true);
8805}
8806
Glenn Kasten58123c32012-02-03 10:32:24 -08008807void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008808{
Glenn Kasten58123c32012-02-03 10:32:24 -08008809 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008810 if (mEffect == 0) {
8811 return;
8812 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008813 // restore suspended effects if the disconnected handle was enabled and the last one.
8814 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008815 sp<ThreadBase> thread = mEffect->thread().promote();
8816 if (thread != 0) {
8817 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8818 }
Eric Laurent59255e42011-07-27 19:49:51 -07008819 }
8820
Mathias Agopian65ab4712010-07-14 17:59:35 -07008821 // release sp on module => module destructor can be called now
8822 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008823 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008824 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008825 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008826 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8827 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008828 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008829 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008830 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8831 mClient.clear();
8832 }
8833}
8834
Eric Laurent25f43952010-07-28 05:40:18 -07008835status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8836 uint32_t cmdSize,
8837 void *pCmdData,
8838 uint32_t *replySize,
8839 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008840{
Steve Block3856b092011-10-20 11:56:00 +01008841// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008842// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008843
8844 // only get parameter command is permitted for applications not controlling the effect
8845 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8846 return INVALID_OPERATION;
8847 }
8848 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008849 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008850
8851 // handle commands that are not forwarded transparently to effect engine
8852 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8853 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8854 // no risk to block the whole media server process or mixer threads is we are stuck here
8855 Mutex::Autolock _l(mCblk->lock);
8856 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8857 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8858 mCblk->serverIndex = 0;
8859 mCblk->clientIndex = 0;
8860 return BAD_VALUE;
8861 }
8862 status_t status = NO_ERROR;
8863 while (mCblk->serverIndex < mCblk->clientIndex) {
8864 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008865 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008866 int *p = (int *)(mBuffer + mCblk->serverIndex);
8867 int size = *p++;
8868 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008869 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008870 break;
8871 }
8872 effect_param_t *param = (effect_param_t *)p;
8873 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008874 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008875 mCblk->serverIndex += size;
8876 continue;
8877 }
Eric Laurent25f43952010-07-28 05:40:18 -07008878 uint32_t psize = sizeof(effect_param_t) +
8879 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8880 param->vsize;
8881 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8882 psize,
8883 p,
8884 &rsize,
8885 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008886 // stop at first error encountered
8887 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008888 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008889 *(int *)pReplyData = reply;
8890 break;
8891 } else if (reply != NO_ERROR) {
8892 *(int *)pReplyData = reply;
8893 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008894 }
8895 mCblk->serverIndex += size;
8896 }
8897 mCblk->serverIndex = 0;
8898 mCblk->clientIndex = 0;
8899 return status;
8900 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008901 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008902 return enable();
8903 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008904 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008905 return disable();
8906 }
8907
8908 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8909}
8910
Eric Laurent59255e42011-07-27 19:49:51 -07008911void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008912{
Steve Block3856b092011-10-20 11:56:00 +01008913 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008914
8915 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008916 mEnabled = enabled;
8917
Mathias Agopian65ab4712010-07-14 17:59:35 -07008918 if (signal && mEffectClient != 0) {
8919 mEffectClient->controlStatusChanged(hasControl);
8920 }
8921}
8922
Eric Laurent25f43952010-07-28 05:40:18 -07008923void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8924 uint32_t cmdSize,
8925 void *pCmdData,
8926 uint32_t replySize,
8927 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008928{
8929 if (mEffectClient != 0) {
8930 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8931 }
8932}
8933
8934
8935
8936void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8937{
8938 if (mEffectClient != 0) {
8939 mEffectClient->enableStatusChanged(enabled);
8940 }
8941}
8942
8943status_t AudioFlinger::EffectHandle::onTransact(
8944 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8945{
8946 return BnEffect::onTransact(code, data, reply, flags);
8947}
8948
8949
8950void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8951{
Glenn Kastena0d68332012-01-27 16:47:15 -08008952 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008953
8954 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008955 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008956 mPriority,
8957 mHasControl,
8958 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008959 mCblk ? mCblk->clientIndex : 0,
8960 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008961 );
8962
8963 if (locked) {
8964 mCblk->lock.unlock();
8965 }
8966}
8967
8968#undef LOG_TAG
8969#define LOG_TAG "AudioFlinger::EffectChain"
8970
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008971AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008972 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008973 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008974 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8975 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008976{
Dima Zavinfce7a472011-04-19 22:30:36 -07008977 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008978 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008979 return;
8980 }
8981 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8982 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008983}
8984
8985AudioFlinger::EffectChain::~EffectChain()
8986{
8987 if (mOwnInBuffer) {
8988 delete mInBuffer;
8989 }
8990
8991}
8992
Eric Laurent59255e42011-07-27 19:49:51 -07008993// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008994sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008995{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008996 size_t size = mEffects.size();
8997
8998 for (size_t i = 0; i < size; i++) {
8999 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009000 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009001 }
9002 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009003 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009004}
9005
Eric Laurent59255e42011-07-27 19:49:51 -07009006// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009007sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009008{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009009 size_t size = mEffects.size();
9010
9011 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009012 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9013 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009014 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009015 }
9016 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009017 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009018}
9019
Eric Laurent59255e42011-07-27 19:49:51 -07009020// getEffectFromType_l() must be called with ThreadBase::mLock held
9021sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9022 const effect_uuid_t *type)
9023{
Eric Laurent59255e42011-07-27 19:49:51 -07009024 size_t size = mEffects.size();
9025
9026 for (size_t i = 0; i < size; i++) {
9027 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009028 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009029 }
9030 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009031 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009032}
9033
Eric Laurent91b14c42012-05-30 12:30:29 -07009034void AudioFlinger::EffectChain::clearInputBuffer()
9035{
9036 Mutex::Autolock _l(mLock);
9037 sp<ThreadBase> thread = mThread.promote();
9038 if (thread == 0) {
9039 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9040 return;
9041 }
9042 clearInputBuffer_l(thread);
9043}
9044
9045// Must be called with EffectChain::mLock locked
9046void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9047{
9048 size_t numSamples = thread->frameCount() * thread->channelCount();
9049 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9050
9051}
9052
Mathias Agopian65ab4712010-07-14 17:59:35 -07009053// Must be called with EffectChain::mLock locked
9054void AudioFlinger::EffectChain::process_l()
9055{
Eric Laurentdac69112010-09-28 14:09:57 -07009056 sp<ThreadBase> thread = mThread.promote();
9057 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009058 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009059 return;
9060 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009061 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9062 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009063 // always process effects unless no more tracks are on the session and the effect tail
9064 // has been rendered
9065 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009066 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009067 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009068
Eric Laurent544fe9b2011-11-11 15:42:52 -08009069 if (!tracksOnSession && mTailBufferCount == 0) {
9070 doProcess = false;
9071 }
9072
9073 if (activeTrackCnt() == 0) {
9074 // if no track is active and the effect tail has not been rendered,
9075 // the input buffer must be cleared here as the mixer process will not do it
9076 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009077 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009078 if (mTailBufferCount > 0) {
9079 mTailBufferCount--;
9080 }
9081 }
9082 }
Eric Laurentdac69112010-09-28 14:09:57 -07009083 }
9084
Mathias Agopian65ab4712010-07-14 17:59:35 -07009085 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009086 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009087 for (size_t i = 0; i < size; i++) {
9088 mEffects[i]->process();
9089 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009090 }
9091 for (size_t i = 0; i < size; i++) {
9092 mEffects[i]->updateState();
9093 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009094}
9095
Eric Laurentcab11242010-07-15 12:50:15 -07009096// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009097status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009098{
9099 effect_descriptor_t desc = effect->desc();
9100 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9101
9102 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009103 effect->setChain(this);
9104 sp<ThreadBase> thread = mThread.promote();
9105 if (thread == 0) {
9106 return NO_INIT;
9107 }
9108 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009109
9110 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9111 // Auxiliary effects are inserted at the beginning of mEffects vector as
9112 // they are processed first and accumulated in chain input buffer
9113 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009114
Mathias Agopian65ab4712010-07-14 17:59:35 -07009115 // the input buffer for auxiliary effect contains mono samples in
9116 // 32 bit format. This is to avoid saturation in AudoMixer
9117 // accumulation stage. Saturation is done in EffectModule::process() before
9118 // calling the process in effect engine
9119 size_t numSamples = thread->frameCount();
9120 int32_t *buffer = new int32_t[numSamples];
9121 memset(buffer, 0, numSamples * sizeof(int32_t));
9122 effect->setInBuffer((int16_t *)buffer);
9123 // auxiliary effects output samples to chain input buffer for further processing
9124 // by insert effects
9125 effect->setOutBuffer(mInBuffer);
9126 } else {
9127 // Insert effects are inserted at the end of mEffects vector as they are processed
9128 // after track and auxiliary effects.
9129 // Insert effect order as a function of indicated preference:
9130 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9131 // another effect is present
9132 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9133 // last effect claiming first position
9134 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9135 // first effect claiming last position
9136 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9137 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9138 // already present
9139
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009140 size_t size = mEffects.size();
9141 size_t idx_insert = size;
9142 ssize_t idx_insert_first = -1;
9143 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009144
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009145 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009146 effect_descriptor_t d = mEffects[i]->desc();
9147 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9148 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9149 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9150 // check invalid effect chaining combinations
9151 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9152 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009153 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009154 return INVALID_OPERATION;
9155 }
9156 // remember position of first insert effect and by default
9157 // select this as insert position for new effect
9158 if (idx_insert == size) {
9159 idx_insert = i;
9160 }
9161 // remember position of last insert effect claiming
9162 // first position
9163 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9164 idx_insert_first = i;
9165 }
9166 // remember position of first insert effect claiming
9167 // last position
9168 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9169 idx_insert_last == -1) {
9170 idx_insert_last = i;
9171 }
9172 }
9173 }
9174
9175 // modify idx_insert from first position if needed
9176 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9177 if (idx_insert_last != -1) {
9178 idx_insert = idx_insert_last;
9179 } else {
9180 idx_insert = size;
9181 }
9182 } else {
9183 if (idx_insert_first != -1) {
9184 idx_insert = idx_insert_first + 1;
9185 }
9186 }
9187
9188 // always read samples from chain input buffer
9189 effect->setInBuffer(mInBuffer);
9190
9191 // if last effect in the chain, output samples to chain
9192 // output buffer, otherwise to chain input buffer
9193 if (idx_insert == size) {
9194 if (idx_insert != 0) {
9195 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9196 mEffects[idx_insert-1]->configure();
9197 }
9198 effect->setOutBuffer(mOutBuffer);
9199 } else {
9200 effect->setOutBuffer(mInBuffer);
9201 }
9202 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009203
Steve Block3856b092011-10-20 11:56:00 +01009204 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009205 }
9206 effect->configure();
9207 return NO_ERROR;
9208}
9209
Eric Laurentcab11242010-07-15 12:50:15 -07009210// removeEffect_l() must be called with PlaybackThread::mLock held
9211size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009212{
9213 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009214 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009215 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9216
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009217 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009218 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009219 // calling stop here will remove pre-processing effect from the audio HAL.
9220 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9221 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009222 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9223 mEffects[i]->state() == EffectModule::STOPPING) {
9224 mEffects[i]->stop();
9225 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009226 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9227 delete[] effect->inBuffer();
9228 } else {
9229 if (i == size - 1 && i != 0) {
9230 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9231 mEffects[i - 1]->configure();
9232 }
9233 }
9234 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009235 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009236 break;
9237 }
9238 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009239
9240 return mEffects.size();
9241}
9242
Eric Laurentcab11242010-07-15 12:50:15 -07009243// setDevice_l() must be called with PlaybackThread::mLock held
9244void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009245{
9246 size_t size = mEffects.size();
9247 for (size_t i = 0; i < size; i++) {
9248 mEffects[i]->setDevice(device);
9249 }
9250}
9251
Eric Laurentcab11242010-07-15 12:50:15 -07009252// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009253void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009254{
9255 size_t size = mEffects.size();
9256 for (size_t i = 0; i < size; i++) {
9257 mEffects[i]->setMode(mode);
9258 }
9259}
9260
Eric Laurentcab11242010-07-15 12:50:15 -07009261// setVolume_l() must be called with PlaybackThread::mLock held
9262bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009263{
9264 uint32_t newLeft = *left;
9265 uint32_t newRight = *right;
9266 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009267 int ctrlIdx = -1;
9268 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009269
Eric Laurentcab11242010-07-15 12:50:15 -07009270 // first update volume controller
9271 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009272 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009273 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9274 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009275 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009276 break;
9277 }
9278 }
9279
9280 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009281 if (hasControl) {
9282 *left = mNewLeftVolume;
9283 *right = mNewRightVolume;
9284 }
9285 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009286 }
9287
9288 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009289 mLeftVolume = newLeft;
9290 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009291
9292 // second get volume update from volume controller
9293 if (ctrlIdx >= 0) {
9294 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009295 mNewLeftVolume = newLeft;
9296 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009297 }
9298 // then indicate volume to all other effects in chain.
9299 // Pass altered volume to effects before volume controller
9300 // and requested volume to effects after controller
9301 uint32_t lVol = newLeft;
9302 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009303
Mathias Agopian65ab4712010-07-14 17:59:35 -07009304 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009305 if ((int)i == ctrlIdx) continue;
9306 // this also works for ctrlIdx == -1 when there is no volume controller
9307 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009308 lVol = *left;
9309 rVol = *right;
9310 }
9311 mEffects[i]->setVolume(&lVol, &rVol, false);
9312 }
9313 *left = newLeft;
9314 *right = newRight;
9315
9316 return hasControl;
9317}
9318
Mathias Agopian65ab4712010-07-14 17:59:35 -07009319status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9320{
9321 const size_t SIZE = 256;
9322 char buffer[SIZE];
9323 String8 result;
9324
9325 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9326 result.append(buffer);
9327
9328 bool locked = tryLock(mLock);
9329 // failed to lock - AudioFlinger is probably deadlocked
9330 if (!locked) {
9331 result.append("\tCould not lock mutex:\n");
9332 }
9333
Eric Laurentcab11242010-07-15 12:50:15 -07009334 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9335 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009336 mEffects.size(),
9337 (uint32_t)mInBuffer,
9338 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009339 mActiveTrackCnt);
9340 result.append(buffer);
9341 write(fd, result.string(), result.size());
9342
9343 for (size_t i = 0; i < mEffects.size(); ++i) {
9344 sp<EffectModule> effect = mEffects[i];
9345 if (effect != 0) {
9346 effect->dump(fd, args);
9347 }
9348 }
9349
9350 if (locked) {
9351 mLock.unlock();
9352 }
9353
9354 return NO_ERROR;
9355}
9356
Eric Laurent59255e42011-07-27 19:49:51 -07009357// must be called with ThreadBase::mLock held
9358void AudioFlinger::EffectChain::setEffectSuspended_l(
9359 const effect_uuid_t *type, bool suspend)
9360{
9361 sp<SuspendedEffectDesc> desc;
9362 // use effect type UUID timelow as key as there is no real risk of identical
9363 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009364 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009365 if (suspend) {
9366 if (index >= 0) {
9367 desc = mSuspendedEffects.valueAt(index);
9368 } else {
9369 desc = new SuspendedEffectDesc();
9370 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9371 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009372 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009373 }
9374 if (desc->mRefCount++ == 0) {
9375 sp<EffectModule> effect = getEffectIfEnabled(type);
9376 if (effect != 0) {
9377 desc->mEffect = effect;
9378 effect->setSuspended(true);
9379 effect->setEnabled(false);
9380 }
9381 }
9382 } else {
9383 if (index < 0) {
9384 return;
9385 }
9386 desc = mSuspendedEffects.valueAt(index);
9387 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009388 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009389 desc->mRefCount = 1;
9390 }
9391 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009392 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009393 if (desc->mEffect != 0) {
9394 sp<EffectModule> effect = desc->mEffect.promote();
9395 if (effect != 0) {
9396 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009397 effect->lock();
9398 EffectHandle *handle = effect->controlHandle_l();
9399 if (handle != NULL && !handle->destroyed_l()) {
9400 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009401 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009402 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009403 }
9404 desc->mEffect.clear();
9405 }
9406 mSuspendedEffects.removeItemsAt(index);
9407 }
9408 }
9409}
9410
9411// must be called with ThreadBase::mLock held
9412void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9413{
9414 sp<SuspendedEffectDesc> desc;
9415
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009416 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009417 if (suspend) {
9418 if (index >= 0) {
9419 desc = mSuspendedEffects.valueAt(index);
9420 } else {
9421 desc = new SuspendedEffectDesc();
9422 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009423 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009424 }
9425 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009426 Vector< sp<EffectModule> > effects;
9427 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009428 for (size_t i = 0; i < effects.size(); i++) {
9429 setEffectSuspended_l(&effects[i]->desc().type, true);
9430 }
9431 }
9432 } else {
9433 if (index < 0) {
9434 return;
9435 }
9436 desc = mSuspendedEffects.valueAt(index);
9437 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009438 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009439 desc->mRefCount = 1;
9440 }
9441 if (--desc->mRefCount == 0) {
9442 Vector<const effect_uuid_t *> types;
9443 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9444 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9445 continue;
9446 }
9447 types.add(&mSuspendedEffects.valueAt(i)->mType);
9448 }
9449 for (size_t i = 0; i < types.size(); i++) {
9450 setEffectSuspended_l(types[i], false);
9451 }
Steve Block3856b092011-10-20 11:56:00 +01009452 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009453 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9454 }
9455 }
9456}
9457
Eric Laurent6bffdb82011-09-23 08:40:41 -07009458
9459// The volume effect is used for automated tests only
9460#ifndef OPENSL_ES_H_
9461static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9462 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9463const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9464#endif //OPENSL_ES_H_
9465
Eric Laurentdb7c0792011-08-10 10:37:50 -07009466bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9467{
9468 // auxiliary effects and visualizer are never suspended on output mix
9469 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9470 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009471 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9472 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009473 return false;
9474 }
9475 return true;
9476}
9477
Glenn Kastend0539712012-01-30 12:56:03 -08009478void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009479{
Glenn Kastend0539712012-01-30 12:56:03 -08009480 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009481 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009482 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9483 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009484 }
Eric Laurent59255e42011-07-27 19:49:51 -07009485 }
Eric Laurent59255e42011-07-27 19:49:51 -07009486}
9487
9488sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9489 const effect_uuid_t *type)
9490{
Glenn Kasten090f0192012-01-30 13:00:02 -08009491 sp<EffectModule> effect = getEffectFromType_l(type);
9492 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009493}
9494
9495void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9496 bool enabled)
9497{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009498 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009499 if (enabled) {
9500 if (index < 0) {
9501 // if the effect is not suspend check if all effects are suspended
9502 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9503 if (index < 0) {
9504 return;
9505 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009506 if (!isEffectEligibleForSuspend(effect->desc())) {
9507 return;
9508 }
Eric Laurent59255e42011-07-27 19:49:51 -07009509 setEffectSuspended_l(&effect->desc().type, enabled);
9510 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009511 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009512 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009513 return;
9514 }
Eric Laurent59255e42011-07-27 19:49:51 -07009515 }
Steve Block3856b092011-10-20 11:56:00 +01009516 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009517 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009518 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9519 // if effect is requested to suspended but was not yet enabled, supend it now.
9520 if (desc->mEffect == 0) {
9521 desc->mEffect = effect;
9522 effect->setEnabled(false);
9523 effect->setSuspended(true);
9524 }
9525 } else {
9526 if (index < 0) {
9527 return;
9528 }
Steve Block3856b092011-10-20 11:56:00 +01009529 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009530 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009531 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9532 desc->mEffect.clear();
9533 effect->setSuspended(false);
9534 }
9535}
9536
Mathias Agopian65ab4712010-07-14 17:59:35 -07009537#undef LOG_TAG
9538#define LOG_TAG "AudioFlinger"
9539
9540// ----------------------------------------------------------------------------
9541
9542status_t AudioFlinger::onTransact(
9543 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9544{
9545 return BnAudioFlinger::onTransact(code, data, reply, flags);
9546}
9547
Mathias Agopian65ab4712010-07-14 17:59:35 -07009548}; // namespace android