blob: fe848933e703cf87d84b6606bde4c5431c53a847 [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,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700435 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700436 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800437 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700438 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800439 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800440 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700441 int *sessionId,
442 status_t *status)
443{
444 sp<PlaybackThread::Track> track;
445 sp<TrackHandle> trackHandle;
446 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700447 status_t lStatus;
448 int lSessionId;
449
Glenn Kasten263709e2012-01-06 08:40:01 -0800450 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
451 // but if someone uses binder directly they could bypass that and cause us to crash
452 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000453 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700454 lStatus = BAD_VALUE;
455 goto Exit;
456 }
457
458 {
459 Mutex::Autolock _l(mLock);
460 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700461 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700462 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000463 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700464 lStatus = BAD_VALUE;
465 goto Exit;
466 }
467
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800468 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700469
Steve Block3856b092011-10-20 11:56:00 +0100470 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700471 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700472 // check if an effect chain with the same session ID is present on another
473 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700474 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700475 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
476 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700477 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700478 if (sessions & PlaybackThread::EFFECT_SESSION) {
479 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700480 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700481 }
Eric Laurentde070132010-07-13 04:45:46 -0700482 }
483 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700484 lSessionId = *sessionId;
485 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700486 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700487 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700488 if (sessionId != NULL) {
489 *sessionId = lSessionId;
490 }
491 }
Steve Block3856b092011-10-20 11:56:00 +0100492 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700493
494 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800495 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700496
497 // move effect chain to this output thread if an effect on same session was waiting
498 // for a track to be created
499 if (lStatus == NO_ERROR && effectThread != NULL) {
500 Mutex::Autolock _dl(thread->mLock);
501 Mutex::Autolock _sl(effectThread->mLock);
502 moveEffectChain_l(lSessionId, effectThread, thread, true);
503 }
Eric Laurenta011e352012-03-29 15:51:43 -0700504
505 // Look for sync events awaiting for a session to be used.
506 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
507 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
508 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700509 if (lStatus == NO_ERROR) {
510 track->setSyncEvent(mPendingSyncEvents[i]);
511 } else {
512 mPendingSyncEvents[i]->cancel();
513 }
Eric Laurenta011e352012-03-29 15:51:43 -0700514 mPendingSyncEvents.removeAt(i);
515 i--;
516 }
517 }
518 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700519 }
520 if (lStatus == NO_ERROR) {
521 trackHandle = new TrackHandle(track);
522 } else {
523 // remove local strong reference to Client before deleting the Track so that the Client
524 // destructor is called by the TrackBase destructor with mLock held
525 client.clear();
526 track.clear();
527 }
528
529Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700530 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700531 *status = lStatus;
532 }
533 return trackHandle;
534}
535
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800536uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700537{
538 Mutex::Autolock _l(mLock);
539 PlaybackThread *thread = checkPlaybackThread_l(output);
540 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000541 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700542 return 0;
543 }
544 return thread->sampleRate();
545}
546
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800547int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700548{
549 Mutex::Autolock _l(mLock);
550 PlaybackThread *thread = checkPlaybackThread_l(output);
551 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000552 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700553 return 0;
554 }
555 return thread->channelCount();
556}
557
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800558audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700559{
560 Mutex::Autolock _l(mLock);
561 PlaybackThread *thread = checkPlaybackThread_l(output);
562 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000563 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800564 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700565 }
566 return thread->format();
567}
568
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800569size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700570{
571 Mutex::Autolock _l(mLock);
572 PlaybackThread *thread = checkPlaybackThread_l(output);
573 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000574 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700575 return 0;
576 }
Glenn Kasten58912562012-04-03 10:45:00 -0700577 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
578 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700579 return thread->frameCount();
580}
581
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800582uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700583{
584 Mutex::Autolock _l(mLock);
585 PlaybackThread *thread = checkPlaybackThread_l(output);
586 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000587 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700588 return 0;
589 }
590 return thread->latency();
591}
592
593status_t AudioFlinger::setMasterVolume(float value)
594{
Eric Laurenta1884f92011-08-23 08:25:03 -0700595 status_t ret = initCheck();
596 if (ret != NO_ERROR) {
597 return ret;
598 }
599
Mathias Agopian65ab4712010-07-14 17:59:35 -0700600 // check calling permissions
601 if (!settingsAllowed()) {
602 return PERMISSION_DENIED;
603 }
604
John Grossman4ff14ba2012-02-08 16:37:41 -0800605 float swmv = value;
606
Eric Laurenta4c5a552012-03-29 10:12:40 -0700607 Mutex::Autolock _l(mLock);
608
Mathias Agopian65ab4712010-07-14 17:59:35 -0700609 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800610 if (MVS_NONE != mMasterVolumeSupportLvl) {
611 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
612 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700613 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
John Grossman4ff14ba2012-02-08 16:37:41 -0800614
615 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
616 if (NULL != dev->set_master_volume) {
617 dev->set_master_volume(dev, value);
618 }
619 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800620 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800621
622 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700623 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700624
John Grossman4ff14ba2012-02-08 16:37:41 -0800625 mMasterVolume = value;
626 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800627 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700628 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700629
630 return NO_ERROR;
631}
632
Glenn Kastenf78aee72012-01-04 11:00:47 -0800633status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700634{
Eric Laurenta1884f92011-08-23 08:25:03 -0700635 status_t ret = initCheck();
636 if (ret != NO_ERROR) {
637 return ret;
638 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700639
640 // check calling permissions
641 if (!settingsAllowed()) {
642 return PERMISSION_DENIED;
643 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800644 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000645 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700646 return BAD_VALUE;
647 }
648
649 { // scope for the lock
650 AutoMutex lock(mHardwareLock);
651 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700652 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700653 mHardwareStatus = AUDIO_HW_IDLE;
654 }
655
656 if (NO_ERROR == ret) {
657 Mutex::Autolock _l(mLock);
658 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800659 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700660 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700661 }
662
663 return ret;
664}
665
666status_t AudioFlinger::setMicMute(bool state)
667{
Eric Laurenta1884f92011-08-23 08:25:03 -0700668 status_t ret = initCheck();
669 if (ret != NO_ERROR) {
670 return ret;
671 }
672
Mathias Agopian65ab4712010-07-14 17:59:35 -0700673 // check calling permissions
674 if (!settingsAllowed()) {
675 return PERMISSION_DENIED;
676 }
677
678 AutoMutex lock(mHardwareLock);
679 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700680 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700681 mHardwareStatus = AUDIO_HW_IDLE;
682 return ret;
683}
684
685bool AudioFlinger::getMicMute() const
686{
Eric Laurenta1884f92011-08-23 08:25:03 -0700687 status_t ret = initCheck();
688 if (ret != NO_ERROR) {
689 return false;
690 }
691
Dima Zavinfce7a472011-04-19 22:30:36 -0700692 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800693 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700694 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700695 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700696 mHardwareStatus = AUDIO_HW_IDLE;
697 return state;
698}
699
700status_t AudioFlinger::setMasterMute(bool muted)
701{
702 // check calling permissions
703 if (!settingsAllowed()) {
704 return PERMISSION_DENIED;
705 }
706
Eric Laurent93575202011-01-18 18:39:02 -0800707 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800708 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700709 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800710 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700711 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700712
713 return NO_ERROR;
714}
715
716float AudioFlinger::masterVolume() const
717{
Glenn Kasten98067102011-12-13 11:47:54 -0800718 Mutex::Autolock _l(mLock);
719 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700720}
721
John Grossman4ff14ba2012-02-08 16:37:41 -0800722float AudioFlinger::masterVolumeSW() const
723{
724 Mutex::Autolock _l(mLock);
725 return masterVolumeSW_l();
726}
727
Mathias Agopian65ab4712010-07-14 17:59:35 -0700728bool AudioFlinger::masterMute() const
729{
Glenn Kasten98067102011-12-13 11:47:54 -0800730 Mutex::Autolock _l(mLock);
731 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700732}
733
John Grossman4ff14ba2012-02-08 16:37:41 -0800734float AudioFlinger::masterVolume_l() const
735{
736 if (MVS_FULL == mMasterVolumeSupportLvl) {
737 float ret_val;
738 AutoMutex lock(mHardwareLock);
739
740 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800741 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
742 (NULL != mPrimaryHardwareDev->get_master_volume),
743 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800744
745 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
746 mHardwareStatus = AUDIO_HW_IDLE;
747 return ret_val;
748 }
749
750 return mMasterVolume;
751}
752
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800753status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
754 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700755{
756 // check calling permissions
757 if (!settingsAllowed()) {
758 return PERMISSION_DENIED;
759 }
760
Glenn Kasten263709e2012-01-06 08:40:01 -0800761 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000762 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700763 return BAD_VALUE;
764 }
765
766 AutoMutex lock(mLock);
767 PlaybackThread *thread = NULL;
768 if (output) {
769 thread = checkPlaybackThread_l(output);
770 if (thread == NULL) {
771 return BAD_VALUE;
772 }
773 }
774
775 mStreamTypes[stream].volume = value;
776
777 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800778 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700779 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700780 }
781 } else {
782 thread->setStreamVolume(stream, value);
783 }
784
785 return NO_ERROR;
786}
787
Glenn Kastenfff6d712012-01-12 16:38:12 -0800788status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700789{
790 // check calling permissions
791 if (!settingsAllowed()) {
792 return PERMISSION_DENIED;
793 }
794
Glenn Kasten263709e2012-01-06 08:40:01 -0800795 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700796 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000797 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700798 return BAD_VALUE;
799 }
800
Eric Laurent93575202011-01-18 18:39:02 -0800801 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700802 mStreamTypes[stream].mute = muted;
803 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700804 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805
806 return NO_ERROR;
807}
808
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800809float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700810{
Glenn Kasten263709e2012-01-06 08:40:01 -0800811 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700812 return 0.0f;
813 }
814
815 AutoMutex lock(mLock);
816 float volume;
817 if (output) {
818 PlaybackThread *thread = checkPlaybackThread_l(output);
819 if (thread == NULL) {
820 return 0.0f;
821 }
822 volume = thread->streamVolume(stream);
823 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800824 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700825 }
826
827 return volume;
828}
829
Glenn Kastenfff6d712012-01-12 16:38:12 -0800830bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700831{
Glenn Kasten263709e2012-01-06 08:40:01 -0800832 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833 return true;
834 }
835
Glenn Kasten6637baa2012-01-09 09:40:36 -0800836 AutoMutex lock(mLock);
837 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700838}
839
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800840status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700841{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800842 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700843 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
844 // check calling permissions
845 if (!settingsAllowed()) {
846 return PERMISSION_DENIED;
847 }
848
Mathias Agopian65ab4712010-07-14 17:59:35 -0700849 // ioHandle == 0 means the parameters are global to the audio hardware interface
850 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700851 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700852 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800853 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700854 AutoMutex lock(mHardwareLock);
855 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
856 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
857 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
858 status_t result = dev->set_parameters(dev, keyValuePairs.string());
859 final_result = result ?: final_result;
860 }
861 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800862 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700863 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
864 AudioParameter param = AudioParameter(keyValuePairs);
865 String8 value;
866 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700867 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
868 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700869 for (size_t i = 0; i < mRecordThreads.size(); i++) {
870 sp<RecordThread> thread = mRecordThreads.valueAt(i);
871 RecordThread::RecordTrack *track = thread->track();
872 if (track != NULL) {
873 audio_devices_t device = (audio_devices_t)(
874 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700875 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700876 thread->setEffectSuspended(FX_IID_AEC,
877 suspend,
878 track->sessionId());
879 thread->setEffectSuspended(FX_IID_NS,
880 suspend,
881 track->sessionId());
882 }
883 }
Eric Laurentbee53372011-08-29 12:42:48 -0700884 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700885 }
886 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700887 String8 screenState;
888 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
889 bool isOff = screenState == "off";
890 if (isOff != (gScreenState & 1)) {
891 gScreenState = ((gScreenState & ~1) + 2) | isOff;
892 }
893 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700894 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700895 }
896
897 // hold a strong ref on thread in case closeOutput() or closeInput() is called
898 // and the thread is exited once the lock is released
899 sp<ThreadBase> thread;
900 {
901 Mutex::Autolock _l(mLock);
902 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -0700903 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700904 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800905 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700906 // indicate output device change to all input threads for pre processing
907 AudioParameter param = AudioParameter(keyValuePairs);
908 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700909 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
910 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700911 for (size_t i = 0; i < mRecordThreads.size(); i++) {
912 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
913 }
914 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700915 }
916 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800917 if (thread != 0) {
918 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700919 }
920 return BAD_VALUE;
921}
922
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800923String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700924{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800925// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700926// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
927
Eric Laurenta4c5a552012-03-29 10:12:40 -0700928 Mutex::Autolock _l(mLock);
929
Mathias Agopian65ab4712010-07-14 17:59:35 -0700930 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700931 String8 out_s8;
932
Dima Zavin799a70e2011-04-18 16:57:27 -0700933 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800934 char *s;
935 {
936 AutoMutex lock(mHardwareLock);
937 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700938 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800939 s = dev->get_parameters(dev, keys.string());
940 mHardwareStatus = AUDIO_HW_IDLE;
941 }
John Grossmanef7740b2012-02-09 11:28:36 -0800942 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700943 free(s);
944 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700945 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700946 }
947
Mathias Agopian65ab4712010-07-14 17:59:35 -0700948 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
949 if (playbackThread != NULL) {
950 return playbackThread->getParameters(keys);
951 }
952 RecordThread *recordThread = checkRecordThread_l(ioHandle);
953 if (recordThread != NULL) {
954 return recordThread->getParameters(keys);
955 }
956 return String8("");
957}
958
Glenn Kastendd8104c2012-07-02 12:42:44 -0700959size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
960 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700961{
Eric Laurenta1884f92011-08-23 08:25:03 -0700962 status_t ret = initCheck();
963 if (ret != NO_ERROR) {
964 return 0;
965 }
966
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800967 AutoMutex lock(mHardwareLock);
968 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700969 struct audio_config config = {
970 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -0700971 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700972 format: format,
973 };
974 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800975 mHardwareStatus = AUDIO_HW_IDLE;
976 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700977}
978
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800979unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700980{
981 if (ioHandle == 0) {
982 return 0;
983 }
984
985 Mutex::Autolock _l(mLock);
986
987 RecordThread *recordThread = checkRecordThread_l(ioHandle);
988 if (recordThread != NULL) {
989 return recordThread->getInputFramesLost();
990 }
991 return 0;
992}
993
994status_t AudioFlinger::setVoiceVolume(float value)
995{
Eric Laurenta1884f92011-08-23 08:25:03 -0700996 status_t ret = initCheck();
997 if (ret != NO_ERROR) {
998 return ret;
999 }
1000
Mathias Agopian65ab4712010-07-14 17:59:35 -07001001 // check calling permissions
1002 if (!settingsAllowed()) {
1003 return PERMISSION_DENIED;
1004 }
1005
1006 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001007 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -07001008 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001009 mHardwareStatus = AUDIO_HW_IDLE;
1010
1011 return ret;
1012}
1013
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001014status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1015 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001016{
1017 status_t status;
1018
1019 Mutex::Autolock _l(mLock);
1020
1021 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1022 if (playbackThread != NULL) {
1023 return playbackThread->getRenderPosition(halFrames, dspFrames);
1024 }
1025
1026 return BAD_VALUE;
1027}
1028
1029void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1030{
1031
1032 Mutex::Autolock _l(mLock);
1033
Glenn Kastenbb001922012-02-03 11:10:26 -08001034 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001035 if (mNotificationClients.indexOfKey(pid) < 0) {
1036 sp<NotificationClient> notificationClient = new NotificationClient(this,
1037 client,
1038 pid);
Steve Block3856b092011-10-20 11:56:00 +01001039 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001040
1041 mNotificationClients.add(pid, notificationClient);
1042
1043 sp<IBinder> binder = client->asBinder();
1044 binder->linkToDeath(notificationClient);
1045
1046 // the config change is always sent from playback or record threads to avoid deadlock
1047 // with AudioSystem::gLock
1048 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1049 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1050 }
1051
1052 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1053 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1054 }
1055 }
1056}
1057
1058void AudioFlinger::removeNotificationClient(pid_t pid)
1059{
1060 Mutex::Autolock _l(mLock);
1061
Glenn Kastena3b09252012-01-20 09:19:01 -08001062 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001063
Steve Block3856b092011-10-20 11:56:00 +01001064 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001065 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001066 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001067 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001068 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001069 ALOGV(" pid %d @ %d", ref->mPid, i);
1070 if (ref->mPid == pid) {
1071 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001072 mAudioSessionRefs.removeAt(i);
1073 delete ref;
1074 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001075 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001076 } else {
1077 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001078 }
1079 }
1080 if (removed) {
1081 purgeStaleEffects_l();
1082 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001083}
1084
1085// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001086void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001087{
1088 size_t size = mNotificationClients.size();
1089 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001090 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1091 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001092 }
1093}
1094
1095// removeClient_l() must be called with AudioFlinger::mLock held
1096void AudioFlinger::removeClient_l(pid_t pid)
1097{
Steve Block3856b092011-10-20 11:56:00 +01001098 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001099 mClients.removeItem(pid);
1100}
1101
Eric Laurent717e1282012-06-29 16:36:52 -07001102// getEffectThread_l() must be called with AudioFlinger::mLock held
1103sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1104{
1105 sp<PlaybackThread> thread;
1106
1107 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1108 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1109 ALOG_ASSERT(thread == 0);
1110 thread = mPlaybackThreads.valueAt(i);
1111 }
1112 }
1113
1114 return thread;
1115}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001116
1117// ----------------------------------------------------------------------------
1118
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001119AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1120 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001121 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001122 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001123 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001124 // mChannelMask
1125 mChannelCount(0),
1126 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1127 mParamStatus(NO_ERROR),
Glenn Kasten94479fd2012-07-09 15:39:54 -07001128 mStandby(false), mDevice((audio_devices_t) device), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001129 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001130{
1131}
1132
1133AudioFlinger::ThreadBase::~ThreadBase()
1134{
1135 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001136 // do not lock the mutex in destructor
1137 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001138 if (mPowerManager != 0) {
1139 sp<IBinder> binder = mPowerManager->asBinder();
1140 binder->unlinkToDeath(mDeathRecipient);
1141 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001142}
1143
1144void AudioFlinger::ThreadBase::exit()
1145{
Steve Block3856b092011-10-20 11:56:00 +01001146 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001147 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001148 // This lock prevents the following race in thread (uniprocessor for illustration):
1149 // if (!exitPending()) {
1150 // // context switch from here to exit()
1151 // // exit() calls requestExit(), what exitPending() observes
1152 // // exit() calls signal(), which is dropped since no waiters
1153 // // context switch back from exit() to here
1154 // mWaitWorkCV.wait(...);
1155 // // now thread is hung
1156 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001157 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001158 requestExit();
1159 mWaitWorkCV.signal();
1160 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001161 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1162 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001163 requestExitAndWait();
1164}
1165
Mathias Agopian65ab4712010-07-14 17:59:35 -07001166status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1167{
1168 status_t status;
1169
Steve Block3856b092011-10-20 11:56:00 +01001170 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001171 Mutex::Autolock _l(mLock);
1172
1173 mNewParameters.add(keyValuePairs);
1174 mWaitWorkCV.signal();
1175 // wait condition with timeout in case the thread loop has exited
1176 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001177 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001178 status = mParamStatus;
1179 mWaitWorkCV.signal();
1180 } else {
1181 status = TIMED_OUT;
1182 }
1183 return status;
1184}
1185
1186void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1187{
1188 Mutex::Autolock _l(mLock);
1189 sendConfigEvent_l(event, param);
1190}
1191
1192// sendConfigEvent_l() must be called with ThreadBase::mLock held
1193void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1194{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001195 ConfigEvent configEvent;
1196 configEvent.mEvent = event;
1197 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001198 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001199 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001200 mWaitWorkCV.signal();
1201}
1202
1203void AudioFlinger::ThreadBase::processConfigEvents()
1204{
1205 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001206 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001207 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001208 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001209 mConfigEvents.removeAt(0);
1210 // release mLock before locking AudioFlinger mLock: lock order is always
1211 // AudioFlinger then ThreadBase to avoid cross deadlock
1212 mLock.unlock();
1213 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001214 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001215 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001216 mLock.lock();
1217 }
1218 mLock.unlock();
1219}
1220
1221status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1222{
1223 const size_t SIZE = 256;
1224 char buffer[SIZE];
1225 String8 result;
1226
1227 bool locked = tryLock(mLock);
1228 if (!locked) {
1229 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1230 write(fd, buffer, strlen(buffer));
1231 }
1232
Eric Laurent612bbb52012-03-14 15:03:26 -07001233 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1234 result.append(buffer);
1235 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1236 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001237 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1238 result.append(buffer);
1239 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1240 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001241 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1242 result.append(buffer);
1243 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001244 result.append(buffer);
1245 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1246 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001247 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1248 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001249 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1250 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001251 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001252 result.append(buffer);
1253
1254 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1255 result.append(buffer);
1256 result.append(" Index Command");
1257 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1258 snprintf(buffer, SIZE, "\n %02d ", i);
1259 result.append(buffer);
1260 result.append(mNewParameters[i]);
1261 }
1262
1263 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1264 result.append(buffer);
1265 snprintf(buffer, SIZE, " Index event param\n");
1266 result.append(buffer);
1267 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001268 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001269 result.append(buffer);
1270 }
1271 result.append("\n");
1272
1273 write(fd, result.string(), result.size());
1274
1275 if (locked) {
1276 mLock.unlock();
1277 }
1278 return NO_ERROR;
1279}
1280
Eric Laurent1d2bff02011-07-24 17:49:51 -07001281status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1282{
1283 const size_t SIZE = 256;
1284 char buffer[SIZE];
1285 String8 result;
1286
1287 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1288 write(fd, buffer, strlen(buffer));
1289
1290 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1291 sp<EffectChain> chain = mEffectChains[i];
1292 if (chain != 0) {
1293 chain->dump(fd, args);
1294 }
1295 }
1296 return NO_ERROR;
1297}
1298
Eric Laurentfeb0db62011-07-22 09:04:31 -07001299void AudioFlinger::ThreadBase::acquireWakeLock()
1300{
1301 Mutex::Autolock _l(mLock);
1302 acquireWakeLock_l();
1303}
1304
1305void AudioFlinger::ThreadBase::acquireWakeLock_l()
1306{
1307 if (mPowerManager == 0) {
1308 // use checkService() to avoid blocking if power service is not up yet
1309 sp<IBinder> binder =
1310 defaultServiceManager()->checkService(String16("power"));
1311 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001312 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001313 } else {
1314 mPowerManager = interface_cast<IPowerManager>(binder);
1315 binder->linkToDeath(mDeathRecipient);
1316 }
1317 }
1318 if (mPowerManager != 0) {
1319 sp<IBinder> binder = new BBinder();
1320 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1321 binder,
1322 String16(mName));
1323 if (status == NO_ERROR) {
1324 mWakeLockToken = binder;
1325 }
Steve Block3856b092011-10-20 11:56:00 +01001326 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001327 }
1328}
1329
1330void AudioFlinger::ThreadBase::releaseWakeLock()
1331{
1332 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001333 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001334}
1335
1336void AudioFlinger::ThreadBase::releaseWakeLock_l()
1337{
1338 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001339 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001340 if (mPowerManager != 0) {
1341 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1342 }
1343 mWakeLockToken.clear();
1344 }
1345}
1346
1347void AudioFlinger::ThreadBase::clearPowerManager()
1348{
1349 Mutex::Autolock _l(mLock);
1350 releaseWakeLock_l();
1351 mPowerManager.clear();
1352}
1353
1354void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1355{
1356 sp<ThreadBase> thread = mThread.promote();
1357 if (thread != 0) {
1358 thread->clearPowerManager();
1359 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001360 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001361}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001362
Eric Laurent59255e42011-07-27 19:49:51 -07001363void AudioFlinger::ThreadBase::setEffectSuspended(
1364 const effect_uuid_t *type, bool suspend, int sessionId)
1365{
1366 Mutex::Autolock _l(mLock);
1367 setEffectSuspended_l(type, suspend, sessionId);
1368}
1369
1370void AudioFlinger::ThreadBase::setEffectSuspended_l(
1371 const effect_uuid_t *type, bool suspend, int sessionId)
1372{
Glenn Kasten090f0192012-01-30 13:00:02 -08001373 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001374 if (chain != 0) {
1375 if (type != NULL) {
1376 chain->setEffectSuspended_l(type, suspend);
1377 } else {
1378 chain->setEffectSuspendedAll_l(suspend);
1379 }
1380 }
1381
1382 updateSuspendedSessions_l(type, suspend, sessionId);
1383}
1384
1385void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1386{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001387 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001388 if (index < 0) {
1389 return;
1390 }
1391
1392 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1393 mSuspendedSessions.editValueAt(index);
1394
1395 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001396 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001397 for (int j = 0; j < desc->mRefCount; j++) {
1398 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1399 chain->setEffectSuspendedAll_l(true);
1400 } else {
Steve Block3856b092011-10-20 11:56:00 +01001401 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001402 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001403 chain->setEffectSuspended_l(&desc->mType, true);
1404 }
1405 }
1406 }
1407}
1408
Eric Laurent59255e42011-07-27 19:49:51 -07001409void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1410 bool suspend,
1411 int sessionId)
1412{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001413 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001414
1415 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1416
1417 if (suspend) {
1418 if (index >= 0) {
1419 sessionEffects = mSuspendedSessions.editValueAt(index);
1420 } else {
1421 mSuspendedSessions.add(sessionId, sessionEffects);
1422 }
1423 } else {
1424 if (index < 0) {
1425 return;
1426 }
1427 sessionEffects = mSuspendedSessions.editValueAt(index);
1428 }
1429
1430
1431 int key = EffectChain::kKeyForSuspendAll;
1432 if (type != NULL) {
1433 key = type->timeLow;
1434 }
1435 index = sessionEffects.indexOfKey(key);
1436
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001437 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001438 if (suspend) {
1439 if (index >= 0) {
1440 desc = sessionEffects.valueAt(index);
1441 } else {
1442 desc = new SuspendedSessionDesc();
1443 if (type != NULL) {
1444 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1445 }
1446 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001447 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001448 }
1449 desc->mRefCount++;
1450 } else {
1451 if (index < 0) {
1452 return;
1453 }
1454 desc = sessionEffects.valueAt(index);
1455 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001456 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001457 sessionEffects.removeItemsAt(index);
1458 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001459 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001460 sessionId);
1461 mSuspendedSessions.removeItem(sessionId);
1462 }
1463 }
1464 }
1465 if (!sessionEffects.isEmpty()) {
1466 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1467 }
1468}
1469
1470void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1471 bool enabled,
1472 int sessionId)
1473{
1474 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001475 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1476}
Eric Laurent59255e42011-07-27 19:49:51 -07001477
Eric Laurenta85a74a2011-10-19 11:44:54 -07001478void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1479 bool enabled,
1480 int sessionId)
1481{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001482 if (mType != RECORD) {
1483 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1484 // another session. This gives the priority to well behaved effect control panels
1485 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001486 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1487 // global effects
1488 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001489 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1490 }
1491 }
Eric Laurent59255e42011-07-27 19:49:51 -07001492
1493 sp<EffectChain> chain = getEffectChain_l(sessionId);
1494 if (chain != 0) {
1495 chain->checkSuspendOnEffectEnabled(effect, enabled);
1496 }
1497}
1498
Mathias Agopian65ab4712010-07-14 17:59:35 -07001499// ----------------------------------------------------------------------------
1500
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001501AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1502 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001503 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001504 uint32_t device,
1505 type_t type)
1506 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001507 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1508 // Assumes constructor is called by AudioFlinger with it's mLock held,
1509 // but it would be safer to explicitly pass initial masterMute as parameter
1510 mMasterMute(audioFlinger->masterMute_l()),
1511 // mStreamTypes[] initialized in constructor body
1512 mOutput(output),
1513 // Assumes constructor is called by AudioFlinger with it's mLock held,
1514 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001515 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001516 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001517 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001518 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001519 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001520 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001521 // index 0 is reserved for normal mixer's submix
1522 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001523{
Glenn Kasten480b4682012-02-28 12:30:08 -08001524 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001525
Mathias Agopian65ab4712010-07-14 17:59:35 -07001526 readOutputParameters();
1527
Glenn Kasten263709e2012-01-06 08:40:01 -08001528 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001529 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1530 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1531 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001532 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1533 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001534 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001535 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1536 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001537}
1538
1539AudioFlinger::PlaybackThread::~PlaybackThread()
1540{
1541 delete [] mMixBuffer;
1542}
1543
1544status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1545{
1546 dumpInternals(fd, args);
1547 dumpTracks(fd, args);
1548 dumpEffectChains(fd, args);
1549 return NO_ERROR;
1550}
1551
1552status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1553{
1554 const size_t SIZE = 256;
1555 char buffer[SIZE];
1556 String8 result;
1557
Glenn Kasten58912562012-04-03 10:45:00 -07001558 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1559 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1560 const stream_type_t *st = &mStreamTypes[i];
1561 if (i > 0) {
1562 result.appendFormat(", ");
1563 }
1564 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1565 if (st->mute) {
1566 result.append("M");
1567 }
1568 }
1569 result.append("\n");
1570 write(fd, result.string(), result.length());
1571 result.clear();
1572
Mathias Agopian65ab4712010-07-14 17:59:35 -07001573 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1574 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001575 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001576 for (size_t i = 0; i < mTracks.size(); ++i) {
1577 sp<Track> track = mTracks[i];
1578 if (track != 0) {
1579 track->dump(buffer, SIZE);
1580 result.append(buffer);
1581 }
1582 }
1583
1584 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1585 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001586 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001587 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001588 sp<Track> track = mActiveTracks[i].promote();
1589 if (track != 0) {
1590 track->dump(buffer, SIZE);
1591 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001592 }
1593 }
1594 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001595
1596 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1597 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1598 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1599 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1600
Mathias Agopian65ab4712010-07-14 17:59:35 -07001601 return NO_ERROR;
1602}
1603
Mathias Agopian65ab4712010-07-14 17:59:35 -07001604status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1605{
1606 const size_t SIZE = 256;
1607 char buffer[SIZE];
1608 String8 result;
1609
1610 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1611 result.append(buffer);
1612 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1613 result.append(buffer);
1614 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1615 result.append(buffer);
1616 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1617 result.append(buffer);
1618 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1619 result.append(buffer);
1620 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1621 result.append(buffer);
1622 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1623 result.append(buffer);
1624 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001625 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001626
1627 dumpBase(fd, args);
1628
1629 return NO_ERROR;
1630}
1631
1632// Thread virtuals
1633status_t AudioFlinger::PlaybackThread::readyToRun()
1634{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001635 status_t status = initCheck();
1636 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001637 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001638 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001639 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001640 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001641 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001642}
1643
1644void AudioFlinger::PlaybackThread::onFirstRef()
1645{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001646 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001647}
1648
1649// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001650sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001651 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001652 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001653 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001654 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001655 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001656 int frameCount,
1657 const sp<IMemory>& sharedBuffer,
1658 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001659 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001660 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001661 status_t *status)
1662{
1663 sp<Track> track;
1664 status_t lStatus;
1665
Glenn Kasten73d22752012-03-19 13:38:30 -07001666 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1667
1668 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001669 if (flags & IAudioFlinger::TRACK_FAST) {
1670 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001671 // not timed
1672 (!isTimed) &&
1673 // either of these use cases:
1674 (
1675 // use case 1: shared buffer with any frame count
1676 (
1677 (sharedBuffer != 0)
1678 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001679 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001680 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001681 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001682 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001683 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001684 )
1685 ) &&
1686 // PCM data
1687 audio_is_linear_pcm(format) &&
1688 // mono or stereo
1689 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1690 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001691#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001692 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001693 (sampleRate == mSampleRate) &&
1694#endif
1695 // normal mixer has an associated fast mixer
1696 hasFastMixer() &&
1697 // there are sufficient fast track slots available
1698 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001699 // FIXME test that MixerThread for this fast track has a capable output HAL
1700 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001701 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001702 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1703 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001704 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001705 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001706 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001707 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001708 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001709 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001710 "mFrameCount=%d format=%d isLinear=%d channelMask=%d sampleRate=%d mSampleRate=%d "
1711 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1712 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1713 audio_is_linear_pcm(format),
1714 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001715 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001716 // For compatibility with AudioTrack calculation, buffer depth is forced
1717 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1718 // This is probably too conservative, but legacy application code may depend on it.
1719 // If you change this calculation, also review the start threshold which is related.
1720 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1721 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1722 if (minBufCount < 2) {
1723 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001724 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001725 int minFrameCount = mNormalFrameCount * minBufCount;
1726 if (frameCount < minFrameCount) {
1727 frameCount = minFrameCount;
1728 }
1729 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001730 }
1731
Mathias Agopian65ab4712010-07-14 17:59:35 -07001732 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001733 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1734 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001735 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001736 "for output %p with format %d",
1737 sampleRate, format, channelMask, mOutput, mFormat);
1738 lStatus = BAD_VALUE;
1739 goto Exit;
1740 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001741 }
1742 } else {
1743 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1744 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001745 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001746 lStatus = BAD_VALUE;
1747 goto Exit;
1748 }
1749 }
1750
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001751 lStatus = initCheck();
1752 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001753 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001754 goto Exit;
1755 }
1756
1757 { // scope for mLock
1758 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001759
1760 // all tracks in same audio session must share the same routing strategy otherwise
1761 // conflicts will happen when tracks are moved from one output to another by audio policy
1762 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001763 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001764 for (size_t i = 0; i < mTracks.size(); ++i) {
1765 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001766 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001767 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001768 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001769 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001770 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001771 lStatus = BAD_VALUE;
1772 goto Exit;
1773 }
1774 }
1775 }
1776
John Grossman4ff14ba2012-02-08 16:37:41 -08001777 if (!isTimed) {
1778 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001779 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001780 } else {
1781 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1782 channelMask, frameCount, sharedBuffer, sessionId);
1783 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001784 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001785 lStatus = NO_MEMORY;
1786 goto Exit;
1787 }
1788 mTracks.add(track);
1789
1790 sp<EffectChain> chain = getEffectChain_l(sessionId);
1791 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001792 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001793 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001794 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001795 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001796 }
1797 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001798
Glenn Kasten3acbd052012-02-28 10:39:56 -08001799 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1800 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1801 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1802 // so ask activity manager to do this on our behalf
1803 int err = requestPriority(callingPid, tid, 1);
1804 if (err != 0) {
1805 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1806 1, callingPid, tid, err);
1807 }
1808 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001809
Mathias Agopian65ab4712010-07-14 17:59:35 -07001810 lStatus = NO_ERROR;
1811
1812Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001813 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001814 *status = lStatus;
1815 }
1816 return track;
1817}
1818
Eric Laurente737cda2012-05-22 18:55:44 -07001819uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1820{
1821 if (mFastMixer != NULL) {
1822 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1823 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1824 }
1825 return latency;
1826}
1827
1828uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1829{
1830 return latency;
1831}
1832
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833uint32_t AudioFlinger::PlaybackThread::latency() const
1834{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001835 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001836 return latency_l();
1837}
1838uint32_t AudioFlinger::PlaybackThread::latency_l() const
1839{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001840 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001841 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001842 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001843 return 0;
1844 }
1845}
1846
Glenn Kasten6637baa2012-01-09 09:40:36 -08001847void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001848{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001849 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001850 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001851}
1852
Glenn Kasten6637baa2012-01-09 09:40:36 -08001853void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001854{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001855 Mutex::Autolock _l(mLock);
1856 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001857}
1858
Glenn Kasten6637baa2012-01-09 09:40:36 -08001859void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001860{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001861 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001862 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001863}
1864
Glenn Kasten6637baa2012-01-09 09:40:36 -08001865void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001866{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001867 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001868 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001869}
1870
Glenn Kastenfff6d712012-01-12 16:38:12 -08001871float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001872{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001873 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001874 return mStreamTypes[stream].volume;
1875}
1876
Mathias Agopian65ab4712010-07-14 17:59:35 -07001877// addTrack_l() must be called with ThreadBase::mLock held
1878status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1879{
1880 status_t status = ALREADY_EXISTS;
1881
1882 // set retry count for buffer fill
1883 track->mRetryCount = kMaxTrackStartupRetries;
1884 if (mActiveTracks.indexOf(track) < 0) {
1885 // the track is newly added, make sure it fills up all its
1886 // buffers before playing. This is to ensure the client will
1887 // effectively get the latency it requested.
1888 track->mFillingUpStatus = Track::FS_FILLING;
1889 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001890 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001891 mActiveTracks.add(track);
1892 if (track->mainBuffer() != mMixBuffer) {
1893 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1894 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001895 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001896 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001897 }
1898 }
1899
1900 status = NO_ERROR;
1901 }
1902
Steve Block3856b092011-10-20 11:56:00 +01001903 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001904 mWaitWorkCV.broadcast();
1905
1906 return status;
1907}
1908
1909// destroyTrack_l() must be called with ThreadBase::mLock held
1910void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1911{
1912 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001913 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001914 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001915 removeTrack_l(track);
1916 }
1917}
1918
1919void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1920{
Eric Laurent29864602012-05-08 18:57:51 -07001921 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001922 mTracks.remove(track);
1923 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001924 // redundant as track is about to be destroyed, for dumpsys only
1925 track->mName = -1;
1926 if (track->isFastTrack()) {
1927 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001928 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001929 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1930 mFastTrackAvailMask |= 1 << index;
1931 // redundant as track is about to be destroyed, for dumpsys only
1932 track->mFastIndex = -1;
1933 }
Eric Laurentb469b942011-05-09 12:09:06 -07001934 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1935 if (chain != 0) {
1936 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001937 }
1938}
1939
1940String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1941{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001942 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001943 char *s;
1944
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001945 Mutex::Autolock _l(mLock);
1946 if (initCheck() != NO_ERROR) {
1947 return out_s8;
1948 }
1949
Dima Zavin799a70e2011-04-18 16:57:27 -07001950 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001951 out_s8 = String8(s);
1952 free(s);
1953 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001954}
1955
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001956// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001957void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1958 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001959 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001960
Steve Block3856b092011-10-20 11:56:00 +01001961 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001962
1963 switch (event) {
1964 case AudioSystem::OUTPUT_OPENED:
1965 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001966 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001967 desc.samplingRate = mSampleRate;
1968 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001969 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001970 desc.latency = latency();
1971 param2 = &desc;
1972 break;
1973
1974 case AudioSystem::STREAM_CONFIG_CHANGED:
1975 param2 = &param;
1976 case AudioSystem::OUTPUT_CLOSED:
1977 default:
1978 break;
1979 }
1980 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1981}
1982
1983void AudioFlinger::PlaybackThread::readOutputParameters()
1984{
Dima Zavin799a70e2011-04-18 16:57:27 -07001985 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001986 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1987 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001988 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001989 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001990 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001991 if (mFrameCount & 15) {
1992 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1993 mFrameCount);
1994 }
1995
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001996 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07001997 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001998 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07001999 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002000 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2001 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2002 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2003 maxNormalFrameCount = maxNormalFrameCount & ~15;
2004 if (maxNormalFrameCount < minNormalFrameCount) {
2005 maxNormalFrameCount = minNormalFrameCount;
2006 }
2007 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2008 if (multiplier <= 1.0) {
2009 multiplier = 1.0;
2010 } else if (multiplier <= 2.0) {
2011 if (2 * mFrameCount <= maxNormalFrameCount) {
2012 multiplier = 2.0;
2013 } else {
2014 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2015 }
2016 } else {
2017 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2018 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2019 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2020 // FIXME this rounding up should not be done if no HAL SRC
2021 uint32_t truncMult = (uint32_t) multiplier;
2022 if ((truncMult & 1)) {
2023 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2024 ++truncMult;
2025 }
2026 }
2027 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002028 }
Glenn Kasten58912562012-04-03 10:45:00 -07002029 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002030 mNormalFrameCount = multiplier * mFrameCount;
2031 // round up to nearest 16 frames to satisfy AudioMixer
2032 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002033 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002034
Glenn Kastene9dd0172012-01-27 18:08:45 -08002035 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002036 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2037 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002038
Eric Laurentde070132010-07-13 04:45:46 -07002039 // force reconfiguration of effect chains and engines to take new buffer size and audio
2040 // parameters into account
2041 // Note that mLock is not held when readOutputParameters() is called from the constructor
2042 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2043 // matter.
2044 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2045 Vector< sp<EffectChain> > effectChains = mEffectChains;
2046 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002047 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002048 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002049}
2050
Eric Laurente737cda2012-05-22 18:55:44 -07002051
Mathias Agopian65ab4712010-07-14 17:59:35 -07002052status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2053{
Glenn Kastena0d68332012-01-27 16:47:15 -08002054 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002055 return BAD_VALUE;
2056 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002057 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002058 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002059 return INVALID_OPERATION;
2060 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002061 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002062
Dima Zavin799a70e2011-04-18 16:57:27 -07002063 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002064}
2065
Eric Laurent39e94f82010-07-28 01:32:47 -07002066uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002067{
2068 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002069 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002070 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002071 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002072 }
2073
2074 for (size_t i = 0; i < mTracks.size(); ++i) {
2075 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002076 if (sessionId == track->sessionId() &&
2077 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002078 result |= TRACK_SESSION;
2079 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002080 }
2081 }
2082
Eric Laurent39e94f82010-07-28 01:32:47 -07002083 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002084}
2085
Eric Laurentde070132010-07-13 04:45:46 -07002086uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2087{
Dima Zavinfce7a472011-04-19 22:30:36 -07002088 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002089 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002090 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2091 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002092 }
2093 for (size_t i = 0; i < mTracks.size(); i++) {
2094 sp<Track> track = mTracks[i];
2095 if (sessionId == track->sessionId() &&
2096 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002097 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002098 }
2099 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002100 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002101}
2102
Mathias Agopian65ab4712010-07-14 17:59:35 -07002103
Glenn Kastenaed850d2012-01-26 09:46:34 -08002104AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002105{
2106 Mutex::Autolock _l(mLock);
2107 return mOutput;
2108}
2109
2110AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2111{
2112 Mutex::Autolock _l(mLock);
2113 AudioStreamOut *output = mOutput;
2114 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002115 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2116 // must push a NULL and wait for ack
2117 mOutputSink.clear();
2118 mPipeSink.clear();
2119 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002120 return output;
2121}
2122
2123// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002124audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002125{
2126 if (mOutput == NULL) {
2127 return NULL;
2128 }
2129 return &mOutput->stream->common;
2130}
2131
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002132uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002133{
Eric Laurentab9071b2012-06-04 13:45:29 -07002134 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002135}
2136
Eric Laurenta011e352012-03-29 15:51:43 -07002137status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2138{
2139 if (!isValidSyncEvent(event)) {
2140 return BAD_VALUE;
2141 }
2142
2143 Mutex::Autolock _l(mLock);
2144
2145 for (size_t i = 0; i < mTracks.size(); ++i) {
2146 sp<Track> track = mTracks[i];
2147 if (event->triggerSession() == track->sessionId()) {
2148 track->setSyncEvent(event);
2149 return NO_ERROR;
2150 }
2151 }
2152
2153 return NAME_NOT_FOUND;
2154}
2155
2156bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2157{
2158 switch (event->type()) {
2159 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2160 return true;
2161 default:
2162 break;
2163 }
2164 return false;
2165}
2166
Eric Laurent44a957f2012-05-15 15:26:05 -07002167void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2168{
2169 size_t count = tracksToRemove.size();
2170 if (CC_UNLIKELY(count)) {
2171 for (size_t i = 0 ; i < count ; i++) {
2172 const sp<Track>& track = tracksToRemove.itemAt(i);
2173 if ((track->sharedBuffer() != 0) &&
2174 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2175 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2176 }
2177 }
2178 }
2179
2180}
2181
Mathias Agopian65ab4712010-07-14 17:59:35 -07002182// ----------------------------------------------------------------------------
2183
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002184AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002185 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002186 : PlaybackThread(audioFlinger, output, id, device, type),
2187 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002188 // mFastMixer below
2189 mFastMixerFutex(0)
2190 // mOutputSink below
2191 // mPipeSink below
2192 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002193{
Glenn Kasten58912562012-04-03 10:45:00 -07002194 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2195 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2196 "mFrameCount=%d, mNormalFrameCount=%d",
2197 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2198 mNormalFrameCount);
2199 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2200
Mathias Agopian65ab4712010-07-14 17:59:35 -07002201 // FIXME - Current mixer implementation only supports stereo output
2202 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002203 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002204 }
Glenn Kasten58912562012-04-03 10:45:00 -07002205
2206 // create an NBAIO sink for the HAL output stream, and negotiate
2207 mOutputSink = new AudioStreamOutSink(output->stream);
2208 size_t numCounterOffers = 0;
2209 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2210 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2211 ALOG_ASSERT(index == 0);
2212
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002213 // initialize fast mixer depending on configuration
2214 bool initFastMixer;
2215 switch (kUseFastMixer) {
2216 case FastMixer_Never:
2217 initFastMixer = false;
2218 break;
2219 case FastMixer_Always:
2220 initFastMixer = true;
2221 break;
2222 case FastMixer_Static:
2223 case FastMixer_Dynamic:
2224 initFastMixer = mFrameCount < mNormalFrameCount;
2225 break;
2226 }
2227 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002228
2229 // create a MonoPipe to connect our submix to FastMixer
2230 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002231 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2232 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2233 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2234 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002235 const NBAIO_Format offers[1] = {format};
2236 size_t numCounterOffers = 0;
2237 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2238 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002239 monoPipe->setAvgFrames((mScreenState & 1) ?
2240 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002241 mPipeSink = monoPipe;
2242
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002243#ifdef TEE_SINK_FRAMES
2244 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2245 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2246 numCounterOffers = 0;
2247 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2248 ALOG_ASSERT(index == 0);
2249 mTeeSink = teeSink;
2250 PipeReader *teeSource = new PipeReader(*teeSink);
2251 numCounterOffers = 0;
2252 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2253 ALOG_ASSERT(index == 0);
2254 mTeeSource = teeSource;
2255#endif
2256
Glenn Kasten58912562012-04-03 10:45:00 -07002257 // create fast mixer and configure it initially with just one fast track for our submix
2258 mFastMixer = new FastMixer();
2259 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002260#ifdef STATE_QUEUE_DUMP
2261 sq->setObserverDump(&mStateQueueObserverDump);
2262 sq->setMutatorDump(&mStateQueueMutatorDump);
2263#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002264 FastMixerState *state = sq->begin();
2265 FastTrack *fastTrack = &state->mFastTracks[0];
2266 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2267 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2268 fastTrack->mVolumeProvider = NULL;
2269 fastTrack->mGeneration++;
2270 state->mFastTracksGen++;
2271 state->mTrackMask = 1;
2272 // fast mixer will use the HAL output sink
2273 state->mOutputSink = mOutputSink.get();
2274 state->mOutputSinkGen++;
2275 state->mFrameCount = mFrameCount;
2276 state->mCommand = FastMixerState::COLD_IDLE;
2277 // already done in constructor initialization list
2278 //mFastMixerFutex = 0;
2279 state->mColdFutexAddr = &mFastMixerFutex;
2280 state->mColdGen++;
2281 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002282 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002283 sq->end();
2284 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2285
2286 // start the fast mixer
2287 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002288 pid_t tid = mFastMixer->getTid();
2289 int err = requestPriority(getpid_cached, tid, 2);
2290 if (err != 0) {
2291 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2292 2, getpid_cached, tid, err);
2293 }
Glenn Kasten58912562012-04-03 10:45:00 -07002294
Glenn Kastenc15d6652012-05-30 14:52:57 -07002295#ifdef AUDIO_WATCHDOG
2296 // create and start the watchdog
2297 mAudioWatchdog = new AudioWatchdog();
2298 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2299 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2300 tid = mAudioWatchdog->getTid();
2301 err = requestPriority(getpid_cached, tid, 1);
2302 if (err != 0) {
2303 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2304 1, getpid_cached, tid, err);
2305 }
2306#endif
2307
Glenn Kasten58912562012-04-03 10:45:00 -07002308 } else {
2309 mFastMixer = NULL;
2310 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002311
2312 switch (kUseFastMixer) {
2313 case FastMixer_Never:
2314 case FastMixer_Dynamic:
2315 mNormalSink = mOutputSink;
2316 break;
2317 case FastMixer_Always:
2318 mNormalSink = mPipeSink;
2319 break;
2320 case FastMixer_Static:
2321 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2322 break;
2323 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002324}
2325
2326AudioFlinger::MixerThread::~MixerThread()
2327{
Glenn Kasten58912562012-04-03 10:45:00 -07002328 if (mFastMixer != NULL) {
2329 FastMixerStateQueue *sq = mFastMixer->sq();
2330 FastMixerState *state = sq->begin();
2331 if (state->mCommand == FastMixerState::COLD_IDLE) {
2332 int32_t old = android_atomic_inc(&mFastMixerFutex);
2333 if (old == -1) {
2334 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2335 }
2336 }
2337 state->mCommand = FastMixerState::EXIT;
2338 sq->end();
2339 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2340 mFastMixer->join();
2341 // Though the fast mixer thread has exited, it's state queue is still valid.
2342 // We'll use that extract the final state which contains one remaining fast track
2343 // corresponding to our sub-mix.
2344 state = sq->begin();
2345 ALOG_ASSERT(state->mTrackMask == 1);
2346 FastTrack *fastTrack = &state->mFastTracks[0];
2347 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2348 delete fastTrack->mBufferProvider;
2349 sq->end(false /*didModify*/);
2350 delete mFastMixer;
Glenn Kastenc15d6652012-05-30 14:52:57 -07002351 if (mAudioWatchdog != 0) {
2352 mAudioWatchdog->requestExit();
2353 mAudioWatchdog->requestExitAndWait();
2354 mAudioWatchdog.clear();
2355 }
Glenn Kasten58912562012-04-03 10:45:00 -07002356 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002357 delete mAudioMixer;
2358}
2359
Glenn Kasten83efdd02012-02-24 07:21:32 -08002360class CpuStats {
2361public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002362 CpuStats();
2363 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002364#ifdef DEBUG_CPU_USAGE
2365private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002366 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2367 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2368
2369 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2370
2371 int mCpuNum; // thread's current CPU number
2372 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002373#endif
2374};
2375
Glenn Kasten190a46f2012-03-06 11:27:10 -08002376CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002377#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002378 : mCpuNum(-1), mCpukHz(-1)
2379#endif
2380{
2381}
2382
2383void CpuStats::sample(const String8 &title) {
2384#ifdef DEBUG_CPU_USAGE
2385 // get current thread's delta CPU time in wall clock ns
2386 double wcNs;
2387 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2388
2389 // record sample for wall clock statistics
2390 if (valid) {
2391 mWcStats.sample(wcNs);
2392 }
2393
2394 // get the current CPU number
2395 int cpuNum = sched_getcpu();
2396
2397 // get the current CPU frequency in kHz
2398 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2399
2400 // check if either CPU number or frequency changed
2401 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2402 mCpuNum = cpuNum;
2403 mCpukHz = cpukHz;
2404 // ignore sample for purposes of cycles
2405 valid = false;
2406 }
2407
2408 // if no change in CPU number or frequency, then record sample for cycle statistics
2409 if (valid && mCpukHz > 0) {
2410 double cycles = wcNs * cpukHz * 0.000001;
2411 mHzStats.sample(cycles);
2412 }
2413
2414 unsigned n = mWcStats.n();
2415 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002416 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002417 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002418 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2419 double perLoop = elapsed / (double) n;
2420 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002421 double perLoop1k = perLoop * 0.001;
2422 double mean = mWcStats.mean();
2423 double stddev = mWcStats.stddev();
2424 double minimum = mWcStats.minimum();
2425 double maximum = mWcStats.maximum();
2426 double meanCycles = mHzStats.mean();
2427 double stddevCycles = mHzStats.stddev();
2428 double minCycles = mHzStats.minimum();
2429 double maxCycles = mHzStats.maximum();
2430 mCpuUsage.resetElapsed();
2431 mWcStats.reset();
2432 mHzStats.reset();
2433 ALOGD("CPU usage for %s over past %.1f secs\n"
2434 " (%u mixer loops at %.1f mean ms per loop):\n"
2435 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2436 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2437 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2438 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002439 elapsed * .000000001, n, perLoop * .000001,
2440 mean * .001,
2441 stddev * .001,
2442 minimum * .001,
2443 maximum * .001,
2444 mean / perLoop100,
2445 stddev / perLoop100,
2446 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002447 maximum / perLoop100,
2448 meanCycles / perLoop1k,
2449 stddevCycles / perLoop1k,
2450 minCycles / perLoop1k,
2451 maxCycles / perLoop1k);
2452
Glenn Kasten83efdd02012-02-24 07:21:32 -08002453 }
2454 }
2455#endif
2456};
2457
Glenn Kasten37d825e2012-02-24 07:21:48 -08002458void AudioFlinger::PlaybackThread::checkSilentMode_l()
2459{
2460 if (!mMasterMute) {
2461 char value[PROPERTY_VALUE_MAX];
2462 if (property_get("ro.audio.silent", value, "0") > 0) {
2463 char *endptr;
2464 unsigned long ul = strtoul(value, &endptr, 0);
2465 if (*endptr == '\0' && ul != 0) {
2466 ALOGD("Silence is golden");
2467 // The setprop command will not allow a property to be changed after
2468 // the first time it is set, so we don't have to worry about un-muting.
2469 setMasterMute_l(true);
2470 }
2471 }
2472 }
2473}
2474
Glenn Kasten000f0e32012-03-01 17:10:56 -08002475bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002476{
2477 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002478
Glenn Kasten000f0e32012-03-01 17:10:56 -08002479 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002480
2481 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002482 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002483
Glenn Kasten000f0e32012-03-01 17:10:56 -08002484 // DUPLICATING
2485 // FIXME could this be made local to while loop?
2486 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002487
Glenn Kasten66fcab92012-02-24 14:59:21 -08002488 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002489 sleepTime = idleSleepTime;
2490
2491if (mType == MIXER) {
2492 sleepTimeShift = 0;
2493}
2494
Glenn Kasten83efdd02012-02-24 07:21:32 -08002495 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002496 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002497
Eric Laurentfeb0db62011-07-22 09:04:31 -07002498 acquireWakeLock();
2499
Mathias Agopian65ab4712010-07-14 17:59:35 -07002500 while (!exitPending())
2501 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002502 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002503
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002504 Vector< sp<EffectChain> > effectChains;
2505
Mathias Agopian65ab4712010-07-14 17:59:35 -07002506 processConfigEvents();
2507
Mathias Agopian65ab4712010-07-14 17:59:35 -07002508 { // scope for mLock
2509
2510 Mutex::Autolock _l(mLock);
2511
2512 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002513 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002514 }
2515
Glenn Kastenfa26a852012-03-06 11:28:04 -08002516 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002517
Mathias Agopian65ab4712010-07-14 17:59:35 -07002518 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002519 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002520 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002521 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002522
2523 threadLoop_standby();
2524
Mathias Agopian65ab4712010-07-14 17:59:35 -07002525 mStandby = true;
2526 mBytesWritten = 0;
2527 }
2528
Glenn Kasten3e074702012-02-28 18:40:35 -08002529 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002530 // we're about to wait, flush the binder command buffer
2531 IPCThreadState::self()->flushCommands();
2532
Glenn Kastenfa26a852012-03-06 11:28:04 -08002533 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002534
Mathias Agopian65ab4712010-07-14 17:59:35 -07002535 if (exitPending()) break;
2536
Eric Laurentfeb0db62011-07-22 09:04:31 -07002537 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002538 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002539 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002540 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002541 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002542 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002543
Eric Laurentda747442012-04-25 18:53:13 -07002544 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002545 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002546
Glenn Kasten37d825e2012-02-24 07:21:48 -08002547 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002548
Glenn Kasten000f0e32012-03-01 17:10:56 -08002549 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002550 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002551 if (mType == MIXER) {
2552 sleepTimeShift = 0;
2553 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002554
Mathias Agopian65ab4712010-07-14 17:59:35 -07002555 continue;
2556 }
2557 }
2558
Glenn Kasten81028042012-04-30 18:15:12 -07002559 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002560 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002561
2562 // prevent any changes in effect chain list and in each effect chain
2563 // during mixing and effect process as the audio buffers could be deleted
2564 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002565 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002566 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002567
Glenn Kastenfec279f2012-03-08 07:47:15 -08002568 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002569 threadLoop_mix();
2570 } else {
2571 threadLoop_sleepTime();
2572 }
2573
2574 if (mSuspended > 0) {
2575 sleepTime = suspendSleepTimeUs();
2576 }
2577
2578 // only process effects if we're going to write
2579 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002580 for (size_t i = 0; i < effectChains.size(); i ++) {
2581 effectChains[i]->process_l();
2582 }
2583 }
2584
2585 // enable changes in effect chain
2586 unlockEffectChains(effectChains);
2587
2588 // sleepTime == 0 means we must write to audio hardware
2589 if (sleepTime == 0) {
2590
2591 threadLoop_write();
2592
2593if (mType == MIXER) {
2594 // write blocked detection
2595 nsecs_t now = systemTime();
2596 nsecs_t delta = now - mLastWriteTime;
2597 if (!mStandby && delta > maxPeriod) {
2598 mNumDelayedWrites++;
2599 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002600#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002601 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002602#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002603 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2604 ns2ms(delta), mNumDelayedWrites, this);
2605 lastWarning = now;
2606 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002607 }
2608}
2609
2610 mStandby = false;
2611 } else {
2612 usleep(sleepTime);
2613 }
2614
Glenn Kasten58912562012-04-03 10:45:00 -07002615 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002616 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002617 // same lock. This will also mutate and push a new fast mixer state.
2618 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002619 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002620
Glenn Kastenfa26a852012-03-06 11:28:04 -08002621 // FIXME I don't understand the need for this here;
2622 // it was in the original code but maybe the
2623 // assignment in saveOutputTracks() makes this unnecessary?
2624 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002625
2626 // Effect chains will be actually deleted here if they were removed from
2627 // mEffectChains list during mixing or effects processing
2628 effectChains.clear();
2629
2630 // FIXME Note that the above .clear() is no longer necessary since effectChains
2631 // is now local to this block, but will keep it for now (at least until merge done).
2632 }
2633
2634if (mType == MIXER || mType == DIRECT) {
2635 // put output stream into standby mode
2636 if (!mStandby) {
2637 mOutput->stream->common.standby(&mOutput->stream->common);
2638 }
2639}
2640if (mType == DUPLICATING) {
2641 // for DuplicatingThread, standby mode is handled by the outputTracks
2642}
2643
2644 releaseWakeLock();
2645
2646 ALOGV("Thread %p type %d exiting", this, mType);
2647 return false;
2648}
2649
Glenn Kasten58912562012-04-03 10:45:00 -07002650void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2651{
Glenn Kasten58912562012-04-03 10:45:00 -07002652 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2653}
2654
2655void AudioFlinger::MixerThread::threadLoop_write()
2656{
2657 // FIXME we should only do one push per cycle; confirm this is true
2658 // Start the fast mixer if it's not already running
2659 if (mFastMixer != NULL) {
2660 FastMixerStateQueue *sq = mFastMixer->sq();
2661 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002662 if (state->mCommand != FastMixerState::MIX_WRITE &&
2663 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002664 if (state->mCommand == FastMixerState::COLD_IDLE) {
2665 int32_t old = android_atomic_inc(&mFastMixerFutex);
2666 if (old == -1) {
2667 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2668 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002669 if (mAudioWatchdog != 0) {
2670 mAudioWatchdog->resume();
2671 }
Glenn Kasten58912562012-04-03 10:45:00 -07002672 }
2673 state->mCommand = FastMixerState::MIX_WRITE;
2674 sq->end();
2675 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002676 if (kUseFastMixer == FastMixer_Dynamic) {
2677 mNormalSink = mPipeSink;
2678 }
Glenn Kasten58912562012-04-03 10:45:00 -07002679 } else {
2680 sq->end(false /*didModify*/);
2681 }
2682 }
2683 PlaybackThread::threadLoop_write();
2684}
2685
Glenn Kasten000f0e32012-03-01 17:10:56 -08002686// shared by MIXER and DIRECT, overridden by DUPLICATING
2687void AudioFlinger::PlaybackThread::threadLoop_write()
2688{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002689 // FIXME rewrite to reduce number of system calls
2690 mLastWriteTime = systemTime();
2691 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002692 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002693
Eric Laurent67c0a582012-05-01 19:31:12 -07002694 // If an NBAIO sink is present, use it to write the normal mixer's submix
2695 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002696#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002697 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002698#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002699 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002700#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002701 // update the setpoint when gScreenState changes
2702 uint32_t screenState = gScreenState;
2703 if (screenState != mScreenState) {
2704 mScreenState = screenState;
2705 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2706 if (pipe != NULL) {
2707 pipe->setAvgFrames((mScreenState & 1) ?
2708 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2709 }
2710 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002711 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002712#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002713 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002714#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002715 if (framesWritten > 0) {
2716 bytesWritten = framesWritten << mBitShift;
2717 } else {
2718 bytesWritten = framesWritten;
2719 }
2720 // otherwise use the HAL / AudioStreamOut directly
2721 } else {
2722 // Direct output thread.
2723 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002724 }
2725
Eric Laurent67c0a582012-05-01 19:31:12 -07002726 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002727 mNumWrites++;
2728 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002729}
2730
Glenn Kasten58912562012-04-03 10:45:00 -07002731void AudioFlinger::MixerThread::threadLoop_standby()
2732{
2733 // Idle the fast mixer if it's currently running
2734 if (mFastMixer != NULL) {
2735 FastMixerStateQueue *sq = mFastMixer->sq();
2736 FastMixerState *state = sq->begin();
2737 if (!(state->mCommand & FastMixerState::IDLE)) {
2738 state->mCommand = FastMixerState::COLD_IDLE;
2739 state->mColdFutexAddr = &mFastMixerFutex;
2740 state->mColdGen++;
2741 mFastMixerFutex = 0;
2742 sq->end();
2743 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2744 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002745 if (kUseFastMixer == FastMixer_Dynamic) {
2746 mNormalSink = mOutputSink;
2747 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002748 if (mAudioWatchdog != 0) {
2749 mAudioWatchdog->pause();
2750 }
Glenn Kasten58912562012-04-03 10:45:00 -07002751 } else {
2752 sq->end(false /*didModify*/);
2753 }
2754 }
2755 PlaybackThread::threadLoop_standby();
2756}
2757
Glenn Kasten000f0e32012-03-01 17:10:56 -08002758// shared by MIXER and DIRECT, overridden by DUPLICATING
2759void AudioFlinger::PlaybackThread::threadLoop_standby()
2760{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002761 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2762 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002763}
2764
2765void AudioFlinger::MixerThread::threadLoop_mix()
2766{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002767 // obtain the presentation timestamp of the next output buffer
2768 int64_t pts;
2769 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002770
Glenn Kasten952eeb22012-03-06 11:30:57 -08002771 if (NULL != mOutput->stream->get_next_write_timestamp) {
2772 status = mOutput->stream->get_next_write_timestamp(
2773 mOutput->stream, &pts);
2774 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002775
Glenn Kasten952eeb22012-03-06 11:30:57 -08002776 if (status != NO_ERROR) {
2777 pts = AudioBufferProvider::kInvalidPTS;
2778 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002779
Glenn Kasten952eeb22012-03-06 11:30:57 -08002780 // mix buffers...
2781 mAudioMixer->process(pts);
2782 // increase sleep time progressively when application underrun condition clears.
2783 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2784 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2785 // such that we would underrun the audio HAL.
2786 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2787 sleepTimeShift--;
2788 }
2789 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002790 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002791 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002792}
2793
2794void AudioFlinger::MixerThread::threadLoop_sleepTime()
2795{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002796 // If no tracks are ready, sleep once for the duration of an output
2797 // buffer size, then write 0s to the output
2798 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002799 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002800 sleepTime = activeSleepTime >> sleepTimeShift;
2801 if (sleepTime < kMinThreadSleepTimeUs) {
2802 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002803 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002804 // reduce sleep time in case of consecutive application underruns to avoid
2805 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2806 // duration we would end up writing less data than needed by the audio HAL if
2807 // the condition persists.
2808 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2809 sleepTimeShift++;
2810 }
2811 } else {
2812 sleepTime = idleSleepTime;
2813 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002814 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002815 memset (mMixBuffer, 0, mixBufferSize);
2816 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002817 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002818 }
2819 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002820}
2821
2822// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002823AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002824 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002825{
2826
Glenn Kasten29c23c32012-01-26 13:37:52 -08002827 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002828 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002829 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002830 size_t mixedTracks = 0;
2831 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002832 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002833 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002834 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002835
2836 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002837 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002838
Eric Laurent571d49c2010-08-11 05:20:11 -07002839 if (masterMute) {
2840 masterVolume = 0;
2841 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002842 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002843 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002844 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002845 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002846 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002847 masterVolume = (float)((v + (1 << 23)) >> 24);
2848 chain.clear();
2849 }
2850
Glenn Kasten288ed212012-04-25 17:52:27 -07002851 // prepare a new state to push
2852 FastMixerStateQueue *sq = NULL;
2853 FastMixerState *state = NULL;
2854 bool didModify = false;
2855 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2856 if (mFastMixer != NULL) {
2857 sq = mFastMixer->sq();
2858 state = sq->begin();
2859 }
2860
Mathias Agopian65ab4712010-07-14 17:59:35 -07002861 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002862 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002863 if (t == 0) continue;
2864
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002865 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002866 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002867
Glenn Kasten288ed212012-04-25 17:52:27 -07002868 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002869 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002870
2871 // It's theoretically possible (though unlikely) for a fast track to be created
2872 // and then removed within the same normal mix cycle. This is not a problem, as
2873 // the track never becomes active so it's fast mixer slot is never touched.
2874 // The converse, of removing an (active) track and then creating a new track
2875 // at the identical fast mixer slot within the same normal mix cycle,
2876 // is impossible because the slot isn't marked available until the end of each cycle.
2877 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002878 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2879 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002880 FastTrack *fastTrack = &state->mFastTracks[j];
2881
2882 // Determine whether the track is currently in underrun condition,
2883 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002884 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2885 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002886 uint32_t recentFull = (underruns.mBitFields.mFull -
2887 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2888 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2889 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2890 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2891 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2892 uint32_t recentUnderruns = recentPartial + recentEmpty;
2893 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002894 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002895 // or stopped which can occur when flush() is called while active
2896 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002897 track->mUnderrunCount += recentUnderruns;
2898 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002899
Glenn Kastend08f48c2012-05-01 18:14:02 -07002900 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002901 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002902 bool isActive = true;
2903 switch (track->mState) {
2904 case TrackBase::STOPPING_1:
2905 // track stays active in STOPPING_1 state until first underrun
2906 if (recentUnderruns > 0) {
2907 track->mState = TrackBase::STOPPING_2;
2908 }
2909 break;
2910 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002911 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002912 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002913 break;
2914 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002915 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002916 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002917 break;
2918 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002919 if (recentFull > 0 || recentPartial > 0) {
2920 // track has provided at least some frames recently: reset retry count
2921 track->mRetryCount = kMaxTrackRetries;
2922 }
2923 if (recentUnderruns == 0) {
2924 // no recent underruns: stay active
2925 break;
2926 }
2927 // there has recently been an underrun of some kind
2928 if (track->sharedBuffer() == 0) {
2929 // were any of the recent underruns "empty" (no frames available)?
2930 if (recentEmpty == 0) {
2931 // no, then ignore the partial underruns as they are allowed indefinitely
2932 break;
2933 }
2934 // there has recently been an "empty" underrun: decrement the retry counter
2935 if (--(track->mRetryCount) > 0) {
2936 break;
2937 }
2938 // indicate to client process that the track was disabled because of underrun;
2939 // it will then automatically call start() when data is available
2940 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2941 // remove from active list, but state remains ACTIVE [confusing but true]
2942 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002943 break;
2944 }
2945 // fall through
2946 case TrackBase::STOPPING_2:
2947 case TrackBase::PAUSED:
2948 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002949 case TrackBase::STOPPED:
2950 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07002951 // Check for presentation complete if track is inactive
2952 // We have consumed all the buffers of this track.
2953 // This would be incomplete if we auto-paused on underrun
2954 {
2955 size_t audioHALFrames =
2956 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2957 size_t framesWritten =
2958 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2959 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2960 // track stays in active list until presentation is complete
2961 break;
2962 }
2963 }
2964 if (track->isStopping_2()) {
2965 track->mState = TrackBase::STOPPED;
2966 }
2967 if (track->isStopped()) {
2968 // Can't reset directly, as fast mixer is still polling this track
2969 // track->reset();
2970 // So instead mark this track as needing to be reset after push with ack
2971 resetMask |= 1 << i;
2972 }
2973 isActive = false;
2974 break;
2975 case TrackBase::IDLE:
2976 default:
2977 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07002978 }
2979
2980 if (isActive) {
2981 // was it previously inactive?
2982 if (!(state->mTrackMask & (1 << j))) {
2983 ExtendedAudioBufferProvider *eabp = track;
2984 VolumeProvider *vp = track;
2985 fastTrack->mBufferProvider = eabp;
2986 fastTrack->mVolumeProvider = vp;
2987 fastTrack->mSampleRate = track->mSampleRate;
2988 fastTrack->mChannelMask = track->mChannelMask;
2989 fastTrack->mGeneration++;
2990 state->mTrackMask |= 1 << j;
2991 didModify = true;
2992 // no acknowledgement required for newly active tracks
2993 }
2994 // cache the combined master volume and stream type volume for fast mixer; this
2995 // lacks any synchronization or barrier so VolumeProvider may read a stale value
2996 track->mCachedVolume = track->isMuted() ?
2997 0 : masterVolume * mStreamTypes[track->streamType()].volume;
2998 ++fastTracks;
2999 } else {
3000 // was it previously active?
3001 if (state->mTrackMask & (1 << j)) {
3002 fastTrack->mBufferProvider = NULL;
3003 fastTrack->mGeneration++;
3004 state->mTrackMask &= ~(1 << j);
3005 didModify = true;
3006 // If any fast tracks were removed, we must wait for acknowledgement
3007 // because we're about to decrement the last sp<> on those tracks.
3008 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003009 } else {
3010 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003011 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003012 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003013 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003014 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003015 }
3016 continue;
3017 }
3018
3019 { // local variable scope to avoid goto warning
3020
Mathias Agopian65ab4712010-07-14 17:59:35 -07003021 audio_track_cblk_t* cblk = track->cblk();
3022
3023 // The first time a track is added we wait
3024 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003025 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003026 // make sure that we have enough frames to mix one full buffer.
3027 // enforce this condition only once to enable draining the buffer in case the client
3028 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003029 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003030 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003031 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003032 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003033 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003034 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003035 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003036 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003037 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003038 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003039 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003040 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003041 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3042 // the minimum track buffer size is normally twice the number of frames necessary
3043 // to fill one buffer and the resampler should not leave more than one buffer worth
3044 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003045 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003046 }
3047 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003048 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003049 !track->isPaused() && !track->isTerminated())
3050 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003051 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003052
3053 mixedTracks++;
3054
3055 // track->mainBuffer() != mMixBuffer means there is an effect chain
3056 // connected to the track
3057 chain.clear();
3058 if (track->mainBuffer() != mMixBuffer) {
3059 chain = getEffectChain_l(track->sessionId());
3060 // Delegate volume control to effect in track effect chain if needed
3061 if (chain != 0) {
3062 tracksWithEffect++;
3063 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003064 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003065 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003066 }
3067 }
3068
3069
3070 int param = AudioMixer::VOLUME;
3071 if (track->mFillingUpStatus == Track::FS_FILLED) {
3072 // no ramp for the first volume setting
3073 track->mFillingUpStatus = Track::FS_ACTIVE;
3074 if (track->mState == TrackBase::RESUMING) {
3075 track->mState = TrackBase::ACTIVE;
3076 param = AudioMixer::RAMP_VOLUME;
3077 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003078 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003079 } else if (cblk->server != 0) {
3080 // If the track is stopped before the first frame was mixed,
3081 // do not apply ramp
3082 param = AudioMixer::RAMP_VOLUME;
3083 }
3084
3085 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003086 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003087 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003088 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003089 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003090 if (track->isPausing()) {
3091 track->setPaused();
3092 }
3093 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003094
Mathias Agopian65ab4712010-07-14 17:59:35 -07003095 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003096 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003097 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003098 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003099 vl = vlr & 0xFFFF;
3100 vr = vlr >> 16;
3101 // track volumes come from shared memory, so can't be trusted and must be clamped
3102 if (vl > MAX_GAIN_INT) {
3103 ALOGV("Track left volume out of range: %04X", vl);
3104 vl = MAX_GAIN_INT;
3105 }
3106 if (vr > MAX_GAIN_INT) {
3107 ALOGV("Track right volume out of range: %04X", vr);
3108 vr = MAX_GAIN_INT;
3109 }
3110 // now apply the master volume and stream type volume
3111 vl = (uint32_t)(v * vl) << 12;
3112 vr = (uint32_t)(v * vr) << 12;
3113 // assuming master volume and stream type volume each go up to 1.0,
3114 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003115
Glenn Kasten05632a52012-01-03 14:22:33 -08003116 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3117 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003118 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003119 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003120 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003121 }
3122 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003123 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003124 // Delegate volume control to effect in track effect chain if needed
3125 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3126 // Do not ramp volume if volume is controlled by effect
3127 param = AudioMixer::VOLUME;
3128 track->mHasVolumeController = true;
3129 } else {
3130 // force no volume ramp when volume controller was just disabled or removed
3131 // from effect chain to avoid volume spike
3132 if (track->mHasVolumeController) {
3133 param = AudioMixer::VOLUME;
3134 }
3135 track->mHasVolumeController = false;
3136 }
3137
3138 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003139 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003140 vl = (vl + (1 << 11)) >> 12;
3141 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3142 vr = (vr + (1 << 11)) >> 12;
3143 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003144
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003145 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 -07003146
Mathias Agopian65ab4712010-07-14 17:59:35 -07003147 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003148 mAudioMixer->setBufferProvider(name, track);
3149 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003150
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003151 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3152 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3153 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003154 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003155 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003156 AudioMixer::TRACK,
3157 AudioMixer::FORMAT, (void *)track->format());
3158 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003159 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003160 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003161 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003162 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003163 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003164 AudioMixer::RESAMPLE,
3165 AudioMixer::SAMPLE_RATE,
3166 (void *)(cblk->sampleRate));
3167 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003168 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003169 AudioMixer::TRACK,
3170 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3171 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003172 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003173 AudioMixer::TRACK,
3174 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3175
3176 // reset retry count
3177 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003178
Eric Laurent27741442012-01-17 19:20:12 -08003179 // If one track is ready, set the mixer ready if:
3180 // - the mixer was not ready during previous round OR
3181 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003182 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003183 mixerStatus != MIXER_TRACKS_ENABLED) {
3184 mixerStatus = MIXER_TRACKS_READY;
3185 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003186 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003187 // clear effect chain input buffer if an active track underruns to avoid sending
3188 // previous audio buffer again to effects
3189 chain = getEffectChain_l(track->sessionId());
3190 if (chain != 0) {
3191 chain->clearInputBuffer();
3192 }
3193
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003194 //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 -07003195 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3196 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003197 // We have consumed all the buffers of this track.
3198 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003199 // TODO: use actual buffer filling status instead of latency when available from
3200 // audio HAL
3201 size_t audioHALFrames =
3202 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3203 size_t framesWritten =
3204 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3205 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003206 if (track->isStopped()) {
3207 track->reset();
3208 }
Eric Laurenta011e352012-03-29 15:51:43 -07003209 tracksToRemove->add(track);
3210 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003211 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003212 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003213 // No buffers for this track. Give it a few chances to
3214 // fill a buffer, then remove it from active list.
3215 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003216 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003217 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003218 // indicate to client process that the track was disabled because of underrun;
3219 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003220 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003221 // If one track is not ready, mark the mixer also not ready if:
3222 // - the mixer was ready during previous round OR
3223 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003224 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003225 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003226 mixerStatus = MIXER_TRACKS_ENABLED;
3227 }
3228 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003229 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003230 }
Glenn Kasten58912562012-04-03 10:45:00 -07003231
3232 } // local variable scope to avoid goto warning
3233track_is_ready: ;
3234
Mathias Agopian65ab4712010-07-14 17:59:35 -07003235 }
3236
Glenn Kasten288ed212012-04-25 17:52:27 -07003237 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003238 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003239 if (didModify) {
3240 state->mFastTracksGen++;
3241 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3242 if (kUseFastMixer == FastMixer_Dynamic &&
3243 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3244 state->mCommand = FastMixerState::COLD_IDLE;
3245 state->mColdFutexAddr = &mFastMixerFutex;
3246 state->mColdGen++;
3247 mFastMixerFutex = 0;
3248 if (kUseFastMixer == FastMixer_Dynamic) {
3249 mNormalSink = mOutputSink;
3250 }
3251 // If we go into cold idle, need to wait for acknowledgement
3252 // so that fast mixer stops doing I/O.
3253 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003254 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003255 }
3256 sq->end();
3257 }
3258 if (sq != NULL) {
3259 sq->end(didModify);
3260 sq->push(block);
3261 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07003262 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3263 mAudioWatchdog->pause();
3264 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003265
3266 // Now perform the deferred reset on fast tracks that have stopped
3267 while (resetMask != 0) {
3268 size_t i = __builtin_ctz(resetMask);
3269 ALOG_ASSERT(i < count);
3270 resetMask &= ~(1 << i);
3271 sp<Track> t = mActiveTracks[i].promote();
3272 if (t == 0) continue;
3273 Track* track = t.get();
3274 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3275 track->reset();
3276 }
Glenn Kasten58912562012-04-03 10:45:00 -07003277
Mathias Agopian65ab4712010-07-14 17:59:35 -07003278 // remove all the tracks that need to be...
3279 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003280 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003281 for (size_t i=0 ; i<count ; i++) {
3282 const sp<Track>& track = tracksToRemove->itemAt(i);
3283 mActiveTracks.remove(track);
3284 if (track->mainBuffer() != mMixBuffer) {
3285 chain = getEffectChain_l(track->sessionId());
3286 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003287 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003288 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003289 }
3290 }
3291 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003292 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003293 }
3294 }
3295 }
3296
3297 // mix buffer must be cleared if all tracks are connected to an
3298 // effect chain as in this case the mixer will not write to
3299 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003300 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3301 // FIXME as a performance optimization, should remember previous zero status
3302 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003303 }
3304
Glenn Kasten58912562012-04-03 10:45:00 -07003305 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003306 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003307 if (fastTracks > 0) {
3308 mixerStatus = MIXER_TRACKS_READY;
3309 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003310 return mixerStatus;
3311}
3312
Glenn Kasten66fcab92012-02-24 14:59:21 -08003313/*
3314The derived values that are cached:
3315 - mixBufferSize from frame count * frame size
3316 - activeSleepTime from activeSleepTimeUs()
3317 - idleSleepTime from idleSleepTimeUs()
3318 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3319 - maxPeriod from frame count and sample rate (MIXER only)
3320
3321The parameters that affect these derived values are:
3322 - frame count
3323 - frame size
3324 - sample rate
3325 - device type: A2DP or not
3326 - device latency
3327 - format: PCM or not
3328 - active sleep time
3329 - idle sleep time
3330*/
3331
3332void AudioFlinger::PlaybackThread::cacheParameters_l()
3333{
Glenn Kasten58912562012-04-03 10:45:00 -07003334 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003335 activeSleepTime = activeSleepTimeUs();
3336 idleSleepTime = idleSleepTimeUs();
3337}
3338
Eric Laurent22167852012-06-20 12:26:32 -07003339void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003340{
Steve Block3856b092011-10-20 11:56:00 +01003341 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003342 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003343 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003344
Mathias Agopian65ab4712010-07-14 17:59:35 -07003345 size_t size = mTracks.size();
3346 for (size_t i = 0; i < size; i++) {
3347 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003348 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003349 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003350 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003351 }
3352 }
3353}
3354
Mathias Agopian65ab4712010-07-14 17:59:35 -07003355// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003356int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003357{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003358 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003359}
3360
3361// deleteTrackName_l() must be called with ThreadBase::mLock held
3362void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3363{
Steve Block3856b092011-10-20 11:56:00 +01003364 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003365 mAudioMixer->deleteTrackName(name);
3366}
3367
3368// checkForNewParameters_l() must be called with ThreadBase::mLock held
3369bool AudioFlinger::MixerThread::checkForNewParameters_l()
3370{
Glenn Kasten58912562012-04-03 10:45:00 -07003371 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3372 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003373 bool reconfig = false;
3374
3375 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003376
3377 if (mFastMixer != NULL) {
3378 FastMixerStateQueue *sq = mFastMixer->sq();
3379 FastMixerState *state = sq->begin();
3380 if (!(state->mCommand & FastMixerState::IDLE)) {
3381 previousCommand = state->mCommand;
3382 state->mCommand = FastMixerState::HOT_IDLE;
3383 sq->end();
3384 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3385 } else {
3386 sq->end(false /*didModify*/);
3387 }
3388 }
3389
Mathias Agopian65ab4712010-07-14 17:59:35 -07003390 status_t status = NO_ERROR;
3391 String8 keyValuePair = mNewParameters[0];
3392 AudioParameter param = AudioParameter(keyValuePair);
3393 int value;
3394
3395 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3396 reconfig = true;
3397 }
3398 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003399 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003400 status = BAD_VALUE;
3401 } else {
3402 reconfig = true;
3403 }
3404 }
3405 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003406 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003407 status = BAD_VALUE;
3408 } else {
3409 reconfig = true;
3410 }
3411 }
3412 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3413 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003414 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003415 // if frame count is changed after track creation
3416 if (!mTracks.isEmpty()) {
3417 status = INVALID_OPERATION;
3418 } else {
3419 reconfig = true;
3420 }
3421 }
3422 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003423#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003424 // when changing the audio output device, call addBatteryData to notify
3425 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003426 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003427 uint32_t params = 0;
3428 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003429 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003430 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3431 }
3432
3433 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003434 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003435 // check if any other device (except speaker) is on
3436 if (value & deviceWithoutSpeaker ) {
3437 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3438 }
3439
3440 if (params != 0) {
3441 addBatteryData(params);
3442 }
3443 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003444#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003445
Mathias Agopian65ab4712010-07-14 17:59:35 -07003446 // forward device change to effects that have requested to be
3447 // aware of attached audio device.
Glenn Kasten94479fd2012-07-09 15:39:54 -07003448 mDevice = (audio_devices_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003449 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003450 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003451 }
3452 }
3453
3454 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003455 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 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003458 mOutput->stream->common.standby(&mOutput->stream->common);
3459 mStandby = true;
3460 mBytesWritten = 0;
3461 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003462 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003463 }
3464 if (status == NO_ERROR && reconfig) {
3465 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003466 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3467 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003468 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003469 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003470 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003471 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003472 if (name < 0) break;
3473 mTracks[i]->mName = name;
3474 // limit track sample rate to 2 x new output sample rate
3475 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3476 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3477 }
3478 }
3479 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3480 }
3481 }
3482
3483 mNewParameters.removeAt(0);
3484
3485 mParamStatus = status;
3486 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003487 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3488 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003489 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003490 }
Glenn Kasten58912562012-04-03 10:45:00 -07003491
3492 if (!(previousCommand & FastMixerState::IDLE)) {
3493 ALOG_ASSERT(mFastMixer != NULL);
3494 FastMixerStateQueue *sq = mFastMixer->sq();
3495 FastMixerState *state = sq->begin();
3496 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3497 state->mCommand = previousCommand;
3498 sq->end();
3499 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3500 }
3501
Mathias Agopian65ab4712010-07-14 17:59:35 -07003502 return reconfig;
3503}
3504
3505status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3506{
3507 const size_t SIZE = 256;
3508 char buffer[SIZE];
3509 String8 result;
3510
3511 PlaybackThread::dumpInternals(fd, args);
3512
3513 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3514 result.append(buffer);
3515 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003516
3517 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3518 FastMixerDumpState copy = mFastMixerDumpState;
3519 copy.dump(fd);
3520
Glenn Kasten39993082012-05-31 13:40:27 -07003521#ifdef STATE_QUEUE_DUMP
3522 // Similar for state queue
3523 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3524 observerCopy.dump(fd);
3525 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3526 mutatorCopy.dump(fd);
3527#endif
3528
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003529 // Write the tee output to a .wav file
3530 NBAIO_Source *teeSource = mTeeSource.get();
3531 if (teeSource != NULL) {
3532 char teePath[64];
3533 struct timeval tv;
3534 gettimeofday(&tv, NULL);
3535 struct tm tm;
3536 localtime_r(&tv.tv_sec, &tm);
3537 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3538 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3539 if (teeFd >= 0) {
3540 char wavHeader[44];
3541 memcpy(wavHeader,
3542 "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",
3543 sizeof(wavHeader));
3544 NBAIO_Format format = teeSource->format();
3545 unsigned channelCount = Format_channelCount(format);
3546 ALOG_ASSERT(channelCount <= FCC_2);
3547 unsigned sampleRate = Format_sampleRate(format);
3548 wavHeader[22] = channelCount; // number of channels
3549 wavHeader[24] = sampleRate; // sample rate
3550 wavHeader[25] = sampleRate >> 8;
3551 wavHeader[32] = channelCount * 2; // block alignment
3552 write(teeFd, wavHeader, sizeof(wavHeader));
3553 size_t total = 0;
3554 bool firstRead = true;
3555 for (;;) {
3556#define TEE_SINK_READ 1024
3557 short buffer[TEE_SINK_READ * FCC_2];
3558 size_t count = TEE_SINK_READ;
3559 ssize_t actual = teeSource->read(buffer, count);
3560 bool wasFirstRead = firstRead;
3561 firstRead = false;
3562 if (actual <= 0) {
3563 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3564 continue;
3565 }
3566 break;
3567 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003568 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003569 write(teeFd, buffer, actual * channelCount * sizeof(short));
3570 total += actual;
3571 }
3572 lseek(teeFd, (off_t) 4, SEEK_SET);
3573 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3574 write(teeFd, &temp, sizeof(temp));
3575 lseek(teeFd, (off_t) 40, SEEK_SET);
3576 temp = total * channelCount * sizeof(short);
3577 write(teeFd, &temp, sizeof(temp));
3578 close(teeFd);
3579 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3580 } else {
3581 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3582 }
3583 }
3584
Glenn Kastenc15d6652012-05-30 14:52:57 -07003585 if (mAudioWatchdog != 0) {
3586 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3587 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3588 wdCopy.dump(fd);
3589 }
3590
Mathias Agopian65ab4712010-07-14 17:59:35 -07003591 return NO_ERROR;
3592}
3593
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003594uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003595{
Glenn Kasten58912562012-04-03 10:45:00 -07003596 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003597}
3598
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003599uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003600{
Glenn Kasten58912562012-04-03 10:45:00 -07003601 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003602}
3603
Glenn Kasten66fcab92012-02-24 14:59:21 -08003604void AudioFlinger::MixerThread::cacheParameters_l()
3605{
3606 PlaybackThread::cacheParameters_l();
3607
3608 // FIXME: Relaxed timing because of a certain device that can't meet latency
3609 // Should be reduced to 2x after the vendor fixes the driver issue
3610 // increase threshold again due to low power audio mode. The way this warning
3611 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003612 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003613}
3614
Mathias Agopian65ab4712010-07-14 17:59:35 -07003615// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003616AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3617 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003618 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003619 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003620{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003621}
3622
3623AudioFlinger::DirectOutputThread::~DirectOutputThread()
3624{
3625}
3626
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003627AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3628 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003629)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003630{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003631 sp<Track> trackToRemove;
3632
Glenn Kastenfec279f2012-03-08 07:47:15 -08003633 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003634
Glenn Kasten952eeb22012-03-06 11:30:57 -08003635 // find out which tracks need to be processed
3636 if (mActiveTracks.size() != 0) {
3637 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003638 // The track died recently
3639 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003640
Glenn Kasten952eeb22012-03-06 11:30:57 -08003641 Track* const track = t.get();
3642 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003643
Glenn Kasten952eeb22012-03-06 11:30:57 -08003644 // The first time a track is added we wait
3645 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003646 uint32_t minFrames;
3647 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3648 minFrames = mNormalFrameCount;
3649 } else {
3650 minFrames = 1;
3651 }
3652 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003653 !track->isPaused() && !track->isTerminated())
3654 {
3655 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003656
Glenn Kasten952eeb22012-03-06 11:30:57 -08003657 if (track->mFillingUpStatus == Track::FS_FILLED) {
3658 track->mFillingUpStatus = Track::FS_ACTIVE;
3659 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003660 if (track->mState == TrackBase::RESUMING) {
3661 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003662 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003663 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003664
Glenn Kasten952eeb22012-03-06 11:30:57 -08003665 // compute volume for this track
3666 float left, right;
3667 if (track->isMuted() || mMasterMute || track->isPausing() ||
3668 mStreamTypes[track->streamType()].mute) {
3669 left = right = 0;
3670 if (track->isPausing()) {
3671 track->setPaused();
3672 }
3673 } else {
3674 float typeVolume = mStreamTypes[track->streamType()].volume;
3675 float v = mMasterVolume * typeVolume;
3676 uint32_t vlr = cblk->getVolumeLR();
3677 float v_clamped = v * (vlr & 0xFFFF);
3678 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3679 left = v_clamped/MAX_GAIN;
3680 v_clamped = v * (vlr >> 16);
3681 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3682 right = v_clamped/MAX_GAIN;
3683 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003684
Glenn Kasten952eeb22012-03-06 11:30:57 -08003685 if (left != mLeftVolFloat || right != mRightVolFloat) {
3686 mLeftVolFloat = left;
3687 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003688
Glenn Kasten952eeb22012-03-06 11:30:57 -08003689 // Convert volumes from float to 8.24
3690 uint32_t vl = (uint32_t)(left * (1 << 24));
3691 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003692
Glenn Kasten952eeb22012-03-06 11:30:57 -08003693 // Delegate volume control to effect in track effect chain if needed
3694 // only one effect chain can be present on DirectOutputThread, so if
3695 // there is one, the track is connected to it
3696 if (!mEffectChains.isEmpty()) {
3697 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003698 mEffectChains[0]->setVolume_l(&vl, &vr);
3699 left = (float)vl / (1 << 24);
3700 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003701 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003702 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003703 }
3704
3705 // reset retry count
3706 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003707 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003708 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003709 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003710 // clear effect chain input buffer if an active track underruns to avoid sending
3711 // previous audio buffer again to effects
3712 if (!mEffectChains.isEmpty()) {
3713 mEffectChains[0]->clearInputBuffer();
3714 }
3715
Glenn Kasten952eeb22012-03-06 11:30:57 -08003716 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurent67c0a582012-05-01 19:31:12 -07003717 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3718 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003719 // We have consumed all the buffers of this track.
3720 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003721 // TODO: implement behavior for compressed audio
3722 size_t audioHALFrames =
3723 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3724 size_t framesWritten =
3725 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3726 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003727 if (track->isStopped()) {
3728 track->reset();
3729 }
Eric Laurenta011e352012-03-29 15:51:43 -07003730 trackToRemove = track;
3731 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003732 } else {
3733 // No buffers for this track. Give it a few chances to
3734 // fill a buffer, then remove it from active list.
3735 if (--(track->mRetryCount) <= 0) {
3736 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3737 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003738 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003739 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003740 }
3741 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003742 }
3743 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003744
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003745 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003746 // remove all the tracks that need to be...
3747 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003748 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003749 mActiveTracks.remove(trackToRemove);
3750 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003751 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003752 trackToRemove->sessionId());
3753 mEffectChains[0]->decActiveTrackCnt();
3754 }
3755 if (trackToRemove->isTerminated()) {
3756 removeTrack_l(trackToRemove);
3757 }
3758 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003759
Glenn Kastenfec279f2012-03-08 07:47:15 -08003760 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003761}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003762
Glenn Kasten000f0e32012-03-01 17:10:56 -08003763void AudioFlinger::DirectOutputThread::threadLoop_mix()
3764{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003765 AudioBufferProvider::Buffer buffer;
3766 size_t frameCount = mFrameCount;
3767 int8_t *curBuf = (int8_t *)mMixBuffer;
3768 // output audio to hardware
3769 while (frameCount) {
3770 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003771 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003772 if (CC_UNLIKELY(buffer.raw == NULL)) {
3773 memset(curBuf, 0, frameCount * mFrameSize);
3774 break;
3775 }
3776 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3777 frameCount -= buffer.frameCount;
3778 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003779 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003780 }
3781 sleepTime = 0;
3782 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003783 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003784
Glenn Kasten000f0e32012-03-01 17:10:56 -08003785}
3786
3787void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3788{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003789 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003790 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003791 sleepTime = activeSleepTime;
3792 } else {
3793 sleepTime = idleSleepTime;
3794 }
3795 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003796 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003797 sleepTime = 0;
3798 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003799}
3800
3801// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003802int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003803{
3804 return 0;
3805}
3806
3807// deleteTrackName_l() must be called with ThreadBase::mLock held
3808void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3809{
3810}
3811
3812// checkForNewParameters_l() must be called with ThreadBase::mLock held
3813bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3814{
3815 bool reconfig = false;
3816
3817 while (!mNewParameters.isEmpty()) {
3818 status_t status = NO_ERROR;
3819 String8 keyValuePair = mNewParameters[0];
3820 AudioParameter param = AudioParameter(keyValuePair);
3821 int value;
3822
3823 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3824 // do not accept frame count changes if tracks are open as the track buffer
3825 // size depends on frame count and correct behavior would not be garantied
3826 // if frame count is changed after track creation
3827 if (!mTracks.isEmpty()) {
3828 status = INVALID_OPERATION;
3829 } else {
3830 reconfig = true;
3831 }
3832 }
3833 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003834 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 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003837 mOutput->stream->common.standby(&mOutput->stream->common);
3838 mStandby = true;
3839 mBytesWritten = 0;
3840 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003841 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003842 }
3843 if (status == NO_ERROR && reconfig) {
3844 readOutputParameters();
3845 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3846 }
3847 }
3848
3849 mNewParameters.removeAt(0);
3850
3851 mParamStatus = status;
3852 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003853 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3854 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003855 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003856 }
3857 return reconfig;
3858}
3859
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003860uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003861{
3862 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003863 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003864 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003865 } else {
3866 time = 10000;
3867 }
3868 return time;
3869}
3870
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003871uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003872{
3873 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003874 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003875 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003876 } else {
3877 time = 10000;
3878 }
3879 return time;
3880}
3881
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003882uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003883{
3884 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003885 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003886 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3887 } else {
3888 time = 10000;
3889 }
3890 return time;
3891}
3892
Glenn Kasten66fcab92012-02-24 14:59:21 -08003893void AudioFlinger::DirectOutputThread::cacheParameters_l()
3894{
3895 PlaybackThread::cacheParameters_l();
3896
3897 // use shorter standby delay as on normal output to release
3898 // hardware resources as soon as possible
3899 standbyDelay = microseconds(activeSleepTime*2);
3900}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003901
Mathias Agopian65ab4712010-07-14 17:59:35 -07003902// ----------------------------------------------------------------------------
3903
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003904AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003905 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003906 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3907 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003908{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003909 addOutputTrack(mainThread);
3910}
3911
3912AudioFlinger::DuplicatingThread::~DuplicatingThread()
3913{
3914 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3915 mOutputTracks[i]->destroy();
3916 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003917}
3918
Glenn Kasten000f0e32012-03-01 17:10:56 -08003919void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003920{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003921 // mix buffers...
3922 if (outputsReady(outputTracks)) {
3923 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3924 } else {
3925 memset(mMixBuffer, 0, mixBufferSize);
3926 }
3927 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003928 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003929 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003930}
3931
3932void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3933{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003934 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003935 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003936 sleepTime = activeSleepTime;
3937 } else {
3938 sleepTime = idleSleepTime;
3939 }
3940 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003941 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3942 writeFrames = mNormalFrameCount;
3943 memset(mMixBuffer, 0, mixBufferSize);
3944 } else {
3945 // flush remaining overflow buffers in output tracks
3946 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003947 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003948 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003949 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003950}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003951
Glenn Kasten000f0e32012-03-01 17:10:56 -08003952void AudioFlinger::DuplicatingThread::threadLoop_write()
3953{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003954 for (size_t i = 0; i < outputTracks.size(); i++) {
3955 outputTracks[i]->write(mMixBuffer, writeFrames);
3956 }
3957 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003958}
Glenn Kasten688a6402012-02-29 07:57:06 -08003959
Glenn Kasten000f0e32012-03-01 17:10:56 -08003960void AudioFlinger::DuplicatingThread::threadLoop_standby()
3961{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003962 // DuplicatingThread implements standby by stopping all tracks
3963 for (size_t i = 0; i < outputTracks.size(); i++) {
3964 outputTracks[i]->stop();
3965 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003966}
3967
Glenn Kastenfa26a852012-03-06 11:28:04 -08003968void AudioFlinger::DuplicatingThread::saveOutputTracks()
3969{
3970 outputTracks = mOutputTracks;
3971}
3972
3973void AudioFlinger::DuplicatingThread::clearOutputTracks()
3974{
3975 outputTracks.clear();
3976}
3977
Mathias Agopian65ab4712010-07-14 17:59:35 -07003978void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3979{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003980 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003981 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07003982 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003983 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003984 this,
3985 mSampleRate,
3986 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003987 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003988 frameCount);
3989 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003990 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003991 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003992 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003993 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003994 }
3995}
3996
3997void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3998{
3999 Mutex::Autolock _l(mLock);
4000 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004001 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004002 mOutputTracks[i]->destroy();
4003 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004004 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004005 return;
4006 }
4007 }
Steve Block3856b092011-10-20 11:56:00 +01004008 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004009}
4010
Glenn Kasten438b0362012-03-06 11:24:48 -08004011// caller must hold mLock
4012void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004013{
4014 mWaitTimeMs = UINT_MAX;
4015 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4016 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004017 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004018 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4019 if (waitTimeMs < mWaitTimeMs) {
4020 mWaitTimeMs = waitTimeMs;
4021 }
4022 }
4023 }
4024}
4025
4026
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004027bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004028{
4029 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004030 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004031 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004032 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004033 return false;
4034 }
4035 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004036 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004037 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004038 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004039 return false;
4040 }
4041 }
4042 return true;
4043}
4044
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004045uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004046{
4047 return (mWaitTimeMs * 1000) / 2;
4048}
4049
Glenn Kasten66fcab92012-02-24 14:59:21 -08004050void AudioFlinger::DuplicatingThread::cacheParameters_l()
4051{
4052 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4053 updateWaitTime_l();
4054
4055 MixerThread::cacheParameters_l();
4056}
4057
Mathias Agopian65ab4712010-07-14 17:59:35 -07004058// ----------------------------------------------------------------------------
4059
4060// TrackBase constructor must be called with AudioFlinger::mLock held
4061AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004062 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004063 const sp<Client>& client,
4064 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004065 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004066 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004067 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004068 const sp<IMemory>& sharedBuffer,
4069 int sessionId)
4070 : RefBase(),
4071 mThread(thread),
4072 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004073 mCblk(NULL),
4074 // mBuffer
4075 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004076 mFrameCount(0),
4077 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004078 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004079 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004080 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004081 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004082 // mChannelCount
4083 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004084{
Steve Block3856b092011-10-20 11:56:00 +01004085 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004086
Steve Blockb8a80522011-12-20 16:23:08 +00004087 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004088 size_t size = sizeof(audio_track_cblk_t);
4089 uint8_t channelCount = popcount(channelMask);
4090 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4091 if (sharedBuffer == 0) {
4092 size += bufferSize;
4093 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004094
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004095 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004096 mCblkMemory = client->heap()->allocate(size);
4097 if (mCblkMemory != 0) {
4098 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004099 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004100 new(mCblk) audio_track_cblk_t();
4101 // clear all buffers
4102 mCblk->frameCount = frameCount;
4103 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004104// uncomment the following lines to quickly test 32-bit wraparound
4105// mCblk->user = 0xffff0000;
4106// mCblk->server = 0xffff0000;
4107// mCblk->userBase = 0xffff0000;
4108// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004109 mChannelCount = channelCount;
4110 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004111 if (sharedBuffer == 0) {
4112 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4113 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4114 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004115 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004116 mCblk->flags = CBLK_UNDERRUN_ON;
4117 } else {
4118 mBuffer = sharedBuffer->pointer();
4119 }
4120 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4121 }
4122 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004123 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004124 client->heap()->dump("AudioTrack");
4125 return;
4126 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004127 } else {
4128 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004129 // construct the shared structure in-place.
4130 new(mCblk) audio_track_cblk_t();
4131 // clear all buffers
4132 mCblk->frameCount = frameCount;
4133 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004134// uncomment the following lines to quickly test 32-bit wraparound
4135// mCblk->user = 0xffff0000;
4136// mCblk->server = 0xffff0000;
4137// mCblk->userBase = 0xffff0000;
4138// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004139 mChannelCount = channelCount;
4140 mChannelMask = channelMask;
4141 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4142 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4143 // Force underrun condition to avoid false underrun callback until first data is
4144 // written to buffer (other flags are cleared)
4145 mCblk->flags = CBLK_UNDERRUN_ON;
4146 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004147 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004148}
4149
4150AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4151{
Glenn Kastena0d68332012-01-27 16:47:15 -08004152 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004153 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004154 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004155 } else {
4156 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004157 }
4158 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004159 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004160 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004161 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004162 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004163 // If the client's reference count drops to zero, the associated destructor
4164 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4165 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004166 mClient.clear();
4167 }
4168}
4169
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004170// AudioBufferProvider interface
4171// getNextBuffer() = 0;
4172// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004173void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4174{
Glenn Kastene0feee32011-12-13 11:53:26 -08004175 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004176 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004177 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004178 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004179 buffer->frameCount = 0;
4180}
4181
4182bool AudioFlinger::ThreadBase::TrackBase::step() {
4183 bool result;
4184 audio_track_cblk_t* cblk = this->cblk();
4185
4186 result = cblk->stepServer(mFrameCount);
4187 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004188 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004189 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004190 }
4191 return result;
4192}
4193
4194void AudioFlinger::ThreadBase::TrackBase::reset() {
4195 audio_track_cblk_t* cblk = this->cblk();
4196
4197 cblk->user = 0;
4198 cblk->server = 0;
4199 cblk->userBase = 0;
4200 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004201 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004202 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004203}
4204
Mathias Agopian65ab4712010-07-14 17:59:35 -07004205int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4206 return (int)mCblk->sampleRate;
4207}
4208
Mathias Agopian65ab4712010-07-14 17:59:35 -07004209void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4210 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004211 size_t frameSize = cblk->frameSize;
4212 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4213 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004214
4215 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004216 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4217 "TrackBase::getBuffer buffer out of range:\n"
4218 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4219 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004220 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004221 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004222
4223 return bufferStart;
4224}
4225
Eric Laurenta011e352012-03-29 15:51:43 -07004226status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4227{
4228 mSyncEvents.add(event);
4229 return NO_ERROR;
4230}
4231
Mathias Agopian65ab4712010-07-14 17:59:35 -07004232// ----------------------------------------------------------------------------
4233
4234// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4235AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004236 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004237 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004238 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004239 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004240 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004241 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004242 int frameCount,
4243 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004244 int sessionId,
4245 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004246 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004247 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004248 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004249 // mRetryCount initialized later when needed
4250 mSharedBuffer(sharedBuffer),
4251 mStreamType(streamType),
4252 mName(-1), // see note below
4253 mMainBuffer(thread->mixBuffer()),
4254 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004255 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004256 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004257 mFlags(flags),
4258 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004259 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004260 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004261{
4262 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004263 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4264 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004265 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004266 // to avoid leaking a track name, do not allocate one unless there is an mCblk
4267 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004268 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004269 if (mName < 0) {
4270 ALOGE("no more track names available");
4271 return;
4272 }
4273 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004274 if (flags & IAudioFlinger::TRACK_FAST) {
4275 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4276 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4277 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004278 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004279 // FIXME This is too eager. We allocate a fast track index before the
4280 // fast track becomes active. Since fast tracks are a scarce resource,
4281 // this means we are potentially denying other more important fast tracks from
4282 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004283 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004284 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004285 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004286 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004287 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004288 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004289 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004290 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004291}
4292
4293AudioFlinger::PlaybackThread::Track::~Track()
4294{
Steve Block3856b092011-10-20 11:56:00 +01004295 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004296 sp<ThreadBase> thread = mThread.promote();
4297 if (thread != 0) {
4298 Mutex::Autolock _l(thread->mLock);
4299 mState = TERMINATED;
4300 }
4301}
4302
4303void AudioFlinger::PlaybackThread::Track::destroy()
4304{
4305 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4306 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004307 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004308 // we must acquire a strong reference on this Track before locking mLock
4309 // here so that the destructor is called only when exiting this function.
4310 // On the other hand, as long as Track::destroy() is only called by
4311 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4312 // this Track with its member mTrack.
4313 sp<Track> keep(this);
4314 { // scope for mLock
4315 sp<ThreadBase> thread = mThread.promote();
4316 if (thread != 0) {
4317 if (!isOutputTrack()) {
4318 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004319 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004320
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004321#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004322 // to track the speaker usage
4323 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004324#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004325 }
4326 AudioSystem::releaseOutput(thread->id());
4327 }
4328 Mutex::Autolock _l(thread->mLock);
4329 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4330 playbackThread->destroyTrack_l(this);
4331 }
4332 }
4333}
4334
Glenn Kasten288ed212012-04-25 17:52:27 -07004335/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4336{
Glenn Kastene213c862012-04-25 13:46:15 -07004337 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 -07004338 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004339}
4340
Mathias Agopian65ab4712010-07-14 17:59:35 -07004341void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4342{
Glenn Kasten83d86532012-01-17 14:39:34 -08004343 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004344 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004345 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004346 } else {
4347 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4348 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004349 track_state state = mState;
4350 char stateChar;
4351 switch (state) {
4352 case IDLE:
4353 stateChar = 'I';
4354 break;
4355 case TERMINATED:
4356 stateChar = 'T';
4357 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004358 case STOPPING_1:
4359 stateChar = 's';
4360 break;
4361 case STOPPING_2:
4362 stateChar = '5';
4363 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004364 case STOPPED:
4365 stateChar = 'S';
4366 break;
4367 case RESUMING:
4368 stateChar = 'R';
4369 break;
4370 case ACTIVE:
4371 stateChar = 'A';
4372 break;
4373 case PAUSING:
4374 stateChar = 'p';
4375 break;
4376 case PAUSED:
4377 stateChar = 'P';
4378 break;
Eric Laurent29864602012-05-08 18:57:51 -07004379 case FLUSHED:
4380 stateChar = 'F';
4381 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004382 default:
4383 stateChar = '?';
4384 break;
4385 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004386 char nowInUnderrun;
4387 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4388 case UNDERRUN_FULL:
4389 nowInUnderrun = ' ';
4390 break;
4391 case UNDERRUN_PARTIAL:
4392 nowInUnderrun = '<';
4393 break;
4394 case UNDERRUN_EMPTY:
4395 nowInUnderrun = '*';
4396 break;
4397 default:
4398 nowInUnderrun = '?';
4399 break;
4400 }
Glenn Kastene213c862012-04-25 13:46:15 -07004401 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4402 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004403 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004404 mStreamType,
4405 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004406 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004407 mSessionId,
4408 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004409 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004410 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004411 mMute,
4412 mFillingUpStatus,
4413 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004414 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4415 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004416 mCblk->server,
4417 mCblk->user,
4418 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004419 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004420 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004421 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004422 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004423}
4424
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004425// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004426status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004427 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004428{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004429 audio_track_cblk_t* cblk = this->cblk();
4430 uint32_t framesReady;
4431 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004432
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004433 // Check if last stepServer failed, try to step now
4434 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004435 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4436 // Since the fast mixer is higher priority than client callback thread,
4437 // it does not result in priority inversion for client.
4438 // But a non-blocking solution would be preferable to avoid
4439 // fast mixer being unable to tryLock(), and
4440 // to avoid the extra context switches if the client wakes up,
4441 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004442 if (!step()) goto getNextBuffer_exit;
4443 ALOGV("stepServer recovered");
4444 mStepServerFailed = false;
4445 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004446
Glenn Kasten288ed212012-04-25 17:52:27 -07004447 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004448 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004449
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004450 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004451 uint32_t s = cblk->server;
4452 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4453
4454 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4455 if (framesReq > framesReady) {
4456 framesReq = framesReady;
4457 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004458 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004459 framesReq = bufferEnd - s;
4460 }
4461
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004462 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004463 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004464 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004465 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004466
4467getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004468 buffer->raw = NULL;
4469 buffer->frameCount = 0;
4470 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4471 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004472}
4473
Glenn Kasten288ed212012-04-25 17:52:27 -07004474// Note that framesReady() takes a mutex on the control block using tryLock().
4475// This could result in priority inversion if framesReady() is called by the normal mixer,
4476// as the normal mixer thread runs at lower
4477// priority than the client's callback thread: there is a short window within framesReady()
4478// during which the normal mixer could be preempted, and the client callback would block.
4479// Another problem can occur if framesReady() is called by the fast mixer:
4480// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4481// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4482size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004483 return mCblk->framesReady();
4484}
4485
Glenn Kasten288ed212012-04-25 17:52:27 -07004486// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004487bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004488 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004489
John Grossman4ff14ba2012-02-08 16:37:41 -08004490 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004491 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4492 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004493 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004494 return true;
4495 }
4496 return false;
4497}
4498
Glenn Kasten3acbd052012-02-28 10:39:56 -08004499status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004500 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004501{
4502 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004503 ALOGV("start(%d), calling pid %d session %d",
4504 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004505
Mathias Agopian65ab4712010-07-14 17:59:35 -07004506 sp<ThreadBase> thread = mThread.promote();
4507 if (thread != 0) {
4508 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004509 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004510 // here the track could be either new, or restarted
4511 // in both cases "unstop" the track
4512 if (mState == PAUSED) {
4513 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004514 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004515 } else {
4516 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004517 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004518 }
4519
4520 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4521 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004522 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004523 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004524
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004525#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004526 // to track the speaker usage
4527 if (status == NO_ERROR) {
4528 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4529 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004530#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004531 }
4532 if (status == NO_ERROR) {
4533 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4534 playbackThread->addTrack_l(this);
4535 } else {
4536 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004537 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004538 }
4539 } else {
4540 status = BAD_VALUE;
4541 }
4542 return status;
4543}
4544
4545void AudioFlinger::PlaybackThread::Track::stop()
4546{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004547 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004548 sp<ThreadBase> thread = mThread.promote();
4549 if (thread != 0) {
4550 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004551 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004552 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004553 // If the track is not active (PAUSED and buffers full), flush buffers
4554 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4555 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4556 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004557 mState = STOPPED;
4558 } else if (!isFastTrack()) {
4559 mState = STOPPED;
4560 } else {
4561 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4562 // and then to STOPPED and reset() when presentation is complete
4563 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004564 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004565 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004566 }
4567 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4568 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004569 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004570 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004571
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004572#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004573 // to track the speaker usage
4574 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004575#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004576 }
4577 }
4578}
4579
4580void AudioFlinger::PlaybackThread::Track::pause()
4581{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004582 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004583 sp<ThreadBase> thread = mThread.promote();
4584 if (thread != 0) {
4585 Mutex::Autolock _l(thread->mLock);
4586 if (mState == ACTIVE || mState == RESUMING) {
4587 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004588 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004589 if (!isOutputTrack()) {
4590 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004591 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004592 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004593
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004594#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004595 // to track the speaker usage
4596 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004597#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004598 }
4599 }
4600 }
4601}
4602
4603void AudioFlinger::PlaybackThread::Track::flush()
4604{
Steve Block3856b092011-10-20 11:56:00 +01004605 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004606 sp<ThreadBase> thread = mThread.promote();
4607 if (thread != 0) {
4608 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004609 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4610 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004611 return;
4612 }
4613 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004614 // FLUSHED state
4615 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004616 // do not reset the track if it is still in the process of being stopped or paused.
4617 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004618 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004619 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004620 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4621 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4622 reset();
4623 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004624 }
4625}
4626
4627void AudioFlinger::PlaybackThread::Track::reset()
4628{
4629 // Do not reset twice to avoid discarding data written just after a flush and before
4630 // the audioflinger thread detects the track is stopped.
4631 if (!mResetDone) {
4632 TrackBase::reset();
4633 // Force underrun condition to avoid false underrun callback until first data is
4634 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004635 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4636 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004637 mFillingUpStatus = FS_FILLING;
4638 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004639 if (mState == FLUSHED) {
4640 mState = IDLE;
4641 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004642 }
4643}
4644
4645void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4646{
4647 mMute = muted;
4648}
4649
Mathias Agopian65ab4712010-07-14 17:59:35 -07004650status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4651{
4652 status_t status = DEAD_OBJECT;
4653 sp<ThreadBase> thread = mThread.promote();
4654 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004655 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004656 sp<AudioFlinger> af = mClient->audioFlinger();
4657
4658 Mutex::Autolock _l(af->mLock);
4659
4660 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004661
Eric Laurent109347d2012-07-02 12:31:03 -07004662 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004663 Mutex::Autolock _dl(playbackThread->mLock);
4664 Mutex::Autolock _sl(srcThread->mLock);
4665 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4666 if (chain == 0) {
4667 return INVALID_OPERATION;
4668 }
4669
4670 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4671 if (effect == 0) {
4672 return INVALID_OPERATION;
4673 }
4674 srcThread->removeEffect_l(effect);
4675 playbackThread->addEffect_l(effect);
4676 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4677 if (effect->state() == EffectModule::ACTIVE ||
4678 effect->state() == EffectModule::STOPPING) {
4679 effect->start();
4680 }
4681
4682 sp<EffectChain> dstChain = effect->chain().promote();
4683 if (dstChain == 0) {
4684 srcThread->addEffect_l(effect);
4685 return INVALID_OPERATION;
4686 }
4687 AudioSystem::unregisterEffect(effect->id());
4688 AudioSystem::registerEffect(&effect->desc(),
4689 srcThread->id(),
4690 dstChain->strategy(),
4691 AUDIO_SESSION_OUTPUT_MIX,
4692 effect->id());
4693 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004694 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004695 }
4696 return status;
4697}
4698
4699void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4700{
4701 mAuxEffectId = EffectId;
4702 mAuxBuffer = buffer;
4703}
4704
Eric Laurenta011e352012-03-29 15:51:43 -07004705bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4706 size_t audioHalFrames)
4707{
4708 // a track is considered presented when the total number of frames written to audio HAL
4709 // corresponds to the number of frames written when presentationComplete() is called for the
4710 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4711 if (mPresentationCompleteFrames == 0) {
4712 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4713 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4714 mPresentationCompleteFrames, audioHalFrames);
4715 }
4716 if (framesWritten >= mPresentationCompleteFrames) {
4717 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4718 mSessionId, framesWritten);
4719 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004720 return true;
4721 }
4722 return false;
4723}
4724
4725void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4726{
4727 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4728 if (mSyncEvents[i]->type() == type) {
4729 mSyncEvents[i]->trigger();
4730 mSyncEvents.removeAt(i);
4731 i--;
4732 }
4733 }
4734}
4735
Glenn Kasten58912562012-04-03 10:45:00 -07004736// implement VolumeBufferProvider interface
4737
4738uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4739{
4740 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4741 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4742 uint32_t vlr = mCblk->getVolumeLR();
4743 uint32_t vl = vlr & 0xFFFF;
4744 uint32_t vr = vlr >> 16;
4745 // track volumes come from shared memory, so can't be trusted and must be clamped
4746 if (vl > MAX_GAIN_INT) {
4747 vl = MAX_GAIN_INT;
4748 }
4749 if (vr > MAX_GAIN_INT) {
4750 vr = MAX_GAIN_INT;
4751 }
4752 // now apply the cached master volume and stream type volume;
4753 // this is trusted but lacks any synchronization or barrier so may be stale
4754 float v = mCachedVolume;
4755 vl *= v;
4756 vr *= v;
4757 // re-combine into U4.16
4758 vlr = (vr << 16) | (vl & 0xFFFF);
4759 // FIXME look at mute, pause, and stop flags
4760 return vlr;
4761}
Eric Laurenta011e352012-03-29 15:51:43 -07004762
Eric Laurent29864602012-05-08 18:57:51 -07004763status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4764{
4765 if (mState == TERMINATED || mState == PAUSED ||
4766 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4767 (mState == STOPPED)))) {
4768 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4769 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4770 event->cancel();
4771 return INVALID_OPERATION;
4772 }
4773 TrackBase::setSyncEvent(event);
4774 return NO_ERROR;
4775}
4776
John Grossman4ff14ba2012-02-08 16:37:41 -08004777// timed audio tracks
4778
4779sp<AudioFlinger::PlaybackThread::TimedTrack>
4780AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004781 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004782 const sp<Client>& client,
4783 audio_stream_type_t streamType,
4784 uint32_t sampleRate,
4785 audio_format_t format,
4786 uint32_t channelMask,
4787 int frameCount,
4788 const sp<IMemory>& sharedBuffer,
4789 int sessionId) {
4790 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004791 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004792
Glenn Kastena0356762012-03-19 10:38:51 -07004793 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004794 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4795 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004796}
4797
4798AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004799 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004800 const sp<Client>& client,
4801 audio_stream_type_t streamType,
4802 uint32_t sampleRate,
4803 audio_format_t format,
4804 uint32_t channelMask,
4805 int frameCount,
4806 const sp<IMemory>& sharedBuffer,
4807 int sessionId)
4808 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004809 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004810 mQueueHeadInFlight(false),
4811 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004812 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004813 mTimedSilenceBuffer(NULL),
4814 mTimedSilenceBufferSize(0),
4815 mTimedAudioOutputOnTime(false),
4816 mMediaTimeTransformValid(false)
4817{
4818 LocalClock lc;
4819 mLocalTimeFreq = lc.getLocalFreq();
4820
4821 mLocalTimeToSampleTransform.a_zero = 0;
4822 mLocalTimeToSampleTransform.b_zero = 0;
4823 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4824 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4825 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4826 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004827
4828 mMediaTimeToSampleTransform.a_zero = 0;
4829 mMediaTimeToSampleTransform.b_zero = 0;
4830 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4831 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4832 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4833 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004834}
4835
4836AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4837 mClient->releaseTimedTrack();
4838 delete [] mTimedSilenceBuffer;
4839}
4840
4841status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4842 size_t size, sp<IMemory>* buffer) {
4843
4844 Mutex::Autolock _l(mTimedBufferQueueLock);
4845
4846 trimTimedBufferQueue_l();
4847
4848 // lazily initialize the shared memory heap for timed buffers
4849 if (mTimedMemoryDealer == NULL) {
4850 const int kTimedBufferHeapSize = 512 << 10;
4851
4852 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4853 "AudioFlingerTimed");
4854 if (mTimedMemoryDealer == NULL)
4855 return NO_MEMORY;
4856 }
4857
4858 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4859 if (newBuffer == NULL) {
4860 newBuffer = mTimedMemoryDealer->allocate(size);
4861 if (newBuffer == NULL)
4862 return NO_MEMORY;
4863 }
4864
4865 *buffer = newBuffer;
4866 return NO_ERROR;
4867}
4868
4869// caller must hold mTimedBufferQueueLock
4870void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4871 int64_t mediaTimeNow;
4872 {
4873 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4874 if (!mMediaTimeTransformValid)
4875 return;
4876
4877 int64_t targetTimeNow;
4878 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4879 ? mCCHelper.getCommonTime(&targetTimeNow)
4880 : mCCHelper.getLocalTime(&targetTimeNow);
4881
4882 if (OK != res)
4883 return;
4884
4885 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4886 &mediaTimeNow)) {
4887 return;
4888 }
4889 }
4890
John Grossman1c345192012-03-27 14:00:17 -07004891 size_t trimEnd;
4892 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004893 int64_t bufEnd;
4894
John Grossmanc95cfbb2012-04-12 11:53:11 -07004895 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4896 // We have a next buffer. Just use its PTS as the PTS of the frame
4897 // following the last frame in this buffer. If the stream is sparse
4898 // (ie, there are deliberate gaps left in the stream which should be
4899 // filled with silence by the TimedAudioTrack), then this can result
4900 // in one extra buffer being left un-trimmed when it could have
4901 // been. In general, this is not typical, and we would rather
4902 // optimized away the TS calculation below for the more common case
4903 // where PTSes are contiguous.
4904 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4905 } else {
4906 // We have no next buffer. Compute the PTS of the frame following
4907 // the last frame in this buffer by computing the duration of of
4908 // this frame in media time units and adding it to the PTS of the
4909 // buffer.
4910 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4911 / mCblk->frameSize;
4912
4913 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4914 &bufEnd)) {
4915 ALOGE("Failed to convert frame count of %lld to media time"
4916 " duration" " (scale factor %d/%u) in %s",
4917 frameCount,
4918 mMediaTimeToSampleTransform.a_to_b_numer,
4919 mMediaTimeToSampleTransform.a_to_b_denom,
4920 __PRETTY_FUNCTION__);
4921 break;
4922 }
4923 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004924 }
John Grossman9fbdee12012-03-26 17:51:46 -07004925
4926 if (bufEnd > mediaTimeNow)
4927 break;
4928
4929 // Is the buffer we want to use in the middle of a mix operation right
4930 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4931 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004932 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004933 mTrimQueueHeadOnRelease = true;
4934 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004935 }
4936
John Grossman9fbdee12012-03-26 17:51:46 -07004937 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004938 if (trimStart < trimEnd) {
4939 // Update the bookkeeping for framesReady()
4940 for (size_t i = trimStart; i < trimEnd; ++i) {
4941 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4942 }
4943
4944 // Now actually remove the buffers from the queue.
4945 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004946 }
4947}
4948
John Grossman1c345192012-03-27 14:00:17 -07004949void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4950 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004951 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4952 "%s called (reason \"%s\"), but timed buffer queue has no"
4953 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004954
4955 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4956 mTimedBufferQueue.removeAt(0);
4957}
4958
4959void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4960 const TimedBuffer& buf,
4961 const char* logTag) {
4962 uint32_t bufBytes = buf.buffer()->size();
4963 uint32_t consumedAlready = buf.position();
4964
Eric Laurentb388e532012-04-14 13:32:48 -07004965 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004966 "Bad bookkeeping while updating frames pending. Timed buffer is"
4967 " only %u bytes long, but claims to have consumed %u"
4968 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004969 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004970
4971 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004972 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4973 "Bad bookkeeping while updating frames pending. Should have at"
4974 " least %u queued frames, but we think we have only %u. (update"
4975 " reason: \"%s\")",
4976 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004977
4978 mFramesPendingInQueue -= bufFrames;
4979}
4980
John Grossman4ff14ba2012-02-08 16:37:41 -08004981status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4982 const sp<IMemory>& buffer, int64_t pts) {
4983
4984 {
4985 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4986 if (!mMediaTimeTransformValid)
4987 return INVALID_OPERATION;
4988 }
4989
4990 Mutex::Autolock _l(mTimedBufferQueueLock);
4991
John Grossman1c345192012-03-27 14:00:17 -07004992 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4993 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004994 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4995
4996 return NO_ERROR;
4997}
4998
4999status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5000 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5001
John Grossman1c345192012-03-27 14:00:17 -07005002 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5003 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5004 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005005
5006 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5007 target == TimedAudioTrack::COMMON_TIME)) {
5008 return BAD_VALUE;
5009 }
5010
5011 Mutex::Autolock lock(mMediaTimeTransformLock);
5012 mMediaTimeTransform = xform;
5013 mMediaTimeTransformTarget = target;
5014 mMediaTimeTransformValid = true;
5015
5016 return NO_ERROR;
5017}
5018
5019#define min(a, b) ((a) < (b) ? (a) : (b))
5020
5021// implementation of getNextBuffer for tracks whose buffers have timestamps
5022status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5023 AudioBufferProvider::Buffer* buffer, int64_t pts)
5024{
5025 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005026 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005027 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005028 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005029 return INVALID_OPERATION;
5030 }
5031
John Grossman4ff14ba2012-02-08 16:37:41 -08005032 Mutex::Autolock _l(mTimedBufferQueueLock);
5033
John Grossman9fbdee12012-03-26 17:51:46 -07005034 ALOG_ASSERT(!mQueueHeadInFlight,
5035 "getNextBuffer called without releaseBuffer!");
5036
John Grossman4ff14ba2012-02-08 16:37:41 -08005037 while (true) {
5038
5039 // if we have no timed buffers, then fail
5040 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005041 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005042 buffer->frameCount = 0;
5043 return NOT_ENOUGH_DATA;
5044 }
5045
5046 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5047
5048 // calculate the PTS of the head of the timed buffer queue expressed in
5049 // local time
5050 int64_t headLocalPTS;
5051 {
5052 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5053
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005054 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005055
5056 if (mMediaTimeTransform.a_to_b_denom == 0) {
5057 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005058 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005059 return NO_ERROR;
5060 }
5061
5062 int64_t transformedPTS;
5063 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5064 &transformedPTS)) {
5065 // the transform failed. this shouldn't happen, but if it does
5066 // then just drop this buffer
5067 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005068 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005069 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005070 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005071 return NO_ERROR;
5072 }
5073
5074 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5075 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5076 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005077 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005078 buffer->frameCount = 0;
5079 return INVALID_OPERATION;
5080 }
5081 } else {
5082 headLocalPTS = transformedPTS;
5083 }
5084 }
5085
5086 // adjust the head buffer's PTS to reflect the portion of the head buffer
5087 // that has already been consumed
5088 int64_t effectivePTS = headLocalPTS +
5089 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5090
5091 // Calculate the delta in samples between the head of the input buffer
5092 // queue and the start of the next output buffer that will be written.
5093 // If the transformation fails because of over or underflow, it means
5094 // that the sample's position in the output stream is so far out of
5095 // whack that it should just be dropped.
5096 int64_t sampleDelta;
5097 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5098 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005099 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5100 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005101 continue;
5102 }
5103 if (!mLocalTimeToSampleTransform.doForwardTransform(
5104 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005105 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005106 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005107 continue;
5108 }
5109
John Grossman1c345192012-03-27 14:00:17 -07005110 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5111 " sampleDelta=[%d.%08x]",
5112 head.pts(), head.position(), pts,
5113 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5114 + (sampleDelta >> 32)),
5115 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005116
5117 // if the delta between the ideal placement for the next input sample and
5118 // the current output position is within this threshold, then we will
5119 // concatenate the next input samples to the previous output
5120 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005121 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005122
5123 // if this is the first buffer of audio that we're emitting from this track
5124 // then it should be almost exactly on time.
5125 const int64_t kSampleStartupThreshold = 1LL << 32;
5126
5127 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005128 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005129 // the next input is close enough to being on time, so concatenate it
5130 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005131 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005132
John Grossman1c345192012-03-27 14:00:17 -07005133 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5134 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005135 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005136 }
5137
5138 // Looks like our output is not on time. Reset our on timed status.
5139 // Next time we mix samples from our input queue, then should be within
5140 // the StartupThreshold.
5141 mTimedAudioOutputOnTime = false;
5142 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005143 // the gap between the current output position and the proper start of
5144 // the next input sample is too big, so fill it with silence
5145 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5146
John Grossman9fbdee12012-03-26 17:51:46 -07005147 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005148 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5149 return NO_ERROR;
5150 } else {
5151 // the next input sample is late
5152 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5153 size_t onTimeSamplePosition =
5154 head.position() + lateFrames * mCblk->frameSize;
5155
5156 if (onTimeSamplePosition > head.buffer()->size()) {
5157 // all the remaining samples in the head are too late, so
5158 // drop it and move on
5159 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005160 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005161 continue;
5162 } else {
5163 // skip over the late samples
5164 head.setPosition(onTimeSamplePosition);
5165
5166 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005167 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005168
5169 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5170 return NO_ERROR;
5171 }
5172 }
5173 }
5174}
5175
5176// Yield samples from the timed buffer queue head up to the given output
5177// buffer's capacity.
5178//
5179// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005180void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005181 AudioBufferProvider::Buffer* buffer) {
5182
5183 const TimedBuffer& head = mTimedBufferQueue[0];
5184
5185 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5186 head.position());
5187
5188 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5189 mCblk->frameSize);
5190 size_t framesRequested = buffer->frameCount;
5191 buffer->frameCount = min(framesLeftInHead, framesRequested);
5192
John Grossman9fbdee12012-03-26 17:51:46 -07005193 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005194 mTimedAudioOutputOnTime = true;
5195}
5196
5197// Yield samples of silence up to the given output buffer's capacity
5198//
5199// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005200void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005201 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5202
5203 // lazily allocate a buffer filled with silence
5204 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5205 delete [] mTimedSilenceBuffer;
5206 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5207 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5208 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5209 }
5210
5211 buffer->raw = mTimedSilenceBuffer;
5212 size_t framesRequested = buffer->frameCount;
5213 buffer->frameCount = min(numFrames, framesRequested);
5214
5215 mTimedAudioOutputOnTime = false;
5216}
5217
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005218// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005219void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5220 AudioBufferProvider::Buffer* buffer) {
5221
5222 Mutex::Autolock _l(mTimedBufferQueueLock);
5223
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005224 // If the buffer which was just released is part of the buffer at the head
5225 // of the queue, be sure to update the amt of the buffer which has been
5226 // consumed. If the buffer being returned is not part of the head of the
5227 // queue, its either because the buffer is part of the silence buffer, or
5228 // because the head of the timed queue was trimmed after the mixer called
5229 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005230 if (buffer->raw == mTimedSilenceBuffer) {
5231 ALOG_ASSERT(!mQueueHeadInFlight,
5232 "Queue head in flight during release of silence buffer!");
5233 goto done;
5234 }
5235
5236 ALOG_ASSERT(mQueueHeadInFlight,
5237 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5238 " head in flight.");
5239
5240 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005241 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005242
5243 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005244 void* end = reinterpret_cast<void*>(
5245 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5246 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005247
John Grossman9fbdee12012-03-26 17:51:46 -07005248 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5249 "released buffer not within the head of the timed buffer"
5250 " queue; qHead = [%p, %p], released buffer = %p",
5251 start, end, buffer->raw);
5252
5253 head.setPosition(head.position() +
5254 (buffer->frameCount * mCblk->frameSize));
5255 mQueueHeadInFlight = false;
5256
John Grossman1c345192012-03-27 14:00:17 -07005257 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5258 "Bad bookkeeping during releaseBuffer! Should have at"
5259 " least %u queued frames, but we think we have only %u",
5260 buffer->frameCount, mFramesPendingInQueue);
5261
5262 mFramesPendingInQueue -= buffer->frameCount;
5263
John Grossman9fbdee12012-03-26 17:51:46 -07005264 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5265 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005266 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005267 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005268 }
John Grossman9fbdee12012-03-26 17:51:46 -07005269 } else {
5270 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5271 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005272 }
5273
John Grossman9fbdee12012-03-26 17:51:46 -07005274done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005275 buffer->raw = 0;
5276 buffer->frameCount = 0;
5277}
5278
Glenn Kasten288ed212012-04-25 17:52:27 -07005279size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005280 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005281 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005282}
5283
5284AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5285 : mPTS(0), mPosition(0) {}
5286
5287AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5288 const sp<IMemory>& buffer, int64_t pts)
5289 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5290
Mathias Agopian65ab4712010-07-14 17:59:35 -07005291// ----------------------------------------------------------------------------
5292
5293// RecordTrack constructor must be called with AudioFlinger::mLock held
5294AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005295 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005296 const sp<Client>& client,
5297 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005298 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005299 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005300 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005301 int sessionId)
5302 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005303 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005304 mOverflow(false)
5305{
5306 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005307 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5308 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5309 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5310 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5311 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5312 } else {
5313 mCblk->frameSize = sizeof(int8_t);
5314 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005315 }
5316}
5317
5318AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5319{
5320 sp<ThreadBase> thread = mThread.promote();
5321 if (thread != 0) {
5322 AudioSystem::releaseInput(thread->id());
5323 }
5324}
5325
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005326// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005327status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005328{
5329 audio_track_cblk_t* cblk = this->cblk();
5330 uint32_t framesAvail;
5331 uint32_t framesReq = buffer->frameCount;
5332
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005333 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005334 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005335 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005336 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005337 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005338 }
5339
5340 framesAvail = cblk->framesAvailable_l();
5341
Glenn Kastenf6b16782011-12-15 09:51:17 -08005342 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005343 uint32_t s = cblk->server;
5344 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5345
5346 if (framesReq > framesAvail) {
5347 framesReq = framesAvail;
5348 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005349 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005350 framesReq = bufferEnd - s;
5351 }
5352
5353 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005354 buffer->frameCount = framesReq;
5355 return NO_ERROR;
5356 }
5357
5358getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005359 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005360 buffer->frameCount = 0;
5361 return NOT_ENOUGH_DATA;
5362}
5363
Glenn Kasten3acbd052012-02-28 10:39:56 -08005364status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005365 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005366{
5367 sp<ThreadBase> thread = mThread.promote();
5368 if (thread != 0) {
5369 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005370 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005371 } else {
5372 return BAD_VALUE;
5373 }
5374}
5375
5376void AudioFlinger::RecordThread::RecordTrack::stop()
5377{
5378 sp<ThreadBase> thread = mThread.promote();
5379 if (thread != 0) {
5380 RecordThread *recordThread = (RecordThread *)thread.get();
5381 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005382 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005383 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005384 // read from buffer
5385 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005386 }
5387}
5388
5389void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5390{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005391 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005392 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005393 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005394 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005395 mSessionId,
5396 mFrameCount,
5397 mState,
5398 mCblk->sampleRate,
5399 mCblk->server,
5400 mCblk->user);
5401}
5402
5403
5404// ----------------------------------------------------------------------------
5405
5406AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005407 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005408 DuplicatingThread *sourceThread,
5409 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005410 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005411 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005412 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005413 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5414 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005415 mActive(false), mSourceThread(sourceThread)
5416{
5417
Mathias Agopian65ab4712010-07-14 17:59:35 -07005418 if (mCblk != NULL) {
5419 mCblk->flags |= CBLK_DIRECTION_OUT;
5420 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005421 mOutBuffer.frameCount = 0;
5422 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005423 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005424 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5425 mCblk, mBuffer, mCblk->buffers,
5426 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005427 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005428 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005429 }
5430}
5431
5432AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5433{
5434 clearBufferQueue();
5435}
5436
Glenn Kasten3acbd052012-02-28 10:39:56 -08005437status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005438 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005439{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005440 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005441 if (status != NO_ERROR) {
5442 return status;
5443 }
5444
5445 mActive = true;
5446 mRetryCount = 127;
5447 return status;
5448}
5449
5450void AudioFlinger::PlaybackThread::OutputTrack::stop()
5451{
5452 Track::stop();
5453 clearBufferQueue();
5454 mOutBuffer.frameCount = 0;
5455 mActive = false;
5456}
5457
5458bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5459{
5460 Buffer *pInBuffer;
5461 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005462 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005463 bool outputBufferFull = false;
5464 inBuffer.frameCount = frames;
5465 inBuffer.i16 = data;
5466
5467 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5468
5469 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005470 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005471 sp<ThreadBase> thread = mThread.promote();
5472 if (thread != 0) {
5473 MixerThread *mixerThread = (MixerThread *)thread.get();
5474 if (mCblk->frameCount > frames){
5475 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5476 uint32_t startFrames = (mCblk->frameCount - frames);
5477 pInBuffer = new Buffer;
5478 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5479 pInBuffer->frameCount = startFrames;
5480 pInBuffer->i16 = pInBuffer->mBuffer;
5481 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5482 mBufferQueue.add(pInBuffer);
5483 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005484 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005485 }
5486 }
5487 }
5488 }
5489
5490 while (waitTimeLeftMs) {
5491 // First write pending buffers, then new data
5492 if (mBufferQueue.size()) {
5493 pInBuffer = mBufferQueue.itemAt(0);
5494 } else {
5495 pInBuffer = &inBuffer;
5496 }
5497
5498 if (pInBuffer->frameCount == 0) {
5499 break;
5500 }
5501
5502 if (mOutBuffer.frameCount == 0) {
5503 mOutBuffer.frameCount = pInBuffer->frameCount;
5504 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005505 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005506 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005507 outputBufferFull = true;
5508 break;
5509 }
5510 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5511 if (waitTimeLeftMs >= waitTimeMs) {
5512 waitTimeLeftMs -= waitTimeMs;
5513 } else {
5514 waitTimeLeftMs = 0;
5515 }
5516 }
5517
5518 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5519 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5520 mCblk->stepUser(outFrames);
5521 pInBuffer->frameCount -= outFrames;
5522 pInBuffer->i16 += outFrames * channelCount;
5523 mOutBuffer.frameCount -= outFrames;
5524 mOutBuffer.i16 += outFrames * channelCount;
5525
5526 if (pInBuffer->frameCount == 0) {
5527 if (mBufferQueue.size()) {
5528 mBufferQueue.removeAt(0);
5529 delete [] pInBuffer->mBuffer;
5530 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005531 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005532 } else {
5533 break;
5534 }
5535 }
5536 }
5537
5538 // If we could not write all frames, allocate a buffer and queue it for next time.
5539 if (inBuffer.frameCount) {
5540 sp<ThreadBase> thread = mThread.promote();
5541 if (thread != 0 && !thread->standby()) {
5542 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5543 pInBuffer = new Buffer;
5544 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5545 pInBuffer->frameCount = inBuffer.frameCount;
5546 pInBuffer->i16 = pInBuffer->mBuffer;
5547 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5548 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005549 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005550 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005551 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005552 }
5553 }
5554 }
5555
5556 // Calling write() with a 0 length buffer, means that no more data will be written:
5557 // If no more buffers are pending, fill output track buffer to make sure it is started
5558 // by output mixer.
5559 if (frames == 0 && mBufferQueue.size() == 0) {
5560 if (mCblk->user < mCblk->frameCount) {
5561 frames = mCblk->frameCount - mCblk->user;
5562 pInBuffer = new Buffer;
5563 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5564 pInBuffer->frameCount = frames;
5565 pInBuffer->i16 = pInBuffer->mBuffer;
5566 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5567 mBufferQueue.add(pInBuffer);
5568 } else if (mActive) {
5569 stop();
5570 }
5571 }
5572
5573 return outputBufferFull;
5574}
5575
5576status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5577{
5578 int active;
5579 status_t result;
5580 audio_track_cblk_t* cblk = mCblk;
5581 uint32_t framesReq = buffer->frameCount;
5582
Steve Block3856b092011-10-20 11:56:00 +01005583// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005584 buffer->frameCount = 0;
5585
5586 uint32_t framesAvail = cblk->framesAvailable();
5587
5588
5589 if (framesAvail == 0) {
5590 Mutex::Autolock _l(cblk->lock);
5591 goto start_loop_here;
5592 while (framesAvail == 0) {
5593 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005594 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005595 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005596 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005597 }
5598 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5599 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005600 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005601 }
5602 // read the server count again
5603 start_loop_here:
5604 framesAvail = cblk->framesAvailable_l();
5605 }
5606 }
5607
5608// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005609// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005610// }
5611
5612 if (framesReq > framesAvail) {
5613 framesReq = framesAvail;
5614 }
5615
5616 uint32_t u = cblk->user;
5617 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5618
Marco Nelissena1472d92012-03-30 14:36:54 -07005619 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005620 framesReq = bufferEnd - u;
5621 }
5622
5623 buffer->frameCount = framesReq;
5624 buffer->raw = (void *)cblk->buffer(u);
5625 return NO_ERROR;
5626}
5627
5628
5629void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5630{
5631 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005632
5633 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005634 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005635 delete [] pBuffer->mBuffer;
5636 delete pBuffer;
5637 }
5638 mBufferQueue.clear();
5639}
5640
5641// ----------------------------------------------------------------------------
5642
5643AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5644 : RefBase(),
5645 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005646 // 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 -07005647 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005648 mPid(pid),
5649 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005650{
5651 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5652}
5653
5654// Client destructor must be called with AudioFlinger::mLock held
5655AudioFlinger::Client::~Client()
5656{
5657 mAudioFlinger->removeClient_l(mPid);
5658}
5659
Glenn Kasten435dbe62012-01-30 10:15:48 -08005660sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005661{
5662 return mMemoryDealer;
5663}
5664
John Grossman4ff14ba2012-02-08 16:37:41 -08005665// Reserve one of the limited slots for a timed audio track associated
5666// with this client
5667bool AudioFlinger::Client::reserveTimedTrack()
5668{
5669 const int kMaxTimedTracksPerClient = 4;
5670
5671 Mutex::Autolock _l(mTimedTrackLock);
5672
5673 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5674 ALOGW("can not create timed track - pid %d has exceeded the limit",
5675 mPid);
5676 return false;
5677 }
5678
5679 mTimedTrackCount++;
5680 return true;
5681}
5682
5683// Release a slot for a timed audio track
5684void AudioFlinger::Client::releaseTimedTrack()
5685{
5686 Mutex::Autolock _l(mTimedTrackLock);
5687 mTimedTrackCount--;
5688}
5689
Mathias Agopian65ab4712010-07-14 17:59:35 -07005690// ----------------------------------------------------------------------------
5691
5692AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5693 const sp<IAudioFlingerClient>& client,
5694 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005695 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005696{
5697}
5698
5699AudioFlinger::NotificationClient::~NotificationClient()
5700{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005701}
5702
5703void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5704{
5705 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005706 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005707}
5708
5709// ----------------------------------------------------------------------------
5710
5711AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5712 : BnAudioTrack(),
5713 mTrack(track)
5714{
5715}
5716
5717AudioFlinger::TrackHandle::~TrackHandle() {
5718 // just stop the track on deletion, associated resources
5719 // will be freed from the main thread once all pending buffers have
5720 // been played. Unless it's not in the active track list, in which
5721 // case we free everything now...
5722 mTrack->destroy();
5723}
5724
Glenn Kasten90716c52012-01-26 13:40:12 -08005725sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5726 return mTrack->getCblk();
5727}
5728
Glenn Kasten3acbd052012-02-28 10:39:56 -08005729status_t AudioFlinger::TrackHandle::start() {
5730 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005731}
5732
5733void AudioFlinger::TrackHandle::stop() {
5734 mTrack->stop();
5735}
5736
5737void AudioFlinger::TrackHandle::flush() {
5738 mTrack->flush();
5739}
5740
5741void AudioFlinger::TrackHandle::mute(bool e) {
5742 mTrack->mute(e);
5743}
5744
5745void AudioFlinger::TrackHandle::pause() {
5746 mTrack->pause();
5747}
5748
Mathias Agopian65ab4712010-07-14 17:59:35 -07005749status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5750{
5751 return mTrack->attachAuxEffect(EffectId);
5752}
5753
John Grossman4ff14ba2012-02-08 16:37:41 -08005754status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5755 sp<IMemory>* buffer) {
5756 if (!mTrack->isTimedTrack())
5757 return INVALID_OPERATION;
5758
5759 PlaybackThread::TimedTrack* tt =
5760 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5761 return tt->allocateTimedBuffer(size, buffer);
5762}
5763
5764status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5765 int64_t pts) {
5766 if (!mTrack->isTimedTrack())
5767 return INVALID_OPERATION;
5768
5769 PlaybackThread::TimedTrack* tt =
5770 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5771 return tt->queueTimedBuffer(buffer, pts);
5772}
5773
5774status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5775 const LinearTransform& xform, int target) {
5776
5777 if (!mTrack->isTimedTrack())
5778 return INVALID_OPERATION;
5779
5780 PlaybackThread::TimedTrack* tt =
5781 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5782 return tt->setMediaTimeTransform(
5783 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5784}
5785
Mathias Agopian65ab4712010-07-14 17:59:35 -07005786status_t AudioFlinger::TrackHandle::onTransact(
5787 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5788{
5789 return BnAudioTrack::onTransact(code, data, reply, flags);
5790}
5791
5792// ----------------------------------------------------------------------------
5793
5794sp<IAudioRecord> AudioFlinger::openRecord(
5795 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005796 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005797 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005798 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005799 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005800 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005801 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005802 int *sessionId,
5803 status_t *status)
5804{
5805 sp<RecordThread::RecordTrack> recordTrack;
5806 sp<RecordHandle> recordHandle;
5807 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005808 status_t lStatus;
5809 RecordThread *thread;
5810 size_t inFrameCount;
5811 int lSessionId;
5812
5813 // check calling permissions
5814 if (!recordingAllowed()) {
5815 lStatus = PERMISSION_DENIED;
5816 goto Exit;
5817 }
5818
5819 // add client to list
5820 { // scope for mLock
5821 Mutex::Autolock _l(mLock);
5822 thread = checkRecordThread_l(input);
5823 if (thread == NULL) {
5824 lStatus = BAD_VALUE;
5825 goto Exit;
5826 }
5827
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005828 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005829
5830 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005831 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005832 lSessionId = *sessionId;
5833 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005834 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005835 if (sessionId != NULL) {
5836 *sessionId = lSessionId;
5837 }
5838 }
5839 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005840 recordTrack = thread->createRecordTrack_l(client,
5841 sampleRate,
5842 format,
5843 channelMask,
5844 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005845 lSessionId,
5846 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005847 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005848 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005849 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5850 // destructor is called by the TrackBase destructor with mLock held
5851 client.clear();
5852 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005853 goto Exit;
5854 }
5855
5856 // return to handle to client
5857 recordHandle = new RecordHandle(recordTrack);
5858 lStatus = NO_ERROR;
5859
5860Exit:
5861 if (status) {
5862 *status = lStatus;
5863 }
5864 return recordHandle;
5865}
5866
5867// ----------------------------------------------------------------------------
5868
5869AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5870 : BnAudioRecord(),
5871 mRecordTrack(recordTrack)
5872{
5873}
5874
5875AudioFlinger::RecordHandle::~RecordHandle() {
5876 stop();
5877}
5878
Glenn Kasten90716c52012-01-26 13:40:12 -08005879sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5880 return mRecordTrack->getCblk();
5881}
5882
Glenn Kasten3acbd052012-02-28 10:39:56 -08005883status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005884 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005885 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005886}
5887
5888void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005889 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005890 mRecordTrack->stop();
5891}
5892
Mathias Agopian65ab4712010-07-14 17:59:35 -07005893status_t AudioFlinger::RecordHandle::onTransact(
5894 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5895{
5896 return BnAudioRecord::onTransact(code, data, reply, flags);
5897}
5898
5899// ----------------------------------------------------------------------------
5900
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005901AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5902 AudioStreamIn *input,
5903 uint32_t sampleRate,
5904 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005905 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005906 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005907 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005908 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5909 // mRsmpInIndex and mInputBytes set by readInputParameters()
5910 mReqChannelCount(popcount(channels)),
5911 mReqSampleRate(sampleRate)
5912 // mBytesRead is only meaningful while active, and so is cleared in start()
5913 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005914{
Glenn Kasten480b4682012-02-28 12:30:08 -08005915 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005916
Mathias Agopian65ab4712010-07-14 17:59:35 -07005917 readInputParameters();
5918}
5919
5920
5921AudioFlinger::RecordThread::~RecordThread()
5922{
5923 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005924 delete mResampler;
5925 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005926}
5927
5928void AudioFlinger::RecordThread::onFirstRef()
5929{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005930 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005931}
5932
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005933status_t AudioFlinger::RecordThread::readyToRun()
5934{
5935 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005936 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005937 return status;
5938}
5939
Mathias Agopian65ab4712010-07-14 17:59:35 -07005940bool AudioFlinger::RecordThread::threadLoop()
5941{
5942 AudioBufferProvider::Buffer buffer;
5943 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005944 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005945
Eric Laurent44d98482010-09-30 16:12:31 -07005946 nsecs_t lastWarning = 0;
5947
Eric Laurentfeb0db62011-07-22 09:04:31 -07005948 acquireWakeLock();
5949
Mathias Agopian65ab4712010-07-14 17:59:35 -07005950 // start recording
5951 while (!exitPending()) {
5952
5953 processConfigEvents();
5954
5955 { // scope for mLock
5956 Mutex::Autolock _l(mLock);
5957 checkForNewParameters_l();
5958 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5959 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005960 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005961 mStandby = true;
5962 }
5963
5964 if (exitPending()) break;
5965
Eric Laurentfeb0db62011-07-22 09:04:31 -07005966 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005967 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005968 // go to sleep
5969 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005970 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005971 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005972 continue;
5973 }
5974 if (mActiveTrack != 0) {
5975 if (mActiveTrack->mState == TrackBase::PAUSING) {
5976 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005977 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005978 mStandby = true;
5979 }
5980 mActiveTrack.clear();
5981 mStartStopCond.broadcast();
5982 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5983 if (mReqChannelCount != mActiveTrack->channelCount()) {
5984 mActiveTrack.clear();
5985 mStartStopCond.broadcast();
5986 } else if (mBytesRead != 0) {
5987 // record start succeeds only if first read from audio input
5988 // succeeds
5989 if (mBytesRead > 0) {
5990 mActiveTrack->mState = TrackBase::ACTIVE;
5991 } else {
5992 mActiveTrack.clear();
5993 }
5994 mStartStopCond.broadcast();
5995 }
5996 mStandby = false;
5997 }
5998 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005999 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006000 }
6001
6002 if (mActiveTrack != 0) {
6003 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6004 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006005 unlockEffectChains(effectChains);
6006 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006007 continue;
6008 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006009 for (size_t i = 0; i < effectChains.size(); i ++) {
6010 effectChains[i]->process_l();
6011 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006012
Mathias Agopian65ab4712010-07-14 17:59:35 -07006013 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006014 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006015 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006016 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006017 // no resampling
6018 while (framesOut) {
6019 size_t framesIn = mFrameCount - mRsmpInIndex;
6020 if (framesIn) {
6021 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6022 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6023 if (framesIn > framesOut)
6024 framesIn = framesOut;
6025 mRsmpInIndex += framesIn;
6026 framesOut -= framesIn;
6027 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006028 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006029 memcpy(dst, src, framesIn * mFrameSize);
6030 } else {
6031 int16_t *src16 = (int16_t *)src;
6032 int16_t *dst16 = (int16_t *)dst;
6033 if (mChannelCount == 1) {
6034 while (framesIn--) {
6035 *dst16++ = *src16;
6036 *dst16++ = *src16++;
6037 }
6038 } else {
6039 while (framesIn--) {
6040 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
6041 src16 += 2;
6042 }
6043 }
6044 }
6045 }
6046 if (framesOut && mFrameCount == mRsmpInIndex) {
6047 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006048 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006049 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006050 framesOut = 0;
6051 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006052 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006053 mRsmpInIndex = 0;
6054 }
6055 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006056 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006057 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6058 // Force input into standby so that it tries to
6059 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006060 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006061 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006062 }
6063 mRsmpInIndex = mFrameCount;
6064 framesOut = 0;
6065 buffer.frameCount = 0;
6066 }
6067 }
6068 }
6069 } else {
6070 // resampling
6071
6072 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6073 // alter output frame count as if we were expecting stereo samples
6074 if (mChannelCount == 1 && mReqChannelCount == 1) {
6075 framesOut >>= 1;
6076 }
6077 mResampler->resample(mRsmpOutBuffer, framesOut, this);
6078 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6079 // are 32 bit aligned which should be always true.
6080 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006081 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006082 // the resampler always outputs stereo samples: do post stereo to mono conversion
6083 int16_t *src = (int16_t *)mRsmpOutBuffer;
6084 int16_t *dst = buffer.i16;
6085 while (framesOut--) {
6086 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
6087 src += 2;
6088 }
6089 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006090 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006091 }
6092
6093 }
Eric Laurenta011e352012-03-29 15:51:43 -07006094 if (mFramestoDrop == 0) {
6095 mActiveTrack->releaseBuffer(&buffer);
6096 } else {
6097 if (mFramestoDrop > 0) {
6098 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006099 if (mFramestoDrop <= 0) {
6100 clearSyncStartEvent();
6101 }
6102 } else {
6103 mFramestoDrop += buffer.frameCount;
6104 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6105 mSyncStartEvent->isCancelled()) {
6106 ALOGW("Synced record %s, session %d, trigger session %d",
6107 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6108 mActiveTrack->sessionId(),
6109 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6110 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006111 }
6112 }
6113 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006114 mActiveTrack->overflow();
6115 }
6116 // client isn't retrieving buffers fast enough
6117 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006118 if (!mActiveTrack->setOverflow()) {
6119 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006120 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006121 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006122 lastWarning = now;
6123 }
6124 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006125 // Release the processor for a while before asking for a new buffer.
6126 // This will give the application more chance to read from the buffer and
6127 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006128 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006129 }
6130 }
Eric Laurentec437d82011-07-26 20:54:46 -07006131 // enable changes in effect chain
6132 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006133 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006134 }
6135
6136 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006137 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006138 }
6139 mActiveTrack.clear();
6140
6141 mStartStopCond.broadcast();
6142
Eric Laurentfeb0db62011-07-22 09:04:31 -07006143 releaseWakeLock();
6144
Steve Block3856b092011-10-20 11:56:00 +01006145 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006146 return false;
6147}
6148
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006149
6150sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6151 const sp<AudioFlinger::Client>& client,
6152 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006153 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006154 int channelMask,
6155 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006156 int sessionId,
6157 status_t *status)
6158{
6159 sp<RecordTrack> track;
6160 status_t lStatus;
6161
6162 lStatus = initCheck();
6163 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006164 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006165 goto Exit;
6166 }
6167
6168 { // scope for mLock
6169 Mutex::Autolock _l(mLock);
6170
6171 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006172 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006173
Glenn Kasten7378ca52012-01-20 13:44:40 -08006174 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006175 lStatus = NO_MEMORY;
6176 goto Exit;
6177 }
6178
6179 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006180 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6181 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006182 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006183 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6184 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006185 }
6186 lStatus = NO_ERROR;
6187
6188Exit:
6189 if (status) {
6190 *status = lStatus;
6191 }
6192 return track;
6193}
6194
Eric Laurenta011e352012-03-29 15:51:43 -07006195status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006196 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006197 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006198{
Glenn Kasten58912562012-04-03 10:45:00 -07006199 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006200 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006201 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006202
6203 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006204 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006205 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6206 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6207 triggerSession,
6208 recordTrack->sessionId(),
6209 syncStartEventCallback,
6210 this);
Eric Laurent29864602012-05-08 18:57:51 -07006211 // Sync event can be cancelled by the trigger session if the track is not in a
6212 // compatible state in which case we start record immediately
6213 if (mSyncStartEvent->isCancelled()) {
6214 clearSyncStartEvent();
6215 } else {
6216 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6217 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6218 }
Eric Laurenta011e352012-03-29 15:51:43 -07006219 }
6220
Mathias Agopian65ab4712010-07-14 17:59:35 -07006221 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006222 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006223 if (mActiveTrack != 0) {
6224 if (recordTrack != mActiveTrack.get()) {
6225 status = -EBUSY;
6226 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6227 mActiveTrack->mState = TrackBase::ACTIVE;
6228 }
6229 return status;
6230 }
6231
6232 recordTrack->mState = TrackBase::IDLE;
6233 mActiveTrack = recordTrack;
6234 mLock.unlock();
6235 status_t status = AudioSystem::startInput(mId);
6236 mLock.lock();
6237 if (status != NO_ERROR) {
6238 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006239 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006240 return status;
6241 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006242 mRsmpInIndex = mFrameCount;
6243 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006244 if (mResampler != NULL) {
6245 mResampler->reset();
6246 }
6247 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006248 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006249 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006250 mWaitWorkCV.signal();
6251 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006252 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006253 mActiveTrack.clear();
6254 status = INVALID_OPERATION;
6255 goto startError;
6256 }
6257 mStartStopCond.wait(mLock);
6258 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006259 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006260 status = BAD_VALUE;
6261 goto startError;
6262 }
Steve Block3856b092011-10-20 11:56:00 +01006263 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006264 return status;
6265 }
6266startError:
6267 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006268 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006269 return status;
6270}
6271
Eric Laurenta011e352012-03-29 15:51:43 -07006272void AudioFlinger::RecordThread::clearSyncStartEvent()
6273{
6274 if (mSyncStartEvent != 0) {
6275 mSyncStartEvent->cancel();
6276 }
6277 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006278 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006279}
6280
6281void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6282{
6283 sp<SyncEvent> strongEvent = event.promote();
6284
6285 if (strongEvent != 0) {
6286 RecordThread *me = (RecordThread *)strongEvent->cookie();
6287 me->handleSyncStartEvent(strongEvent);
6288 }
6289}
6290
6291void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6292{
Eric Laurent29864602012-05-08 18:57:51 -07006293 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006294 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6295 // from audio HAL
6296 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006297 }
6298}
6299
Mathias Agopian65ab4712010-07-14 17:59:35 -07006300void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006301 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006302 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006303 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006304 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006305 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6306 mActiveTrack->mState = TrackBase::PAUSING;
6307 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006308 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006309 return;
6310 }
6311 mStartStopCond.wait(mLock);
6312 // if we have been restarted, recordTrack == mActiveTrack.get() here
6313 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6314 mLock.unlock();
6315 AudioSystem::stopInput(mId);
6316 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006317 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006318 }
6319 }
6320 }
6321}
6322
Eric Laurenta011e352012-03-29 15:51:43 -07006323bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6324{
6325 return false;
6326}
6327
6328status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6329{
6330 if (!isValidSyncEvent(event)) {
6331 return BAD_VALUE;
6332 }
6333
6334 Mutex::Autolock _l(mLock);
6335
6336 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6337 mTrack->setSyncEvent(event);
6338 return NO_ERROR;
6339 }
6340 return NAME_NOT_FOUND;
6341}
6342
Mathias Agopian65ab4712010-07-14 17:59:35 -07006343status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6344{
6345 const size_t SIZE = 256;
6346 char buffer[SIZE];
6347 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006348
6349 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6350 result.append(buffer);
6351
6352 if (mActiveTrack != 0) {
6353 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006354 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006355 mActiveTrack->dump(buffer, SIZE);
6356 result.append(buffer);
6357
6358 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6359 result.append(buffer);
6360 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6361 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006362 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006363 result.append(buffer);
6364 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6365 result.append(buffer);
6366 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6367 result.append(buffer);
6368
6369
6370 } else {
6371 result.append("No record client\n");
6372 }
6373 write(fd, result.string(), result.size());
6374
6375 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006376 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006377
6378 return NO_ERROR;
6379}
6380
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006381// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006382status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006383{
6384 size_t framesReq = buffer->frameCount;
6385 size_t framesReady = mFrameCount - mRsmpInIndex;
6386 int channelCount;
6387
6388 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006389 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006390 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006391 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006392 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6393 // Force input into standby so that it tries to
6394 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006395 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006396 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006397 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006398 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006399 buffer->frameCount = 0;
6400 return NOT_ENOUGH_DATA;
6401 }
6402 mRsmpInIndex = 0;
6403 framesReady = mFrameCount;
6404 }
6405
6406 if (framesReq > framesReady) {
6407 framesReq = framesReady;
6408 }
6409
6410 if (mChannelCount == 1 && mReqChannelCount == 2) {
6411 channelCount = 1;
6412 } else {
6413 channelCount = 2;
6414 }
6415 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6416 buffer->frameCount = framesReq;
6417 return NO_ERROR;
6418}
6419
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006420// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006421void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6422{
6423 mRsmpInIndex += buffer->frameCount;
6424 buffer->frameCount = 0;
6425}
6426
6427bool AudioFlinger::RecordThread::checkForNewParameters_l()
6428{
6429 bool reconfig = false;
6430
6431 while (!mNewParameters.isEmpty()) {
6432 status_t status = NO_ERROR;
6433 String8 keyValuePair = mNewParameters[0];
6434 AudioParameter param = AudioParameter(keyValuePair);
6435 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006436 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006437 int reqSamplingRate = mReqSampleRate;
6438 int reqChannelCount = mReqChannelCount;
6439
6440 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6441 reqSamplingRate = value;
6442 reconfig = true;
6443 }
6444 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006445 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006446 reconfig = true;
6447 }
6448 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006449 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006450 reconfig = true;
6451 }
6452 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6453 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006454 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006455 // if frame count is changed after track creation
6456 if (mActiveTrack != 0) {
6457 status = INVALID_OPERATION;
6458 } else {
6459 reconfig = true;
6460 }
6461 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006462 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6463 // forward device change to effects that have requested to be
6464 // aware of attached audio device.
6465 for (size_t i = 0; i < mEffectChains.size(); i++) {
6466 mEffectChains[i]->setDevice_l(value);
6467 }
6468 // store input device and output device but do not forward output device to audio HAL.
6469 // Note that status is ignored by the caller for output device
6470 // (see AudioFlinger::setParameters()
Glenn Kasten94479fd2012-07-09 15:39:54 -07006471 uint32_t /*audio_devices_t*/ newDevice = mDevice;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006472 if (value & AUDIO_DEVICE_OUT_ALL) {
Glenn Kasten01542f22012-07-02 12:46:15 -07006473 newDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006474 status = BAD_VALUE;
6475 } else {
Glenn Kasten01542f22012-07-02 12:46:15 -07006476 newDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006477 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6478 if (mTrack != NULL) {
6479 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006480 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006481 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6482 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6483 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006484 }
Glenn Kasten01542f22012-07-02 12:46:15 -07006485 newDevice |= value;
Glenn Kasten94479fd2012-07-09 15:39:54 -07006486 mDevice = (audio_devices_t) newDevice; // since mDevice is read by other threads, only write to it once
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006487 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006488 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006489 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006490 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006491 mInput->stream->common.standby(&mInput->stream->common);
6492 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6493 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006494 }
6495 if (reconfig) {
6496 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006497 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006498 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006499 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006500 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6501 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006502 status = NO_ERROR;
6503 }
6504 if (status == NO_ERROR) {
6505 readInputParameters();
6506 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6507 }
6508 }
6509 }
6510
6511 mNewParameters.removeAt(0);
6512
6513 mParamStatus = status;
6514 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006515 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6516 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006517 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006518 }
6519 return reconfig;
6520}
6521
6522String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6523{
Dima Zavinfce7a472011-04-19 22:30:36 -07006524 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006525 String8 out_s8 = String8();
6526
6527 Mutex::Autolock _l(mLock);
6528 if (initCheck() != NO_ERROR) {
6529 return out_s8;
6530 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006531
Dima Zavin799a70e2011-04-18 16:57:27 -07006532 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006533 out_s8 = String8(s);
6534 free(s);
6535 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006536}
6537
6538void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6539 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006540 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006541
6542 switch (event) {
6543 case AudioSystem::INPUT_OPENED:
6544 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006545 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006546 desc.samplingRate = mSampleRate;
6547 desc.format = mFormat;
6548 desc.frameCount = mFrameCount;
6549 desc.latency = 0;
6550 param2 = &desc;
6551 break;
6552
6553 case AudioSystem::INPUT_CLOSED:
6554 default:
6555 break;
6556 }
6557 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6558}
6559
6560void AudioFlinger::RecordThread::readInputParameters()
6561{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006562 delete mRsmpInBuffer;
6563 // mRsmpInBuffer is always assigned a new[] below
6564 delete mRsmpOutBuffer;
6565 mRsmpOutBuffer = NULL;
6566 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006567 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006568
Dima Zavin799a70e2011-04-18 16:57:27 -07006569 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006570 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6571 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006572 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006573 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006574 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006575 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006576 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006577 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6578
Glenn Kasten53d76db2012-03-08 12:32:47 -08006579 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006580 {
6581 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006582 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6583 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006584 if (mChannelCount == 1 && mReqChannelCount == 2) {
6585 channelCount = 1;
6586 } else {
6587 channelCount = 2;
6588 }
6589 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6590 mResampler->setSampleRate(mSampleRate);
6591 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6592 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6593
6594 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6595 if (mChannelCount == 1 && mReqChannelCount == 1) {
6596 mFrameCount >>= 1;
6597 }
6598
6599 }
6600 mRsmpInIndex = mFrameCount;
6601}
6602
6603unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6604{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006605 Mutex::Autolock _l(mLock);
6606 if (initCheck() != NO_ERROR) {
6607 return 0;
6608 }
6609
Dima Zavin799a70e2011-04-18 16:57:27 -07006610 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006611}
6612
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006613uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6614{
6615 Mutex::Autolock _l(mLock);
6616 uint32_t result = 0;
6617 if (getEffectChain_l(sessionId) != 0) {
6618 result = EFFECT_SESSION;
6619 }
6620
6621 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6622 result |= TRACK_SESSION;
6623 }
6624
6625 return result;
6626}
6627
Eric Laurent59bd0da2011-08-01 09:52:20 -07006628AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6629{
6630 Mutex::Autolock _l(mLock);
6631 return mTrack;
6632}
6633
Glenn Kastenaed850d2012-01-26 09:46:34 -08006634AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006635{
6636 Mutex::Autolock _l(mLock);
6637 return mInput;
6638}
6639
6640AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6641{
6642 Mutex::Autolock _l(mLock);
6643 AudioStreamIn *input = mInput;
6644 mInput = NULL;
6645 return input;
6646}
6647
6648// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006649audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006650{
6651 if (mInput == NULL) {
6652 return NULL;
6653 }
6654 return &mInput->stream->common;
6655}
6656
6657
Mathias Agopian65ab4712010-07-14 17:59:35 -07006658// ----------------------------------------------------------------------------
6659
Eric Laurenta4c5a552012-03-29 10:12:40 -07006660audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6661{
6662 if (!settingsAllowed()) {
6663 return 0;
6664 }
6665 Mutex::Autolock _l(mLock);
6666 return loadHwModule_l(name);
6667}
6668
6669// loadHwModule_l() must be called with AudioFlinger::mLock held
6670audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6671{
6672 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6673 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6674 ALOGW("loadHwModule() module %s already loaded", name);
6675 return mAudioHwDevs.keyAt(i);
6676 }
6677 }
6678
Eric Laurenta4c5a552012-03-29 10:12:40 -07006679 audio_hw_device_t *dev;
6680
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006681 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006682 if (rc) {
6683 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6684 return 0;
6685 }
6686
6687 mHardwareStatus = AUDIO_HW_INIT;
6688 rc = dev->init_check(dev);
6689 mHardwareStatus = AUDIO_HW_IDLE;
6690 if (rc) {
6691 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6692 return 0;
6693 }
6694
6695 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6696 (NULL != dev->set_master_volume)) {
6697 AutoMutex lock(mHardwareLock);
6698 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6699 dev->set_master_volume(dev, mMasterVolume);
6700 mHardwareStatus = AUDIO_HW_IDLE;
6701 }
6702
6703 audio_module_handle_t handle = nextUniqueId();
6704 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6705
6706 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006707 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006708
6709 return handle;
6710
6711}
6712
6713audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6714 audio_devices_t *pDevices,
6715 uint32_t *pSamplingRate,
6716 audio_format_t *pFormat,
6717 audio_channel_mask_t *pChannelMask,
6718 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006719 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006720{
6721 status_t status;
6722 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006723 struct audio_config config = {
6724 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6725 channel_mask: pChannelMask ? *pChannelMask : 0,
6726 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6727 };
6728 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006729 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006730
Eric Laurenta4c5a552012-03-29 10:12:40 -07006731 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6732 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006733 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006734 config.sample_rate,
6735 config.format,
6736 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006737 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006738
6739 if (pDevices == NULL || *pDevices == 0) {
6740 return 0;
6741 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006742
Mathias Agopian65ab4712010-07-14 17:59:35 -07006743 Mutex::Autolock _l(mLock);
6744
Eric Laurenta4c5a552012-03-29 10:12:40 -07006745 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006746 if (outHwDev == NULL)
6747 return 0;
6748
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006749 audio_io_handle_t id = nextUniqueId();
6750
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006751 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006752
6753 status = outHwDev->open_output_stream(outHwDev,
6754 id,
6755 *pDevices,
6756 (audio_output_flags_t)flags,
6757 &config,
6758 &outStream);
6759
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006760 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006761 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006762 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006763 config.sample_rate,
6764 config.format,
6765 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006766 status);
6767
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006768 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006769 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006770
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006771 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006772 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6773 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006774 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006775 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006776 } else {
6777 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006778 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006779 }
6780 mPlaybackThreads.add(id, thread);
6781
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006782 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6783 if (pFormat != NULL) *pFormat = config.format;
6784 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006785 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006786
6787 // notify client processes of the new output creation
6788 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006789
6790 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006791 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006792 ALOGI("Using module %d has the primary audio interface", module);
6793 mPrimaryHardwareDev = outHwDev;
6794
6795 AutoMutex lock(mHardwareLock);
6796 mHardwareStatus = AUDIO_HW_SET_MODE;
6797 outHwDev->set_mode(outHwDev, mMode);
6798
6799 // Determine the level of master volume support the primary audio HAL has,
6800 // and set the initial master volume at the same time.
6801 float initialVolume = 1.0;
6802 mMasterVolumeSupportLvl = MVS_NONE;
6803
6804 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6805 if ((NULL != outHwDev->get_master_volume) &&
6806 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6807 mMasterVolumeSupportLvl = MVS_FULL;
6808 } else {
6809 mMasterVolumeSupportLvl = MVS_SETONLY;
6810 initialVolume = 1.0;
6811 }
6812
6813 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6814 if ((NULL == outHwDev->set_master_volume) ||
6815 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6816 mMasterVolumeSupportLvl = MVS_NONE;
6817 }
6818 // now that we have a primary device, initialize master volume on other devices
6819 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6820 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6821
6822 if ((dev != mPrimaryHardwareDev) &&
6823 (NULL != dev->set_master_volume)) {
6824 dev->set_master_volume(dev, initialVolume);
6825 }
6826 }
6827 mHardwareStatus = AUDIO_HW_IDLE;
6828 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6829 ? initialVolume
6830 : 1.0;
6831 mMasterVolume = initialVolume;
6832 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006833 return id;
6834 }
6835
6836 return 0;
6837}
6838
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006839audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6840 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006841{
6842 Mutex::Autolock _l(mLock);
6843 MixerThread *thread1 = checkMixerThread_l(output1);
6844 MixerThread *thread2 = checkMixerThread_l(output2);
6845
6846 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006847 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006848 return 0;
6849 }
6850
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006851 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006852 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6853 thread->addOutputTrack(thread2);
6854 mPlaybackThreads.add(id, thread);
6855 // notify client processes of the new output creation
6856 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6857 return id;
6858}
6859
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006860status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006861{
6862 // keep strong reference on the playback thread so that
6863 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006864 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006865 {
6866 Mutex::Autolock _l(mLock);
6867 thread = checkPlaybackThread_l(output);
6868 if (thread == NULL) {
6869 return BAD_VALUE;
6870 }
6871
Steve Block3856b092011-10-20 11:56:00 +01006872 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006873
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006874 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006875 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006876 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006877 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6878 dupThread->removeOutputTrack((MixerThread *)thread.get());
6879 }
6880 }
6881 }
Glenn Kastena1117922012-01-26 10:53:32 -08006882 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006883 mPlaybackThreads.removeItem(output);
6884 }
6885 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006886 // The thread entity (active unit of execution) is no longer running here,
6887 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006888
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006889 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006890 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006891 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006892 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006893 out->hwDev->close_output_stream(out->hwDev, out->stream);
6894 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006895 }
6896 return NO_ERROR;
6897}
6898
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006899status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006900{
6901 Mutex::Autolock _l(mLock);
6902 PlaybackThread *thread = checkPlaybackThread_l(output);
6903
6904 if (thread == NULL) {
6905 return BAD_VALUE;
6906 }
6907
Steve Block3856b092011-10-20 11:56:00 +01006908 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006909 thread->suspend();
6910
6911 return NO_ERROR;
6912}
6913
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006914status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006915{
6916 Mutex::Autolock _l(mLock);
6917 PlaybackThread *thread = checkPlaybackThread_l(output);
6918
6919 if (thread == NULL) {
6920 return BAD_VALUE;
6921 }
6922
Steve Block3856b092011-10-20 11:56:00 +01006923 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006924
6925 thread->restore();
6926
6927 return NO_ERROR;
6928}
6929
Eric Laurenta4c5a552012-03-29 10:12:40 -07006930audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6931 audio_devices_t *pDevices,
6932 uint32_t *pSamplingRate,
6933 audio_format_t *pFormat,
6934 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006935{
6936 status_t status;
6937 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006938 struct audio_config config = {
6939 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6940 channel_mask: pChannelMask ? *pChannelMask : 0,
6941 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6942 };
6943 uint32_t reqSamplingRate = config.sample_rate;
6944 audio_format_t reqFormat = config.format;
6945 audio_channel_mask_t reqChannels = config.channel_mask;
6946 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006947 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006948
6949 if (pDevices == NULL || *pDevices == 0) {
6950 return 0;
6951 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006952
Mathias Agopian65ab4712010-07-14 17:59:35 -07006953 Mutex::Autolock _l(mLock);
6954
Eric Laurenta4c5a552012-03-29 10:12:40 -07006955 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006956 if (inHwDev == NULL)
6957 return 0;
6958
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006959 audio_io_handle_t id = nextUniqueId();
6960
6961 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006962 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006963 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006964 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006965 config.sample_rate,
6966 config.format,
6967 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006968 status);
6969
6970 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6971 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6972 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006973 if (status == BAD_VALUE &&
6974 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6975 (config.sample_rate <= 2 * reqSamplingRate) &&
6976 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01006977 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006978 inStream = NULL;
6979 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006980 }
6981
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006982 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006983 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6984
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006985 // Start record thread
6986 // RecorThread require both input and output device indication to forward to audio
6987 // pre processing modules
6988 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6989 thread = new RecordThread(this,
6990 input,
6991 reqSamplingRate,
6992 reqChannels,
6993 id,
6994 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006995 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006996 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006997 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006998 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006999 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007000
Dima Zavin799a70e2011-04-18 16:57:27 -07007001 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007002
7003 // notify client processes of the new input creation
7004 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7005 return id;
7006 }
7007
7008 return 0;
7009}
7010
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007011status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007012{
7013 // keep strong reference on the record thread so that
7014 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007015 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007016 {
7017 Mutex::Autolock _l(mLock);
7018 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007019 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007020 return BAD_VALUE;
7021 }
7022
Steve Block3856b092011-10-20 11:56:00 +01007023 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007024 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007025 mRecordThreads.removeItem(input);
7026 }
7027 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007028 // The thread entity (active unit of execution) is no longer running here,
7029 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007030
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007031 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007032 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007033 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07007034 in->hwDev->close_input_stream(in->hwDev, in->stream);
7035 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007036
7037 return NO_ERROR;
7038}
7039
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007040status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007041{
7042 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007043 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007044
7045 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7046 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007047 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007048 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007049
7050 return NO_ERROR;
7051}
7052
7053
7054int AudioFlinger::newAudioSessionId()
7055{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007056 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007057}
7058
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007059void AudioFlinger::acquireAudioSessionId(int audioSession)
7060{
7061 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007062 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007063 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007064 size_t num = mAudioSessionRefs.size();
7065 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007066 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007067 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7068 ref->mCnt++;
7069 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007070 return;
7071 }
7072 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007073 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7074 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007075}
7076
7077void AudioFlinger::releaseAudioSessionId(int audioSession)
7078{
7079 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007080 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007081 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007082 size_t num = mAudioSessionRefs.size();
7083 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007084 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007085 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7086 ref->mCnt--;
7087 ALOGV(" decremented refcount to %d", ref->mCnt);
7088 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007089 mAudioSessionRefs.removeAt(i);
7090 delete ref;
7091 purgeStaleEffects_l();
7092 }
7093 return;
7094 }
7095 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007096 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007097}
7098
7099void AudioFlinger::purgeStaleEffects_l() {
7100
Steve Block3856b092011-10-20 11:56:00 +01007101 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007102
7103 Vector< sp<EffectChain> > chains;
7104
7105 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7106 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7107 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7108 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007109 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7110 chains.push(ec);
7111 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007112 }
7113 }
7114 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7115 sp<RecordThread> t = mRecordThreads.valueAt(i);
7116 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7117 sp<EffectChain> ec = t->mEffectChains[j];
7118 chains.push(ec);
7119 }
7120 }
7121
7122 for (size_t i = 0; i < chains.size(); i++) {
7123 sp<EffectChain> ec = chains[i];
7124 int sessionid = ec->sessionId();
7125 sp<ThreadBase> t = ec->mThread.promote();
7126 if (t == 0) {
7127 continue;
7128 }
7129 size_t numsessionrefs = mAudioSessionRefs.size();
7130 bool found = false;
7131 for (size_t k = 0; k < numsessionrefs; k++) {
7132 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007133 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007134 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007135 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007136 found = true;
7137 break;
7138 }
7139 }
7140 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007141 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007142 // remove all effects from the chain
7143 while (ec->mEffects.size()) {
7144 sp<EffectModule> effect = ec->mEffects[0];
7145 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007146 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007147 if (effect->purgeHandles()) {
7148 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007149 }
7150 AudioSystem::unregisterEffect(effect->id());
7151 }
7152 }
7153 }
7154 return;
7155}
7156
Mathias Agopian65ab4712010-07-14 17:59:35 -07007157// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007158AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007159{
Glenn Kastena1117922012-01-26 10:53:32 -08007160 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007161}
7162
7163// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007164AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007165{
7166 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007167 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007168}
7169
7170// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007171AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007172{
Glenn Kastena1117922012-01-26 10:53:32 -08007173 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007174}
7175
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007176uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007177{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007178 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007179}
7180
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007181AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007182{
7183 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7184 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007185 AudioStreamOut *output = thread->getOutput();
7186 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007187 return thread;
7188 }
7189 }
7190 return NULL;
7191}
7192
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007193uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007194{
7195 PlaybackThread *thread = primaryPlaybackThread_l();
7196
7197 if (thread == NULL) {
7198 return 0;
7199 }
7200
7201 return thread->device();
7202}
7203
Eric Laurenta011e352012-03-29 15:51:43 -07007204sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7205 int triggerSession,
7206 int listenerSession,
7207 sync_event_callback_t callBack,
7208 void *cookie)
7209{
7210 Mutex::Autolock _l(mLock);
7211
7212 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7213 status_t playStatus = NAME_NOT_FOUND;
7214 status_t recStatus = NAME_NOT_FOUND;
7215 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7216 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7217 if (playStatus == NO_ERROR) {
7218 return event;
7219 }
7220 }
7221 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7222 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7223 if (recStatus == NO_ERROR) {
7224 return event;
7225 }
7226 }
7227 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7228 mPendingSyncEvents.add(event);
7229 } else {
7230 ALOGV("createSyncEvent() invalid event %d", event->type());
7231 event.clear();
7232 }
7233 return event;
7234}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007235
Mathias Agopian65ab4712010-07-14 17:59:35 -07007236// ----------------------------------------------------------------------------
7237// Effect management
7238// ----------------------------------------------------------------------------
7239
7240
Glenn Kastenf587ba52012-01-26 16:25:10 -08007241status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007242{
7243 Mutex::Autolock _l(mLock);
7244 return EffectQueryNumberEffects(numEffects);
7245}
7246
Glenn Kastenf587ba52012-01-26 16:25:10 -08007247status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007248{
7249 Mutex::Autolock _l(mLock);
7250 return EffectQueryEffect(index, descriptor);
7251}
7252
Glenn Kasten5e92a782012-01-30 07:40:52 -08007253status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007254 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007255{
7256 Mutex::Autolock _l(mLock);
7257 return EffectGetDescriptor(pUuid, descriptor);
7258}
7259
7260
Mathias Agopian65ab4712010-07-14 17:59:35 -07007261sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7262 effect_descriptor_t *pDesc,
7263 const sp<IEffectClient>& effectClient,
7264 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007265 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007266 int sessionId,
7267 status_t *status,
7268 int *id,
7269 int *enabled)
7270{
7271 status_t lStatus = NO_ERROR;
7272 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007273 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007274
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007275 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007276 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007277
7278 if (pDesc == NULL) {
7279 lStatus = BAD_VALUE;
7280 goto Exit;
7281 }
7282
Eric Laurent84e9a102010-09-23 16:10:16 -07007283 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007284 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007285 lStatus = PERMISSION_DENIED;
7286 goto Exit;
7287 }
7288
Dima Zavinfce7a472011-04-19 22:30:36 -07007289 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007290 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007291 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007292 lStatus = PERMISSION_DENIED;
7293 goto Exit;
7294 }
7295
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007296 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007297 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007298 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007299 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007300 lStatus = BAD_VALUE;
7301 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007302 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007303 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007304 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007305 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007306 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007307 }
7308 }
7309
Mathias Agopian65ab4712010-07-14 17:59:35 -07007310 {
7311 Mutex::Autolock _l(mLock);
7312
Mathias Agopian65ab4712010-07-14 17:59:35 -07007313
7314 if (!EffectIsNullUuid(&pDesc->uuid)) {
7315 // if uuid is specified, request effect descriptor
7316 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7317 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007318 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007319 goto Exit;
7320 }
7321 } else {
7322 // if uuid is not specified, look for an available implementation
7323 // of the required type in effect factory
7324 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007325 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007326 lStatus = BAD_VALUE;
7327 goto Exit;
7328 }
7329 uint32_t numEffects = 0;
7330 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007331 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007332 bool found = false;
7333
7334 lStatus = EffectQueryNumberEffects(&numEffects);
7335 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007336 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007337 goto Exit;
7338 }
7339 for (uint32_t i = 0; i < numEffects; i++) {
7340 lStatus = EffectQueryEffect(i, &desc);
7341 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007342 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007343 continue;
7344 }
7345 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7346 // If matching type found save effect descriptor. If the session is
7347 // 0 and the effect is not auxiliary, continue enumeration in case
7348 // an auxiliary version of this effect type is available
7349 found = true;
7350 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07007351 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007352 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7353 break;
7354 }
7355 }
7356 }
7357 if (!found) {
7358 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007359 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007360 goto Exit;
7361 }
7362 // For same effect type, chose auxiliary version over insert version if
7363 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007364 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007365 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7366 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7367 }
7368 }
7369
7370 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007371 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007372 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7373 lStatus = INVALID_OPERATION;
7374 goto Exit;
7375 }
7376
Eric Laurent59255e42011-07-27 19:49:51 -07007377 // check recording permission for visualizer
7378 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7379 !recordingAllowed()) {
7380 lStatus = PERMISSION_DENIED;
7381 goto Exit;
7382 }
7383
Mathias Agopian65ab4712010-07-14 17:59:35 -07007384 // return effect descriptor
7385 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7386
7387 // If output is not specified try to find a matching audio session ID in one of the
7388 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007389 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7390 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007391 // Note: io is never 0 when creating an effect on an input
7392 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007393 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007394 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7395 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007396 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007397 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007398 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007399 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007400 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007401 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7402 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7403 io = mRecordThreads.keyAt(i);
7404 break;
7405 }
7406 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007407 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007408 // If no output thread contains the requested session ID, default to
7409 // first output. The effect chain will be moved to the correct output
7410 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007411 if (io == 0 && mPlaybackThreads.size()) {
7412 io = mPlaybackThreads.keyAt(0);
7413 }
Steve Block3856b092011-10-20 11:56:00 +01007414 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007415 }
7416 ThreadBase *thread = checkRecordThread_l(io);
7417 if (thread == NULL) {
7418 thread = checkPlaybackThread_l(io);
7419 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007420 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007421 lStatus = BAD_VALUE;
7422 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007423 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007424 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007425
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007426 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007427
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007428 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007429 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7430 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007431 if (handle != 0 && id != NULL) {
7432 *id = handle->id();
7433 }
7434 }
7435
7436Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007437 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007438 *status = lStatus;
7439 }
7440 return handle;
7441}
7442
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007443status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7444 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007445{
Steve Block3856b092011-10-20 11:56:00 +01007446 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007447 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007448 Mutex::Autolock _l(mLock);
7449 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007450 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007451 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007452 }
Eric Laurentde070132010-07-13 04:45:46 -07007453 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7454 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007455 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007456 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007457 }
Eric Laurentde070132010-07-13 04:45:46 -07007458 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7459 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007460 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007461 return BAD_VALUE;
7462 }
7463
7464 Mutex::Autolock _dl(dstThread->mLock);
7465 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007466 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007467
Mathias Agopian65ab4712010-07-14 17:59:35 -07007468 return NO_ERROR;
7469}
7470
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007471// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007472status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007473 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007474 AudioFlinger::PlaybackThread *dstThread,
7475 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007476{
Steve Block3856b092011-10-20 11:56:00 +01007477 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007478 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007479
Eric Laurent59255e42011-07-27 19:49:51 -07007480 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007481 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007482 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007483 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007484 return INVALID_OPERATION;
7485 }
7486
Eric Laurent39e94f82010-07-28 01:32:47 -07007487 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007488 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007489 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007490 // removed.
7491 srcThread->removeEffectChain_l(chain);
7492
7493 // transfer all effects one by one so that new effect chain is created on new thread with
7494 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007495 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007496 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007497 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007498 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7499 while (effect != 0) {
7500 srcThread->removeEffect_l(effect);
7501 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007502 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7503 if (effect->state() == EffectModule::ACTIVE ||
7504 effect->state() == EffectModule::STOPPING) {
7505 effect->start();
7506 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007507 // if the move request is not received from audio policy manager, the effect must be
7508 // re-registered with the new strategy and output
7509 if (dstChain == 0) {
7510 dstChain = effect->chain().promote();
7511 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007512 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007513 srcThread->addEffect_l(effect);
7514 return NO_INIT;
7515 }
7516 strategy = dstChain->strategy();
7517 }
7518 if (reRegister) {
7519 AudioSystem::unregisterEffect(effect->id());
7520 AudioSystem::registerEffect(&effect->desc(),
7521 dstOutput,
7522 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007523 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007524 effect->id());
7525 }
Eric Laurentde070132010-07-13 04:45:46 -07007526 effect = chain->getEffectFromId_l(0);
7527 }
7528
7529 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007530}
7531
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007532
Mathias Agopian65ab4712010-07-14 17:59:35 -07007533// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007534sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007535 const sp<AudioFlinger::Client>& client,
7536 const sp<IEffectClient>& effectClient,
7537 int32_t priority,
7538 int sessionId,
7539 effect_descriptor_t *desc,
7540 int *enabled,
7541 status_t *status
7542 )
7543{
7544 sp<EffectModule> effect;
7545 sp<EffectHandle> handle;
7546 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007547 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007548 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007549 bool effectCreated = false;
7550 bool effectRegistered = false;
7551
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007552 lStatus = initCheck();
7553 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007554 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007555 goto Exit;
7556 }
7557
7558 // Do not allow effects with session ID 0 on direct output or duplicating threads
7559 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007560 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007561 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007562 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007563 lStatus = BAD_VALUE;
7564 goto Exit;
7565 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007566 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007567 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007568 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007569 desc->name, desc->flags, mType);
7570 lStatus = BAD_VALUE;
7571 goto Exit;
7572 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007573
Steve Block3856b092011-10-20 11:56:00 +01007574 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007575
7576 { // scope for mLock
7577 Mutex::Autolock _l(mLock);
7578
7579 // check for existing effect chain with the requested audio session
7580 chain = getEffectChain_l(sessionId);
7581 if (chain == 0) {
7582 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007583 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007584 chain = new EffectChain(this, sessionId);
7585 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007586 chain->setStrategy(getStrategyForSession_l(sessionId));
7587 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007588 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007589 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007590 }
7591
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007592 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007593
7594 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007595 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007596 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007597 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007598 if (lStatus != NO_ERROR) {
7599 goto Exit;
7600 }
7601 effectRegistered = true;
7602 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007603 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007604 lStatus = effect->status();
7605 if (lStatus != NO_ERROR) {
7606 goto Exit;
7607 }
Eric Laurentcab11242010-07-15 12:50:15 -07007608 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007609 if (lStatus != NO_ERROR) {
7610 goto Exit;
7611 }
7612 effectCreated = true;
7613
7614 effect->setDevice(mDevice);
7615 effect->setMode(mAudioFlinger->getMode());
7616 }
7617 // create effect handle and connect it to effect module
7618 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007619 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007620 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007621 *enabled = (int)effect->isEnabled();
7622 }
7623 }
7624
7625Exit:
7626 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007627 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007628 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007629 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007630 }
7631 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007632 AudioSystem::unregisterEffect(effect->id());
7633 }
7634 if (chainCreated) {
7635 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007636 }
7637 handle.clear();
7638 }
7639
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007640 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007641 *status = lStatus;
7642 }
7643 return handle;
7644}
7645
Eric Laurent717e1282012-06-29 16:36:52 -07007646sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7647{
7648 Mutex::Autolock _l(mLock);
7649 return getEffect_l(sessionId, effectId);
7650}
7651
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007652sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7653{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007654 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007655 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007656}
7657
Eric Laurentde070132010-07-13 04:45:46 -07007658// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7659// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007660status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007661{
7662 // check for existing effect chain with the requested audio session
7663 int sessionId = effect->sessionId();
7664 sp<EffectChain> chain = getEffectChain_l(sessionId);
7665 bool chainCreated = false;
7666
7667 if (chain == 0) {
7668 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007669 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007670 chain = new EffectChain(this, sessionId);
7671 addEffectChain_l(chain);
7672 chain->setStrategy(getStrategyForSession_l(sessionId));
7673 chainCreated = true;
7674 }
Steve Block3856b092011-10-20 11:56:00 +01007675 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007676
7677 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007678 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007679 this, effect->desc().name, chain.get());
7680 return BAD_VALUE;
7681 }
7682
7683 status_t status = chain->addEffect_l(effect);
7684 if (status != NO_ERROR) {
7685 if (chainCreated) {
7686 removeEffectChain_l(chain);
7687 }
7688 return status;
7689 }
7690
7691 effect->setDevice(mDevice);
7692 effect->setMode(mAudioFlinger->getMode());
7693 return NO_ERROR;
7694}
7695
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007696void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007697
Steve Block3856b092011-10-20 11:56:00 +01007698 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007699 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007700 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7701 detachAuxEffect_l(effect->id());
7702 }
7703
7704 sp<EffectChain> chain = effect->chain().promote();
7705 if (chain != 0) {
7706 // remove effect chain if removing last effect
7707 if (chain->removeEffect_l(effect) == 0) {
7708 removeEffectChain_l(chain);
7709 }
7710 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007711 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007712 }
7713}
7714
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007715void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007716 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007717{
7718 effectChains = mEffectChains;
7719 for (size_t i = 0; i < mEffectChains.size(); i++) {
7720 mEffectChains[i]->lock();
7721 }
7722}
7723
7724void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007725 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007726{
7727 for (size_t i = 0; i < effectChains.size(); i++) {
7728 effectChains[i]->unlock();
7729 }
7730}
7731
7732sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7733{
7734 Mutex::Autolock _l(mLock);
7735 return getEffectChain_l(sessionId);
7736}
7737
7738sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7739{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007740 size_t size = mEffectChains.size();
7741 for (size_t i = 0; i < size; i++) {
7742 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007743 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007744 }
7745 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007746 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007747}
7748
Glenn Kastenf78aee72012-01-04 11:00:47 -08007749void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007750{
7751 Mutex::Autolock _l(mLock);
7752 size_t size = mEffectChains.size();
7753 for (size_t i = 0; i < size; i++) {
7754 mEffectChains[i]->setMode_l(mode);
7755 }
7756}
7757
7758void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007759 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007760 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007761
Mathias Agopian65ab4712010-07-14 17:59:35 -07007762 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007763 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007764 // delete the effect module if removing last handle on it
7765 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007766 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007767 removeEffect_l(effect);
7768 AudioSystem::unregisterEffect(effect->id());
7769 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007770 }
7771}
7772
7773status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7774{
7775 int session = chain->sessionId();
7776 int16_t *buffer = mMixBuffer;
7777 bool ownsBuffer = false;
7778
Steve Block3856b092011-10-20 11:56:00 +01007779 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007780 if (session > 0) {
7781 // Only one effect chain can be present in direct output thread and it uses
7782 // the mix buffer as input
7783 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007784 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007785 buffer = new int16_t[numSamples];
7786 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007787 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007788 ownsBuffer = true;
7789 }
7790
7791 // Attach all tracks with same session ID to this chain.
7792 for (size_t i = 0; i < mTracks.size(); ++i) {
7793 sp<Track> track = mTracks[i];
7794 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007795 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007796 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007797 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007798 }
7799 }
7800
7801 // indicate all active tracks in the chain
7802 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7803 sp<Track> track = mActiveTracks[i].promote();
7804 if (track == 0) continue;
7805 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007806 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007807 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007808 }
7809 }
7810 }
7811
7812 chain->setInBuffer(buffer, ownsBuffer);
7813 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007814 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007815 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007816 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7817 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007818 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007819 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7820 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007821 // Effect chain for other sessions are inserted at beginning of effect
7822 // chains list to be processed before output mix effects. Relative order between other
7823 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007824 size_t size = mEffectChains.size();
7825 size_t i = 0;
7826 for (i = 0; i < size; i++) {
7827 if (mEffectChains[i]->sessionId() < session) break;
7828 }
7829 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007830 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007831
7832 return NO_ERROR;
7833}
7834
7835size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7836{
7837 int session = chain->sessionId();
7838
Steve Block3856b092011-10-20 11:56:00 +01007839 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007840
7841 for (size_t i = 0; i < mEffectChains.size(); i++) {
7842 if (chain == mEffectChains[i]) {
7843 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007844 // detach all active tracks from the chain
7845 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7846 sp<Track> track = mActiveTracks[i].promote();
7847 if (track == 0) continue;
7848 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007849 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007850 chain.get(), session);
7851 chain->decActiveTrackCnt();
7852 }
7853 }
7854
Mathias Agopian65ab4712010-07-14 17:59:35 -07007855 // detach all tracks with same session ID from this chain
7856 for (size_t i = 0; i < mTracks.size(); ++i) {
7857 sp<Track> track = mTracks[i];
7858 if (session == track->sessionId()) {
7859 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007860 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007861 }
7862 }
Eric Laurentde070132010-07-13 04:45:46 -07007863 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007864 }
7865 }
7866 return mEffectChains.size();
7867}
7868
Eric Laurentde070132010-07-13 04:45:46 -07007869status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7870 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007871{
7872 Mutex::Autolock _l(mLock);
7873 return attachAuxEffect_l(track, EffectId);
7874}
7875
Eric Laurentde070132010-07-13 04:45:46 -07007876status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7877 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007878{
7879 status_t status = NO_ERROR;
7880
7881 if (EffectId == 0) {
7882 track->setAuxBuffer(0, NULL);
7883 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007884 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7885 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007886 if (effect != 0) {
7887 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7888 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7889 } else {
7890 status = INVALID_OPERATION;
7891 }
7892 } else {
7893 status = BAD_VALUE;
7894 }
7895 }
7896 return status;
7897}
7898
7899void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7900{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007901 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007902 sp<Track> track = mTracks[i];
7903 if (track->auxEffectId() == effectId) {
7904 attachAuxEffect_l(track, 0);
7905 }
7906 }
7907}
7908
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007909status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7910{
7911 // only one chain per input thread
7912 if (mEffectChains.size() != 0) {
7913 return INVALID_OPERATION;
7914 }
Steve Block3856b092011-10-20 11:56:00 +01007915 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007916
7917 chain->setInBuffer(NULL);
7918 chain->setOutBuffer(NULL);
7919
Eric Laurent59255e42011-07-27 19:49:51 -07007920 checkSuspendOnAddEffectChain_l(chain);
7921
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007922 mEffectChains.add(chain);
7923
7924 return NO_ERROR;
7925}
7926
7927size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7928{
Steve Block3856b092011-10-20 11:56:00 +01007929 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007930 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007931 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7932 chain.get(), mEffectChains.size(), this);
7933 if (mEffectChains.size() == 1) {
7934 mEffectChains.removeAt(0);
7935 }
7936 return 0;
7937}
7938
Mathias Agopian65ab4712010-07-14 17:59:35 -07007939// ----------------------------------------------------------------------------
7940// EffectModule implementation
7941// ----------------------------------------------------------------------------
7942
7943#undef LOG_TAG
7944#define LOG_TAG "AudioFlinger::EffectModule"
7945
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007946AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007947 const wp<AudioFlinger::EffectChain>& chain,
7948 effect_descriptor_t *desc,
7949 int id,
7950 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07007951 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
7952 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
7953 // mDescriptor is set below
7954 // mConfig is set by configure() and not used before then
7955 mEffectInterface(NULL),
7956 mStatus(NO_INIT), mState(IDLE),
7957 // mMaxDisableWaitCnt is set by configure() and not used before then
7958 // mDisableWaitCnt is set by process() and updateState() and not used before then
7959 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007960{
Steve Block3856b092011-10-20 11:56:00 +01007961 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007962 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007963 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007964 return;
7965 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007966
7967 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7968
7969 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007970 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007971
7972 if (mStatus != NO_ERROR) {
7973 return;
7974 }
7975 lStatus = init();
7976 if (lStatus < 0) {
7977 mStatus = lStatus;
7978 goto Error;
7979 }
7980
Steve Block3856b092011-10-20 11:56:00 +01007981 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007982 return;
7983Error:
7984 EffectRelease(mEffectInterface);
7985 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007986 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007987}
7988
7989AudioFlinger::EffectModule::~EffectModule()
7990{
Steve Block3856b092011-10-20 11:56:00 +01007991 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007992 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007993 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7994 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7995 sp<ThreadBase> thread = mThread.promote();
7996 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007997 audio_stream_t *stream = thread->stream();
7998 if (stream != NULL) {
7999 stream->remove_audio_effect(stream, mEffectInterface);
8000 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008001 }
8002 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008003 // release effect engine
8004 EffectRelease(mEffectInterface);
8005 }
8006}
8007
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008008status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008009{
8010 status_t status;
8011
8012 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008013 int priority = handle->priority();
8014 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008015 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008016 size_t i;
8017 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008018 EffectHandle *h = mHandles[i];
8019 if (h == NULL || h->destroyed_l()) continue;
8020 // first non destroyed handle is considered in control
8021 if (controlHandle == NULL)
8022 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008023 if (h->priority() <= priority) break;
8024 }
8025 // if inserted in first place, move effect control from previous owner to this handle
8026 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008027 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008028 if (controlHandle != NULL) {
8029 enabled = controlHandle->enabled();
8030 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008031 }
Eric Laurent59255e42011-07-27 19:49:51 -07008032 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008033 status = NO_ERROR;
8034 } else {
8035 status = ALREADY_EXISTS;
8036 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008037 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008038 mHandles.insertAt(handle, i);
8039 return status;
8040}
8041
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008042size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008043{
8044 Mutex::Autolock _l(mLock);
8045 size_t size = mHandles.size();
8046 size_t i;
8047 for (i = 0; i < size; i++) {
8048 if (mHandles[i] == handle) break;
8049 }
8050 if (i == size) {
8051 return size;
8052 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008053 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008054
Mathias Agopian65ab4712010-07-14 17:59:35 -07008055 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008056 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008057 if (i == 0) {
8058 EffectHandle *h = controlHandle_l();
8059 if (h != NULL) {
8060 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008061 }
8062 }
8063
Eric Laurentec437d82011-07-26 20:54:46 -07008064 // Prevent calls to process() and other functions on effect interface from now on.
8065 // The effect engine will be released by the destructor when the last strong reference on
8066 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008067 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008068 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008069 }
8070
Mathias Agopian65ab4712010-07-14 17:59:35 -07008071 return size;
8072}
8073
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008074// must be called with EffectModule::mLock held
8075AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008076{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008077 // the first valid handle in the list has control over the module
8078 for (size_t i = 0; i < mHandles.size(); i++) {
8079 EffectHandle *h = mHandles[i];
8080 if (h != NULL && !h->destroyed_l()) {
8081 return h;
8082 }
8083 }
8084
8085 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008086}
8087
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008088size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008089{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008090 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008091 // keep a strong reference on this EffectModule to avoid calling the
8092 // destructor before we exit
8093 sp<EffectModule> keep(this);
8094 {
8095 sp<ThreadBase> thread = mThread.promote();
8096 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008097 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008098 }
8099 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008100 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008101}
8102
8103void AudioFlinger::EffectModule::updateState() {
8104 Mutex::Autolock _l(mLock);
8105
8106 switch (mState) {
8107 case RESTART:
8108 reset_l();
8109 // FALL THROUGH
8110
8111 case STARTING:
8112 // clear auxiliary effect input buffer for next accumulation
8113 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8114 memset(mConfig.inputCfg.buffer.raw,
8115 0,
8116 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8117 }
8118 start_l();
8119 mState = ACTIVE;
8120 break;
8121 case STOPPING:
8122 stop_l();
8123 mDisableWaitCnt = mMaxDisableWaitCnt;
8124 mState = STOPPED;
8125 break;
8126 case STOPPED:
8127 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8128 // turn off sequence.
8129 if (--mDisableWaitCnt == 0) {
8130 reset_l();
8131 mState = IDLE;
8132 }
8133 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008134 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008135 break;
8136 }
8137}
8138
8139void AudioFlinger::EffectModule::process()
8140{
8141 Mutex::Autolock _l(mLock);
8142
Eric Laurentec437d82011-07-26 20:54:46 -07008143 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008144 mConfig.inputCfg.buffer.raw == NULL ||
8145 mConfig.outputCfg.buffer.raw == NULL) {
8146 return;
8147 }
8148
Eric Laurent8f45bd72010-08-31 13:50:07 -07008149 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008150 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8151 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008152 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008153 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008154 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008155 }
8156
8157 // do the actual processing in the effect engine
8158 int ret = (*mEffectInterface)->process(mEffectInterface,
8159 &mConfig.inputCfg.buffer,
8160 &mConfig.outputCfg.buffer);
8161
8162 // force transition to IDLE state when engine is ready
8163 if (mState == STOPPED && ret == -ENODATA) {
8164 mDisableWaitCnt = 1;
8165 }
8166
8167 // clear auxiliary effect input buffer for next accumulation
8168 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008169 memset(mConfig.inputCfg.buffer.raw, 0,
8170 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008171 }
8172 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008173 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8174 // If an insert effect is idle and input buffer is different from output buffer,
8175 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008176 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008177 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008178 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8179 int16_t *in = mConfig.inputCfg.buffer.s16;
8180 int16_t *out = mConfig.outputCfg.buffer.s16;
8181 for (size_t i = 0; i < frameCnt; i++) {
8182 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008183 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008184 }
8185 }
8186}
8187
8188void AudioFlinger::EffectModule::reset_l()
8189{
8190 if (mEffectInterface == NULL) {
8191 return;
8192 }
8193 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8194}
8195
8196status_t AudioFlinger::EffectModule::configure()
8197{
8198 uint32_t channels;
8199 if (mEffectInterface == NULL) {
8200 return NO_INIT;
8201 }
8202
8203 sp<ThreadBase> thread = mThread.promote();
8204 if (thread == 0) {
8205 return DEAD_OBJECT;
8206 }
8207
8208 // TODO: handle configuration of effects replacing track process
8209 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008210 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008211 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07008212 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008213 }
8214
8215 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008216 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008217 } else {
8218 mConfig.inputCfg.channels = channels;
8219 }
8220 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07008221 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8222 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008223 mConfig.inputCfg.samplingRate = thread->sampleRate();
8224 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8225 mConfig.inputCfg.bufferProvider.cookie = NULL;
8226 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8227 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8228 mConfig.outputCfg.bufferProvider.cookie = NULL;
8229 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8230 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8231 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8232 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008233 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008234 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008235 // - in other sessions:
8236 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8237 // other effect: overwrites output buffer: input buffer == output buffer
8238 // Auxiliary effect:
8239 // accumulates in output buffer: input buffer != output buffer
8240 // Therefore: accumulate <=> input buffer != output buffer
8241 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8242 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8243 } else {
8244 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8245 }
8246 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8247 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8248 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8249 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8250
Steve Block3856b092011-10-20 11:56:00 +01008251 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008252 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8253
Mathias Agopian65ab4712010-07-14 17:59:35 -07008254 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008255 uint32_t size = sizeof(int);
8256 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008257 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008258 sizeof(effect_config_t),
8259 &mConfig,
8260 &size,
8261 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008262 if (status == 0) {
8263 status = cmdStatus;
8264 }
8265
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008266 if (status == 0 &&
8267 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8268 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8269 effect_param_t *p = (effect_param_t *)buf32;
8270
8271 p->psize = sizeof(uint32_t);
8272 p->vsize = sizeof(uint32_t);
8273 size = sizeof(int);
8274 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8275
8276 uint32_t latency = 0;
8277 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8278 if (pbt != NULL) {
8279 latency = pbt->latency_l();
8280 }
8281
8282 *((int32_t *)p->data + 1)= latency;
8283 (*mEffectInterface)->command(mEffectInterface,
8284 EFFECT_CMD_SET_PARAM,
8285 sizeof(effect_param_t) + 8,
8286 &buf32,
8287 &size,
8288 &cmdStatus);
8289 }
8290
Mathias Agopian65ab4712010-07-14 17:59:35 -07008291 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8292 (1000 * mConfig.outputCfg.buffer.frameCount);
8293
8294 return status;
8295}
8296
8297status_t AudioFlinger::EffectModule::init()
8298{
8299 Mutex::Autolock _l(mLock);
8300 if (mEffectInterface == NULL) {
8301 return NO_INIT;
8302 }
8303 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008304 uint32_t size = sizeof(status_t);
8305 status_t status = (*mEffectInterface)->command(mEffectInterface,
8306 EFFECT_CMD_INIT,
8307 0,
8308 NULL,
8309 &size,
8310 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008311 if (status == 0) {
8312 status = cmdStatus;
8313 }
8314 return status;
8315}
8316
Eric Laurentec35a142011-10-05 17:42:25 -07008317status_t AudioFlinger::EffectModule::start()
8318{
8319 Mutex::Autolock _l(mLock);
8320 return start_l();
8321}
8322
Mathias Agopian65ab4712010-07-14 17:59:35 -07008323status_t AudioFlinger::EffectModule::start_l()
8324{
8325 if (mEffectInterface == NULL) {
8326 return NO_INIT;
8327 }
8328 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008329 uint32_t size = sizeof(status_t);
8330 status_t status = (*mEffectInterface)->command(mEffectInterface,
8331 EFFECT_CMD_ENABLE,
8332 0,
8333 NULL,
8334 &size,
8335 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008336 if (status == 0) {
8337 status = cmdStatus;
8338 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008339 if (status == 0 &&
8340 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8341 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8342 sp<ThreadBase> thread = mThread.promote();
8343 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008344 audio_stream_t *stream = thread->stream();
8345 if (stream != NULL) {
8346 stream->add_audio_effect(stream, mEffectInterface);
8347 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008348 }
8349 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008350 return status;
8351}
8352
Eric Laurentec437d82011-07-26 20:54:46 -07008353status_t AudioFlinger::EffectModule::stop()
8354{
8355 Mutex::Autolock _l(mLock);
8356 return stop_l();
8357}
8358
Mathias Agopian65ab4712010-07-14 17:59:35 -07008359status_t AudioFlinger::EffectModule::stop_l()
8360{
8361 if (mEffectInterface == NULL) {
8362 return NO_INIT;
8363 }
8364 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008365 uint32_t size = sizeof(status_t);
8366 status_t status = (*mEffectInterface)->command(mEffectInterface,
8367 EFFECT_CMD_DISABLE,
8368 0,
8369 NULL,
8370 &size,
8371 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008372 if (status == 0) {
8373 status = cmdStatus;
8374 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008375 if (status == 0 &&
8376 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8377 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8378 sp<ThreadBase> thread = mThread.promote();
8379 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008380 audio_stream_t *stream = thread->stream();
8381 if (stream != NULL) {
8382 stream->remove_audio_effect(stream, mEffectInterface);
8383 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008384 }
8385 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008386 return status;
8387}
8388
Eric Laurent25f43952010-07-28 05:40:18 -07008389status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8390 uint32_t cmdSize,
8391 void *pCmdData,
8392 uint32_t *replySize,
8393 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008394{
8395 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008396// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008397
Eric Laurentec437d82011-07-26 20:54:46 -07008398 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008399 return NO_INIT;
8400 }
Eric Laurent25f43952010-07-28 05:40:18 -07008401 status_t status = (*mEffectInterface)->command(mEffectInterface,
8402 cmdCode,
8403 cmdSize,
8404 pCmdData,
8405 replySize,
8406 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008407 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008408 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008409 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008410 EffectHandle *h = mHandles[i];
8411 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008412 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8413 }
8414 }
8415 }
8416 return status;
8417}
8418
8419status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8420{
8421 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008422 return setEnabled_l(enabled);
8423}
8424
8425// must be called with EffectModule::mLock held
8426status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8427{
8428
Steve Block3856b092011-10-20 11:56:00 +01008429 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008430
8431 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008432 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8433 if (enabled && status != NO_ERROR) {
8434 return status;
8435 }
8436
Mathias Agopian65ab4712010-07-14 17:59:35 -07008437 switch (mState) {
8438 // going from disabled to enabled
8439 case IDLE:
8440 mState = STARTING;
8441 break;
8442 case STOPPED:
8443 mState = RESTART;
8444 break;
8445 case STOPPING:
8446 mState = ACTIVE;
8447 break;
8448
8449 // going from enabled to disabled
8450 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008451 mState = STOPPED;
8452 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008453 case STARTING:
8454 mState = IDLE;
8455 break;
8456 case ACTIVE:
8457 mState = STOPPING;
8458 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008459 case DESTROYED:
8460 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008461 }
8462 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008463 EffectHandle *h = mHandles[i];
8464 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008465 h->setEnabled(enabled);
8466 }
8467 }
8468 }
8469 return NO_ERROR;
8470}
8471
Glenn Kastenc59c0042012-02-02 14:06:11 -08008472bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008473{
8474 switch (mState) {
8475 case RESTART:
8476 case STARTING:
8477 case ACTIVE:
8478 return true;
8479 case IDLE:
8480 case STOPPING:
8481 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008482 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008483 default:
8484 return false;
8485 }
8486}
8487
Glenn Kastenc59c0042012-02-02 14:06:11 -08008488bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008489{
8490 switch (mState) {
8491 case RESTART:
8492 case ACTIVE:
8493 case STOPPING:
8494 case STOPPED:
8495 return true;
8496 case IDLE:
8497 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008498 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008499 default:
8500 return false;
8501 }
8502}
8503
Mathias Agopian65ab4712010-07-14 17:59:35 -07008504status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8505{
8506 Mutex::Autolock _l(mLock);
8507 status_t status = NO_ERROR;
8508
8509 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8510 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008511 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008512 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8513 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008514 status_t cmdStatus;
8515 uint32_t volume[2];
8516 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008517 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008518 volume[0] = *left;
8519 volume[1] = *right;
8520 if (controller) {
8521 pVolume = volume;
8522 }
Eric Laurent25f43952010-07-28 05:40:18 -07008523 status = (*mEffectInterface)->command(mEffectInterface,
8524 EFFECT_CMD_SET_VOLUME,
8525 size,
8526 volume,
8527 &size,
8528 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008529 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8530 *left = volume[0];
8531 *right = volume[1];
8532 }
8533 }
8534 return status;
8535}
8536
8537status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8538{
8539 Mutex::Autolock _l(mLock);
8540 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008541 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8542 // audio pre processing modules on RecordThread can receive both output and
8543 // input device indication in the same call
8544 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8545 if (dev) {
8546 status_t cmdStatus;
8547 uint32_t size = sizeof(status_t);
8548
8549 status = (*mEffectInterface)->command(mEffectInterface,
8550 EFFECT_CMD_SET_DEVICE,
8551 sizeof(uint32_t),
8552 &dev,
8553 &size,
8554 &cmdStatus);
8555 if (status == NO_ERROR) {
8556 status = cmdStatus;
8557 }
8558 }
8559 dev = device & AUDIO_DEVICE_IN_ALL;
8560 if (dev) {
8561 status_t cmdStatus;
8562 uint32_t size = sizeof(status_t);
8563
8564 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8565 EFFECT_CMD_SET_INPUT_DEVICE,
8566 sizeof(uint32_t),
8567 &dev,
8568 &size,
8569 &cmdStatus);
8570 if (status2 == NO_ERROR) {
8571 status2 = cmdStatus;
8572 }
8573 if (status == NO_ERROR) {
8574 status = status2;
8575 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008576 }
8577 }
8578 return status;
8579}
8580
Glenn Kastenf78aee72012-01-04 11:00:47 -08008581status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008582{
8583 Mutex::Autolock _l(mLock);
8584 status_t status = NO_ERROR;
8585 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008586 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008587 uint32_t size = sizeof(status_t);
8588 status = (*mEffectInterface)->command(mEffectInterface,
8589 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008590 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008591 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008592 &size,
8593 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008594 if (status == NO_ERROR) {
8595 status = cmdStatus;
8596 }
8597 }
8598 return status;
8599}
8600
Eric Laurent59255e42011-07-27 19:49:51 -07008601void AudioFlinger::EffectModule::setSuspended(bool suspended)
8602{
8603 Mutex::Autolock _l(mLock);
8604 mSuspended = suspended;
8605}
Glenn Kastena3a85482012-01-04 11:01:11 -08008606
8607bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008608{
8609 Mutex::Autolock _l(mLock);
8610 return mSuspended;
8611}
8612
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008613bool AudioFlinger::EffectModule::purgeHandles()
8614{
8615 bool enabled = false;
8616 Mutex::Autolock _l(mLock);
8617 for (size_t i = 0; i < mHandles.size(); i++) {
8618 EffectHandle *handle = mHandles[i];
8619 if (handle != NULL && !handle->destroyed_l()) {
8620 handle->effect().clear();
8621 if (handle->hasControl()) {
8622 enabled = handle->enabled();
8623 }
8624 }
8625 }
8626 return enabled;
8627}
8628
Mathias Agopian65ab4712010-07-14 17:59:35 -07008629status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8630{
8631 const size_t SIZE = 256;
8632 char buffer[SIZE];
8633 String8 result;
8634
8635 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8636 result.append(buffer);
8637
8638 bool locked = tryLock(mLock);
8639 // failed to lock - AudioFlinger is probably deadlocked
8640 if (!locked) {
8641 result.append("\t\tCould not lock Fx mutex:\n");
8642 }
8643
8644 result.append("\t\tSession Status State Engine:\n");
8645 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8646 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8647 result.append(buffer);
8648
8649 result.append("\t\tDescriptor:\n");
8650 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8651 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8652 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8653 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8654 result.append(buffer);
8655 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8656 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8657 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8658 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8659 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008660 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008661 mDescriptor.apiVersion,
8662 mDescriptor.flags);
8663 result.append(buffer);
8664 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8665 mDescriptor.name);
8666 result.append(buffer);
8667 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8668 mDescriptor.implementor);
8669 result.append(buffer);
8670
8671 result.append("\t\t- Input configuration:\n");
8672 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8673 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8674 (uint32_t)mConfig.inputCfg.buffer.raw,
8675 mConfig.inputCfg.buffer.frameCount,
8676 mConfig.inputCfg.samplingRate,
8677 mConfig.inputCfg.channels,
8678 mConfig.inputCfg.format);
8679 result.append(buffer);
8680
8681 result.append("\t\t- Output configuration:\n");
8682 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8683 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8684 (uint32_t)mConfig.outputCfg.buffer.raw,
8685 mConfig.outputCfg.buffer.frameCount,
8686 mConfig.outputCfg.samplingRate,
8687 mConfig.outputCfg.channels,
8688 mConfig.outputCfg.format);
8689 result.append(buffer);
8690
8691 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8692 result.append(buffer);
8693 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8694 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008695 EffectHandle *handle = mHandles[i];
8696 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008697 handle->dump(buffer, SIZE);
8698 result.append(buffer);
8699 }
8700 }
8701
8702 result.append("\n");
8703
8704 write(fd, result.string(), result.length());
8705
8706 if (locked) {
8707 mLock.unlock();
8708 }
8709
8710 return NO_ERROR;
8711}
8712
8713// ----------------------------------------------------------------------------
8714// EffectHandle implementation
8715// ----------------------------------------------------------------------------
8716
8717#undef LOG_TAG
8718#define LOG_TAG "AudioFlinger::EffectHandle"
8719
8720AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8721 const sp<AudioFlinger::Client>& client,
8722 const sp<IEffectClient>& effectClient,
8723 int32_t priority)
8724 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008725 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008726 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008727{
Steve Block3856b092011-10-20 11:56:00 +01008728 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008729
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008730 if (client == 0) {
8731 return;
8732 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008733 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8734 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8735 if (mCblkMemory != 0) {
8736 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8737
Glenn Kastena0d68332012-01-27 16:47:15 -08008738 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008739 new(mCblk) effect_param_cblk_t();
8740 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008741 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008742 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008743 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008744 return;
8745 }
8746}
8747
8748AudioFlinger::EffectHandle::~EffectHandle()
8749{
Steve Block3856b092011-10-20 11:56:00 +01008750 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008751
8752 if (mEffect == 0) {
8753 mDestroyed = true;
8754 return;
8755 }
8756 mEffect->lock();
8757 mDestroyed = true;
8758 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008759 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008760}
8761
8762status_t AudioFlinger::EffectHandle::enable()
8763{
Steve Block3856b092011-10-20 11:56:00 +01008764 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008765 if (!mHasControl) return INVALID_OPERATION;
8766 if (mEffect == 0) return DEAD_OBJECT;
8767
Eric Laurentdb7c0792011-08-10 10:37:50 -07008768 if (mEnabled) {
8769 return NO_ERROR;
8770 }
8771
Eric Laurent59255e42011-07-27 19:49:51 -07008772 mEnabled = true;
8773
8774 sp<ThreadBase> thread = mEffect->thread().promote();
8775 if (thread != 0) {
8776 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8777 }
8778
8779 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8780 if (mEffect->suspended()) {
8781 return NO_ERROR;
8782 }
8783
Eric Laurentdb7c0792011-08-10 10:37:50 -07008784 status_t status = mEffect->setEnabled(true);
8785 if (status != NO_ERROR) {
8786 if (thread != 0) {
8787 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8788 }
8789 mEnabled = false;
8790 }
8791 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008792}
8793
8794status_t AudioFlinger::EffectHandle::disable()
8795{
Steve Block3856b092011-10-20 11:56:00 +01008796 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008797 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008798 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008799
Eric Laurentdb7c0792011-08-10 10:37:50 -07008800 if (!mEnabled) {
8801 return NO_ERROR;
8802 }
Eric Laurent59255e42011-07-27 19:49:51 -07008803 mEnabled = false;
8804
8805 if (mEffect->suspended()) {
8806 return NO_ERROR;
8807 }
8808
8809 status_t status = mEffect->setEnabled(false);
8810
8811 sp<ThreadBase> thread = mEffect->thread().promote();
8812 if (thread != 0) {
8813 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8814 }
8815
8816 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008817}
8818
8819void AudioFlinger::EffectHandle::disconnect()
8820{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008821 disconnect(true);
8822}
8823
Glenn Kasten58123c32012-02-03 10:32:24 -08008824void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008825{
Glenn Kasten58123c32012-02-03 10:32:24 -08008826 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008827 if (mEffect == 0) {
8828 return;
8829 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008830 // restore suspended effects if the disconnected handle was enabled and the last one.
8831 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008832 sp<ThreadBase> thread = mEffect->thread().promote();
8833 if (thread != 0) {
8834 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8835 }
Eric Laurent59255e42011-07-27 19:49:51 -07008836 }
8837
Mathias Agopian65ab4712010-07-14 17:59:35 -07008838 // release sp on module => module destructor can be called now
8839 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008840 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008841 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008842 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008843 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8844 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008845 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008846 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008847 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8848 mClient.clear();
8849 }
8850}
8851
Eric Laurent25f43952010-07-28 05:40:18 -07008852status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8853 uint32_t cmdSize,
8854 void *pCmdData,
8855 uint32_t *replySize,
8856 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008857{
Steve Block3856b092011-10-20 11:56:00 +01008858// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008859// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008860
8861 // only get parameter command is permitted for applications not controlling the effect
8862 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8863 return INVALID_OPERATION;
8864 }
8865 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008866 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008867
8868 // handle commands that are not forwarded transparently to effect engine
8869 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8870 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8871 // no risk to block the whole media server process or mixer threads is we are stuck here
8872 Mutex::Autolock _l(mCblk->lock);
8873 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8874 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8875 mCblk->serverIndex = 0;
8876 mCblk->clientIndex = 0;
8877 return BAD_VALUE;
8878 }
8879 status_t status = NO_ERROR;
8880 while (mCblk->serverIndex < mCblk->clientIndex) {
8881 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008882 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008883 int *p = (int *)(mBuffer + mCblk->serverIndex);
8884 int size = *p++;
8885 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008886 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008887 break;
8888 }
8889 effect_param_t *param = (effect_param_t *)p;
8890 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008891 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008892 mCblk->serverIndex += size;
8893 continue;
8894 }
Eric Laurent25f43952010-07-28 05:40:18 -07008895 uint32_t psize = sizeof(effect_param_t) +
8896 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8897 param->vsize;
8898 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8899 psize,
8900 p,
8901 &rsize,
8902 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008903 // stop at first error encountered
8904 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008905 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008906 *(int *)pReplyData = reply;
8907 break;
8908 } else if (reply != NO_ERROR) {
8909 *(int *)pReplyData = reply;
8910 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008911 }
8912 mCblk->serverIndex += size;
8913 }
8914 mCblk->serverIndex = 0;
8915 mCblk->clientIndex = 0;
8916 return status;
8917 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008918 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008919 return enable();
8920 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008921 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008922 return disable();
8923 }
8924
8925 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8926}
8927
Eric Laurent59255e42011-07-27 19:49:51 -07008928void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008929{
Steve Block3856b092011-10-20 11:56:00 +01008930 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008931
8932 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008933 mEnabled = enabled;
8934
Mathias Agopian65ab4712010-07-14 17:59:35 -07008935 if (signal && mEffectClient != 0) {
8936 mEffectClient->controlStatusChanged(hasControl);
8937 }
8938}
8939
Eric Laurent25f43952010-07-28 05:40:18 -07008940void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8941 uint32_t cmdSize,
8942 void *pCmdData,
8943 uint32_t replySize,
8944 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008945{
8946 if (mEffectClient != 0) {
8947 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8948 }
8949}
8950
8951
8952
8953void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8954{
8955 if (mEffectClient != 0) {
8956 mEffectClient->enableStatusChanged(enabled);
8957 }
8958}
8959
8960status_t AudioFlinger::EffectHandle::onTransact(
8961 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8962{
8963 return BnEffect::onTransact(code, data, reply, flags);
8964}
8965
8966
8967void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8968{
Glenn Kastena0d68332012-01-27 16:47:15 -08008969 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008970
8971 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008972 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008973 mPriority,
8974 mHasControl,
8975 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008976 mCblk ? mCblk->clientIndex : 0,
8977 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008978 );
8979
8980 if (locked) {
8981 mCblk->lock.unlock();
8982 }
8983}
8984
8985#undef LOG_TAG
8986#define LOG_TAG "AudioFlinger::EffectChain"
8987
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008988AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008989 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008990 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008991 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8992 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008993{
Dima Zavinfce7a472011-04-19 22:30:36 -07008994 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008995 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008996 return;
8997 }
8998 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8999 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009000}
9001
9002AudioFlinger::EffectChain::~EffectChain()
9003{
9004 if (mOwnInBuffer) {
9005 delete mInBuffer;
9006 }
9007
9008}
9009
Eric Laurent59255e42011-07-27 19:49:51 -07009010// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009011sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009012{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009013 size_t size = mEffects.size();
9014
9015 for (size_t i = 0; i < size; i++) {
9016 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009017 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009018 }
9019 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009020 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009021}
9022
Eric Laurent59255e42011-07-27 19:49:51 -07009023// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009024sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009025{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009026 size_t size = mEffects.size();
9027
9028 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009029 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9030 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009031 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009032 }
9033 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009034 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009035}
9036
Eric Laurent59255e42011-07-27 19:49:51 -07009037// getEffectFromType_l() must be called with ThreadBase::mLock held
9038sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9039 const effect_uuid_t *type)
9040{
Eric Laurent59255e42011-07-27 19:49:51 -07009041 size_t size = mEffects.size();
9042
9043 for (size_t i = 0; i < size; i++) {
9044 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009045 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009046 }
9047 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009048 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009049}
9050
Eric Laurent91b14c42012-05-30 12:30:29 -07009051void AudioFlinger::EffectChain::clearInputBuffer()
9052{
9053 Mutex::Autolock _l(mLock);
9054 sp<ThreadBase> thread = mThread.promote();
9055 if (thread == 0) {
9056 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9057 return;
9058 }
9059 clearInputBuffer_l(thread);
9060}
9061
9062// Must be called with EffectChain::mLock locked
9063void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9064{
9065 size_t numSamples = thread->frameCount() * thread->channelCount();
9066 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9067
9068}
9069
Mathias Agopian65ab4712010-07-14 17:59:35 -07009070// Must be called with EffectChain::mLock locked
9071void AudioFlinger::EffectChain::process_l()
9072{
Eric Laurentdac69112010-09-28 14:09:57 -07009073 sp<ThreadBase> thread = mThread.promote();
9074 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009075 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009076 return;
9077 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009078 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9079 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009080 // always process effects unless no more tracks are on the session and the effect tail
9081 // has been rendered
9082 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009083 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009084 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009085
Eric Laurent544fe9b2011-11-11 15:42:52 -08009086 if (!tracksOnSession && mTailBufferCount == 0) {
9087 doProcess = false;
9088 }
9089
9090 if (activeTrackCnt() == 0) {
9091 // if no track is active and the effect tail has not been rendered,
9092 // the input buffer must be cleared here as the mixer process will not do it
9093 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009094 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009095 if (mTailBufferCount > 0) {
9096 mTailBufferCount--;
9097 }
9098 }
9099 }
Eric Laurentdac69112010-09-28 14:09:57 -07009100 }
9101
Mathias Agopian65ab4712010-07-14 17:59:35 -07009102 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009103 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009104 for (size_t i = 0; i < size; i++) {
9105 mEffects[i]->process();
9106 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009107 }
9108 for (size_t i = 0; i < size; i++) {
9109 mEffects[i]->updateState();
9110 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009111}
9112
Eric Laurentcab11242010-07-15 12:50:15 -07009113// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009114status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009115{
9116 effect_descriptor_t desc = effect->desc();
9117 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9118
9119 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009120 effect->setChain(this);
9121 sp<ThreadBase> thread = mThread.promote();
9122 if (thread == 0) {
9123 return NO_INIT;
9124 }
9125 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009126
9127 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9128 // Auxiliary effects are inserted at the beginning of mEffects vector as
9129 // they are processed first and accumulated in chain input buffer
9130 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009131
Mathias Agopian65ab4712010-07-14 17:59:35 -07009132 // the input buffer for auxiliary effect contains mono samples in
9133 // 32 bit format. This is to avoid saturation in AudoMixer
9134 // accumulation stage. Saturation is done in EffectModule::process() before
9135 // calling the process in effect engine
9136 size_t numSamples = thread->frameCount();
9137 int32_t *buffer = new int32_t[numSamples];
9138 memset(buffer, 0, numSamples * sizeof(int32_t));
9139 effect->setInBuffer((int16_t *)buffer);
9140 // auxiliary effects output samples to chain input buffer for further processing
9141 // by insert effects
9142 effect->setOutBuffer(mInBuffer);
9143 } else {
9144 // Insert effects are inserted at the end of mEffects vector as they are processed
9145 // after track and auxiliary effects.
9146 // Insert effect order as a function of indicated preference:
9147 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9148 // another effect is present
9149 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9150 // last effect claiming first position
9151 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9152 // first effect claiming last position
9153 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9154 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9155 // already present
9156
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009157 size_t size = mEffects.size();
9158 size_t idx_insert = size;
9159 ssize_t idx_insert_first = -1;
9160 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009161
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009162 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009163 effect_descriptor_t d = mEffects[i]->desc();
9164 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9165 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9166 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9167 // check invalid effect chaining combinations
9168 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9169 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009170 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009171 return INVALID_OPERATION;
9172 }
9173 // remember position of first insert effect and by default
9174 // select this as insert position for new effect
9175 if (idx_insert == size) {
9176 idx_insert = i;
9177 }
9178 // remember position of last insert effect claiming
9179 // first position
9180 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9181 idx_insert_first = i;
9182 }
9183 // remember position of first insert effect claiming
9184 // last position
9185 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9186 idx_insert_last == -1) {
9187 idx_insert_last = i;
9188 }
9189 }
9190 }
9191
9192 // modify idx_insert from first position if needed
9193 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9194 if (idx_insert_last != -1) {
9195 idx_insert = idx_insert_last;
9196 } else {
9197 idx_insert = size;
9198 }
9199 } else {
9200 if (idx_insert_first != -1) {
9201 idx_insert = idx_insert_first + 1;
9202 }
9203 }
9204
9205 // always read samples from chain input buffer
9206 effect->setInBuffer(mInBuffer);
9207
9208 // if last effect in the chain, output samples to chain
9209 // output buffer, otherwise to chain input buffer
9210 if (idx_insert == size) {
9211 if (idx_insert != 0) {
9212 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9213 mEffects[idx_insert-1]->configure();
9214 }
9215 effect->setOutBuffer(mOutBuffer);
9216 } else {
9217 effect->setOutBuffer(mInBuffer);
9218 }
9219 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009220
Steve Block3856b092011-10-20 11:56:00 +01009221 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009222 }
9223 effect->configure();
9224 return NO_ERROR;
9225}
9226
Eric Laurentcab11242010-07-15 12:50:15 -07009227// removeEffect_l() must be called with PlaybackThread::mLock held
9228size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009229{
9230 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009231 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009232 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9233
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009234 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009235 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009236 // calling stop here will remove pre-processing effect from the audio HAL.
9237 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9238 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009239 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9240 mEffects[i]->state() == EffectModule::STOPPING) {
9241 mEffects[i]->stop();
9242 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009243 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9244 delete[] effect->inBuffer();
9245 } else {
9246 if (i == size - 1 && i != 0) {
9247 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9248 mEffects[i - 1]->configure();
9249 }
9250 }
9251 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009252 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009253 break;
9254 }
9255 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009256
9257 return mEffects.size();
9258}
9259
Eric Laurentcab11242010-07-15 12:50:15 -07009260// setDevice_l() must be called with PlaybackThread::mLock held
9261void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009262{
9263 size_t size = mEffects.size();
9264 for (size_t i = 0; i < size; i++) {
9265 mEffects[i]->setDevice(device);
9266 }
9267}
9268
Eric Laurentcab11242010-07-15 12:50:15 -07009269// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009270void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009271{
9272 size_t size = mEffects.size();
9273 for (size_t i = 0; i < size; i++) {
9274 mEffects[i]->setMode(mode);
9275 }
9276}
9277
Eric Laurentcab11242010-07-15 12:50:15 -07009278// setVolume_l() must be called with PlaybackThread::mLock held
9279bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009280{
9281 uint32_t newLeft = *left;
9282 uint32_t newRight = *right;
9283 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009284 int ctrlIdx = -1;
9285 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009286
Eric Laurentcab11242010-07-15 12:50:15 -07009287 // first update volume controller
9288 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009289 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009290 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9291 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009292 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009293 break;
9294 }
9295 }
9296
9297 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009298 if (hasControl) {
9299 *left = mNewLeftVolume;
9300 *right = mNewRightVolume;
9301 }
9302 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009303 }
9304
9305 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009306 mLeftVolume = newLeft;
9307 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009308
9309 // second get volume update from volume controller
9310 if (ctrlIdx >= 0) {
9311 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009312 mNewLeftVolume = newLeft;
9313 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009314 }
9315 // then indicate volume to all other effects in chain.
9316 // Pass altered volume to effects before volume controller
9317 // and requested volume to effects after controller
9318 uint32_t lVol = newLeft;
9319 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009320
Mathias Agopian65ab4712010-07-14 17:59:35 -07009321 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009322 if ((int)i == ctrlIdx) continue;
9323 // this also works for ctrlIdx == -1 when there is no volume controller
9324 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009325 lVol = *left;
9326 rVol = *right;
9327 }
9328 mEffects[i]->setVolume(&lVol, &rVol, false);
9329 }
9330 *left = newLeft;
9331 *right = newRight;
9332
9333 return hasControl;
9334}
9335
Mathias Agopian65ab4712010-07-14 17:59:35 -07009336status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9337{
9338 const size_t SIZE = 256;
9339 char buffer[SIZE];
9340 String8 result;
9341
9342 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9343 result.append(buffer);
9344
9345 bool locked = tryLock(mLock);
9346 // failed to lock - AudioFlinger is probably deadlocked
9347 if (!locked) {
9348 result.append("\tCould not lock mutex:\n");
9349 }
9350
Eric Laurentcab11242010-07-15 12:50:15 -07009351 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9352 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009353 mEffects.size(),
9354 (uint32_t)mInBuffer,
9355 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009356 mActiveTrackCnt);
9357 result.append(buffer);
9358 write(fd, result.string(), result.size());
9359
9360 for (size_t i = 0; i < mEffects.size(); ++i) {
9361 sp<EffectModule> effect = mEffects[i];
9362 if (effect != 0) {
9363 effect->dump(fd, args);
9364 }
9365 }
9366
9367 if (locked) {
9368 mLock.unlock();
9369 }
9370
9371 return NO_ERROR;
9372}
9373
Eric Laurent59255e42011-07-27 19:49:51 -07009374// must be called with ThreadBase::mLock held
9375void AudioFlinger::EffectChain::setEffectSuspended_l(
9376 const effect_uuid_t *type, bool suspend)
9377{
9378 sp<SuspendedEffectDesc> desc;
9379 // use effect type UUID timelow as key as there is no real risk of identical
9380 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009381 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009382 if (suspend) {
9383 if (index >= 0) {
9384 desc = mSuspendedEffects.valueAt(index);
9385 } else {
9386 desc = new SuspendedEffectDesc();
9387 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9388 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009389 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009390 }
9391 if (desc->mRefCount++ == 0) {
9392 sp<EffectModule> effect = getEffectIfEnabled(type);
9393 if (effect != 0) {
9394 desc->mEffect = effect;
9395 effect->setSuspended(true);
9396 effect->setEnabled(false);
9397 }
9398 }
9399 } else {
9400 if (index < 0) {
9401 return;
9402 }
9403 desc = mSuspendedEffects.valueAt(index);
9404 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009405 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009406 desc->mRefCount = 1;
9407 }
9408 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009409 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009410 if (desc->mEffect != 0) {
9411 sp<EffectModule> effect = desc->mEffect.promote();
9412 if (effect != 0) {
9413 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009414 effect->lock();
9415 EffectHandle *handle = effect->controlHandle_l();
9416 if (handle != NULL && !handle->destroyed_l()) {
9417 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009418 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009419 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009420 }
9421 desc->mEffect.clear();
9422 }
9423 mSuspendedEffects.removeItemsAt(index);
9424 }
9425 }
9426}
9427
9428// must be called with ThreadBase::mLock held
9429void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9430{
9431 sp<SuspendedEffectDesc> desc;
9432
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009433 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009434 if (suspend) {
9435 if (index >= 0) {
9436 desc = mSuspendedEffects.valueAt(index);
9437 } else {
9438 desc = new SuspendedEffectDesc();
9439 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009440 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009441 }
9442 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009443 Vector< sp<EffectModule> > effects;
9444 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009445 for (size_t i = 0; i < effects.size(); i++) {
9446 setEffectSuspended_l(&effects[i]->desc().type, true);
9447 }
9448 }
9449 } else {
9450 if (index < 0) {
9451 return;
9452 }
9453 desc = mSuspendedEffects.valueAt(index);
9454 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009455 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009456 desc->mRefCount = 1;
9457 }
9458 if (--desc->mRefCount == 0) {
9459 Vector<const effect_uuid_t *> types;
9460 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9461 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9462 continue;
9463 }
9464 types.add(&mSuspendedEffects.valueAt(i)->mType);
9465 }
9466 for (size_t i = 0; i < types.size(); i++) {
9467 setEffectSuspended_l(types[i], false);
9468 }
Steve Block3856b092011-10-20 11:56:00 +01009469 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009470 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9471 }
9472 }
9473}
9474
Eric Laurent6bffdb82011-09-23 08:40:41 -07009475
9476// The volume effect is used for automated tests only
9477#ifndef OPENSL_ES_H_
9478static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9479 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9480const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9481#endif //OPENSL_ES_H_
9482
Eric Laurentdb7c0792011-08-10 10:37:50 -07009483bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9484{
9485 // auxiliary effects and visualizer are never suspended on output mix
9486 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9487 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009488 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9489 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009490 return false;
9491 }
9492 return true;
9493}
9494
Glenn Kastend0539712012-01-30 12:56:03 -08009495void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009496{
Glenn Kastend0539712012-01-30 12:56:03 -08009497 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009498 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009499 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9500 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009501 }
Eric Laurent59255e42011-07-27 19:49:51 -07009502 }
Eric Laurent59255e42011-07-27 19:49:51 -07009503}
9504
9505sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9506 const effect_uuid_t *type)
9507{
Glenn Kasten090f0192012-01-30 13:00:02 -08009508 sp<EffectModule> effect = getEffectFromType_l(type);
9509 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009510}
9511
9512void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9513 bool enabled)
9514{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009515 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009516 if (enabled) {
9517 if (index < 0) {
9518 // if the effect is not suspend check if all effects are suspended
9519 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9520 if (index < 0) {
9521 return;
9522 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009523 if (!isEffectEligibleForSuspend(effect->desc())) {
9524 return;
9525 }
Eric Laurent59255e42011-07-27 19:49:51 -07009526 setEffectSuspended_l(&effect->desc().type, enabled);
9527 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009528 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009529 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009530 return;
9531 }
Eric Laurent59255e42011-07-27 19:49:51 -07009532 }
Steve Block3856b092011-10-20 11:56:00 +01009533 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009534 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009535 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9536 // if effect is requested to suspended but was not yet enabled, supend it now.
9537 if (desc->mEffect == 0) {
9538 desc->mEffect = effect;
9539 effect->setEnabled(false);
9540 effect->setSuspended(true);
9541 }
9542 } else {
9543 if (index < 0) {
9544 return;
9545 }
Steve Block3856b092011-10-20 11:56:00 +01009546 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009547 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009548 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9549 desc->mEffect.clear();
9550 effect->setSuspended(false);
9551 }
9552}
9553
Mathias Agopian65ab4712010-07-14 17:59:35 -07009554#undef LOG_TAG
9555#define LOG_TAG "AudioFlinger"
9556
9557// ----------------------------------------------------------------------------
9558
9559status_t AudioFlinger::onTransact(
9560 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9561{
9562 return BnAudioFlinger::onTransact(code, data, reply, flags);
9563}
9564
Mathias Agopian65ab4712010-07-14 17:59:35 -07009565}; // namespace android