blob: 59c7f84084f4589ac22caceb818b29479eb6965e [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),
213 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
214 mMasterVolume(1.0f),
215 mMasterVolumeSupportLvl(MVS_NONE),
216 mMasterMute(false),
217 mNextUniqueId(1),
218 mMode(AUDIO_MODE_INVALID),
219 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700220{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700221}
222
223void AudioFlinger::onFirstRef()
224{
Dima Zavin799a70e2011-04-18 16:57:27 -0700225 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700226
Eric Laurent93575202011-01-18 18:39:02 -0800227 Mutex::Autolock _l(mLock);
228
Dima Zavin799a70e2011-04-18 16:57:27 -0700229 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800230 char val_str[PROPERTY_VALUE_MAX] = { 0 };
231 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
232 uint32_t int_val;
233 if (1 == sscanf(val_str, "%u", &int_val)) {
234 mStandbyTimeInNsecs = milliseconds(int_val);
235 ALOGI("Using %u mSec as standby time.", int_val);
236 } else {
237 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
238 ALOGI("Using default %u mSec as standby time.",
239 (uint32_t)(mStandbyTimeInNsecs / 1000000));
240 }
241 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700242
Eric Laurenta4c5a552012-03-29 10:12:40 -0700243 mMode = AUDIO_MODE_NORMAL;
244 mMasterVolumeSW = 1.0;
245 mMasterVolume = 1.0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800246 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700247}
248
249AudioFlinger::~AudioFlinger()
250{
Dima Zavin799a70e2011-04-18 16:57:27 -0700251
Mathias Agopian65ab4712010-07-14 17:59:35 -0700252 while (!mRecordThreads.isEmpty()) {
253 // closeInput() will remove first entry from mRecordThreads
254 closeInput(mRecordThreads.keyAt(0));
255 }
256 while (!mPlaybackThreads.isEmpty()) {
257 // closeOutput() will remove first entry from mPlaybackThreads
258 closeOutput(mPlaybackThreads.keyAt(0));
259 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700260
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800261 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
262 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700263 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
264 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700265 }
266}
267
Eric Laurenta4c5a552012-03-29 10:12:40 -0700268static const char * const audio_interfaces[] = {
269 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
270 AUDIO_HARDWARE_MODULE_ID_A2DP,
271 AUDIO_HARDWARE_MODULE_ID_USB,
272};
273#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
274
275audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(audio_module_handle_t module, uint32_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700276{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700277 // if module is 0, the request comes from an old policy manager and we should load
278 // well known modules
279 if (module == 0) {
280 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
281 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
282 loadHwModule_l(audio_interfaces[i]);
283 }
284 } else {
285 // check a match for the requested module handle
286 AudioHwDevice *audioHwdevice = mAudioHwDevs.valueFor(module);
287 if (audioHwdevice != NULL) {
288 return audioHwdevice->hwDevice();
289 }
290 }
291 // then try to find a module supporting the requested device.
Dima Zavin799a70e2011-04-18 16:57:27 -0700292 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700293 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700294 if ((dev->get_supported_devices(dev) & devices) == devices)
295 return dev;
296 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700297
Dima Zavin799a70e2011-04-18 16:57:27 -0700298 return NULL;
299}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700300
301status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
302{
303 const size_t SIZE = 256;
304 char buffer[SIZE];
305 String8 result;
306
307 result.append("Clients:\n");
308 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800309 sp<Client> client = mClients.valueAt(i).promote();
310 if (client != 0) {
311 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
312 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700313 }
314 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700315
316 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800317 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700318 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
319 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800320 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700321 result.append(buffer);
322 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700323 write(fd, result.string(), result.size());
324 return NO_ERROR;
325}
326
327
328status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
329{
330 const size_t SIZE = 256;
331 char buffer[SIZE];
332 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800333 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700334
John Grossman4ff14ba2012-02-08 16:37:41 -0800335 snprintf(buffer, SIZE, "Hardware status: %d\n"
336 "Standby Time mSec: %u\n",
337 hardwareStatus,
338 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700339 result.append(buffer);
340 write(fd, result.string(), result.size());
341 return NO_ERROR;
342}
343
344status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
345{
346 const size_t SIZE = 256;
347 char buffer[SIZE];
348 String8 result;
349 snprintf(buffer, SIZE, "Permission Denial: "
350 "can't dump AudioFlinger from pid=%d, uid=%d\n",
351 IPCThreadState::self()->getCallingPid(),
352 IPCThreadState::self()->getCallingUid());
353 result.append(buffer);
354 write(fd, result.string(), result.size());
355 return NO_ERROR;
356}
357
358static bool tryLock(Mutex& mutex)
359{
360 bool locked = false;
361 for (int i = 0; i < kDumpLockRetries; ++i) {
362 if (mutex.tryLock() == NO_ERROR) {
363 locked = true;
364 break;
365 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800366 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700367 }
368 return locked;
369}
370
371status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
372{
Glenn Kasten44deb052012-02-05 18:09:08 -0800373 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700374 dumpPermissionDenial(fd, args);
375 } else {
376 // get state of hardware lock
377 bool hardwareLocked = tryLock(mHardwareLock);
378 if (!hardwareLocked) {
379 String8 result(kHardwareLockedString);
380 write(fd, result.string(), result.size());
381 } else {
382 mHardwareLock.unlock();
383 }
384
385 bool locked = tryLock(mLock);
386
387 // failed to lock - AudioFlinger is probably deadlocked
388 if (!locked) {
389 String8 result(kDeadlockedString);
390 write(fd, result.string(), result.size());
391 }
392
393 dumpClients(fd, args);
394 dumpInternals(fd, args);
395
396 // dump playback threads
397 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
398 mPlaybackThreads.valueAt(i)->dump(fd, args);
399 }
400
401 // dump record threads
402 for (size_t i = 0; i < mRecordThreads.size(); i++) {
403 mRecordThreads.valueAt(i)->dump(fd, args);
404 }
405
Dima Zavin799a70e2011-04-18 16:57:27 -0700406 // dump all hardware devs
407 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700408 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700409 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700410 }
411 if (locked) mLock.unlock();
412 }
413 return NO_ERROR;
414}
415
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800416sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
417{
418 // If pid is already in the mClients wp<> map, then use that entry
419 // (for which promote() is always != 0), otherwise create a new entry and Client.
420 sp<Client> client = mClients.valueFor(pid).promote();
421 if (client == 0) {
422 client = new Client(this, pid);
423 mClients.add(pid, client);
424 }
425
426 return client;
427}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700428
429// IAudioFlinger interface
430
431
432sp<IAudioTrack> AudioFlinger::createTrack(
433 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800434 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700435 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800436 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700437 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700438 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800439 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700440 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800441 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800442 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700443 int *sessionId,
444 status_t *status)
445{
446 sp<PlaybackThread::Track> track;
447 sp<TrackHandle> trackHandle;
448 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700449 status_t lStatus;
450 int lSessionId;
451
Glenn Kasten263709e2012-01-06 08:40:01 -0800452 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
453 // but if someone uses binder directly they could bypass that and cause us to crash
454 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000455 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700456 lStatus = BAD_VALUE;
457 goto Exit;
458 }
459
460 {
461 Mutex::Autolock _l(mLock);
462 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700463 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700464 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000465 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700466 lStatus = BAD_VALUE;
467 goto Exit;
468 }
469
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800470 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700471
Steve Block3856b092011-10-20 11:56:00 +0100472 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700473 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700474 // check if an effect chain with the same session ID is present on another
475 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700476 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700477 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
478 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700479 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700480 if (sessions & PlaybackThread::EFFECT_SESSION) {
481 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700482 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700483 }
Eric Laurentde070132010-07-13 04:45:46 -0700484 }
485 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700486 lSessionId = *sessionId;
487 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700488 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700489 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700490 if (sessionId != NULL) {
491 *sessionId = lSessionId;
492 }
493 }
Steve Block3856b092011-10-20 11:56:00 +0100494 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700495
496 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800497 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700498
499 // move effect chain to this output thread if an effect on same session was waiting
500 // for a track to be created
501 if (lStatus == NO_ERROR && effectThread != NULL) {
502 Mutex::Autolock _dl(thread->mLock);
503 Mutex::Autolock _sl(effectThread->mLock);
504 moveEffectChain_l(lSessionId, effectThread, thread, true);
505 }
Eric Laurenta011e352012-03-29 15:51:43 -0700506
507 // Look for sync events awaiting for a session to be used.
508 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
509 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
510 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700511 if (lStatus == NO_ERROR) {
512 track->setSyncEvent(mPendingSyncEvents[i]);
513 } else {
514 mPendingSyncEvents[i]->cancel();
515 }
Eric Laurenta011e352012-03-29 15:51:43 -0700516 mPendingSyncEvents.removeAt(i);
517 i--;
518 }
519 }
520 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700521 }
522 if (lStatus == NO_ERROR) {
523 trackHandle = new TrackHandle(track);
524 } else {
525 // remove local strong reference to Client before deleting the Track so that the Client
526 // destructor is called by the TrackBase destructor with mLock held
527 client.clear();
528 track.clear();
529 }
530
531Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700532 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700533 *status = lStatus;
534 }
535 return trackHandle;
536}
537
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800538uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700539{
540 Mutex::Autolock _l(mLock);
541 PlaybackThread *thread = checkPlaybackThread_l(output);
542 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000543 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700544 return 0;
545 }
546 return thread->sampleRate();
547}
548
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800549int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700550{
551 Mutex::Autolock _l(mLock);
552 PlaybackThread *thread = checkPlaybackThread_l(output);
553 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000554 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700555 return 0;
556 }
557 return thread->channelCount();
558}
559
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800560audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700561{
562 Mutex::Autolock _l(mLock);
563 PlaybackThread *thread = checkPlaybackThread_l(output);
564 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000565 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800566 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700567 }
568 return thread->format();
569}
570
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800571size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700572{
573 Mutex::Autolock _l(mLock);
574 PlaybackThread *thread = checkPlaybackThread_l(output);
575 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000576 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700577 return 0;
578 }
Glenn Kasten58912562012-04-03 10:45:00 -0700579 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
580 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700581 return thread->frameCount();
582}
583
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800584uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700585{
586 Mutex::Autolock _l(mLock);
587 PlaybackThread *thread = checkPlaybackThread_l(output);
588 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000589 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700590 return 0;
591 }
592 return thread->latency();
593}
594
595status_t AudioFlinger::setMasterVolume(float value)
596{
Eric Laurenta1884f92011-08-23 08:25:03 -0700597 status_t ret = initCheck();
598 if (ret != NO_ERROR) {
599 return ret;
600 }
601
Mathias Agopian65ab4712010-07-14 17:59:35 -0700602 // check calling permissions
603 if (!settingsAllowed()) {
604 return PERMISSION_DENIED;
605 }
606
John Grossman4ff14ba2012-02-08 16:37:41 -0800607 float swmv = value;
608
Eric Laurenta4c5a552012-03-29 10:12:40 -0700609 Mutex::Autolock _l(mLock);
610
Mathias Agopian65ab4712010-07-14 17:59:35 -0700611 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800612 if (MVS_NONE != mMasterVolumeSupportLvl) {
613 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
614 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700615 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
John Grossman4ff14ba2012-02-08 16:37:41 -0800616
617 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
618 if (NULL != dev->set_master_volume) {
619 dev->set_master_volume(dev, value);
620 }
621 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800622 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800623
624 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700625 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700626
John Grossman4ff14ba2012-02-08 16:37:41 -0800627 mMasterVolume = value;
628 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800629 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700630 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700631
632 return NO_ERROR;
633}
634
Glenn Kastenf78aee72012-01-04 11:00:47 -0800635status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700636{
Eric Laurenta1884f92011-08-23 08:25:03 -0700637 status_t ret = initCheck();
638 if (ret != NO_ERROR) {
639 return ret;
640 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700641
642 // check calling permissions
643 if (!settingsAllowed()) {
644 return PERMISSION_DENIED;
645 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800646 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000647 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700648 return BAD_VALUE;
649 }
650
651 { // scope for the lock
652 AutoMutex lock(mHardwareLock);
653 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700654 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700655 mHardwareStatus = AUDIO_HW_IDLE;
656 }
657
658 if (NO_ERROR == ret) {
659 Mutex::Autolock _l(mLock);
660 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800661 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700662 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700663 }
664
665 return ret;
666}
667
668status_t AudioFlinger::setMicMute(bool state)
669{
Eric Laurenta1884f92011-08-23 08:25:03 -0700670 status_t ret = initCheck();
671 if (ret != NO_ERROR) {
672 return ret;
673 }
674
Mathias Agopian65ab4712010-07-14 17:59:35 -0700675 // check calling permissions
676 if (!settingsAllowed()) {
677 return PERMISSION_DENIED;
678 }
679
680 AutoMutex lock(mHardwareLock);
681 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700682 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700683 mHardwareStatus = AUDIO_HW_IDLE;
684 return ret;
685}
686
687bool AudioFlinger::getMicMute() const
688{
Eric Laurenta1884f92011-08-23 08:25:03 -0700689 status_t ret = initCheck();
690 if (ret != NO_ERROR) {
691 return false;
692 }
693
Dima Zavinfce7a472011-04-19 22:30:36 -0700694 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800695 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700696 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700697 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700698 mHardwareStatus = AUDIO_HW_IDLE;
699 return state;
700}
701
702status_t AudioFlinger::setMasterMute(bool muted)
703{
704 // check calling permissions
705 if (!settingsAllowed()) {
706 return PERMISSION_DENIED;
707 }
708
Eric Laurent93575202011-01-18 18:39:02 -0800709 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800710 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700711 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800712 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700713 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700714
715 return NO_ERROR;
716}
717
718float AudioFlinger::masterVolume() const
719{
Glenn Kasten98067102011-12-13 11:47:54 -0800720 Mutex::Autolock _l(mLock);
721 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700722}
723
John Grossman4ff14ba2012-02-08 16:37:41 -0800724float AudioFlinger::masterVolumeSW() const
725{
726 Mutex::Autolock _l(mLock);
727 return masterVolumeSW_l();
728}
729
Mathias Agopian65ab4712010-07-14 17:59:35 -0700730bool AudioFlinger::masterMute() const
731{
Glenn Kasten98067102011-12-13 11:47:54 -0800732 Mutex::Autolock _l(mLock);
733 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700734}
735
John Grossman4ff14ba2012-02-08 16:37:41 -0800736float AudioFlinger::masterVolume_l() const
737{
738 if (MVS_FULL == mMasterVolumeSupportLvl) {
739 float ret_val;
740 AutoMutex lock(mHardwareLock);
741
742 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800743 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
744 (NULL != mPrimaryHardwareDev->get_master_volume),
745 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800746
747 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
748 mHardwareStatus = AUDIO_HW_IDLE;
749 return ret_val;
750 }
751
752 return mMasterVolume;
753}
754
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800755status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
756 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700757{
758 // check calling permissions
759 if (!settingsAllowed()) {
760 return PERMISSION_DENIED;
761 }
762
Glenn Kasten263709e2012-01-06 08:40:01 -0800763 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000764 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700765 return BAD_VALUE;
766 }
767
768 AutoMutex lock(mLock);
769 PlaybackThread *thread = NULL;
770 if (output) {
771 thread = checkPlaybackThread_l(output);
772 if (thread == NULL) {
773 return BAD_VALUE;
774 }
775 }
776
777 mStreamTypes[stream].volume = value;
778
779 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800780 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700781 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700782 }
783 } else {
784 thread->setStreamVolume(stream, value);
785 }
786
787 return NO_ERROR;
788}
789
Glenn Kastenfff6d712012-01-12 16:38:12 -0800790status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700791{
792 // check calling permissions
793 if (!settingsAllowed()) {
794 return PERMISSION_DENIED;
795 }
796
Glenn Kasten263709e2012-01-06 08:40:01 -0800797 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700798 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000799 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700800 return BAD_VALUE;
801 }
802
Eric Laurent93575202011-01-18 18:39:02 -0800803 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700804 mStreamTypes[stream].mute = muted;
805 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700806 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700807
808 return NO_ERROR;
809}
810
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800811float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700812{
Glenn Kasten263709e2012-01-06 08:40:01 -0800813 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814 return 0.0f;
815 }
816
817 AutoMutex lock(mLock);
818 float volume;
819 if (output) {
820 PlaybackThread *thread = checkPlaybackThread_l(output);
821 if (thread == NULL) {
822 return 0.0f;
823 }
824 volume = thread->streamVolume(stream);
825 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800826 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700827 }
828
829 return volume;
830}
831
Glenn Kastenfff6d712012-01-12 16:38:12 -0800832bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833{
Glenn Kasten263709e2012-01-06 08:40:01 -0800834 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700835 return true;
836 }
837
Glenn Kasten6637baa2012-01-09 09:40:36 -0800838 AutoMutex lock(mLock);
839 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700840}
841
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800842status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700843{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800844 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
846 // check calling permissions
847 if (!settingsAllowed()) {
848 return PERMISSION_DENIED;
849 }
850
Mathias Agopian65ab4712010-07-14 17:59:35 -0700851 // ioHandle == 0 means the parameters are global to the audio hardware interface
852 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700853 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700854 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800855 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700856 AutoMutex lock(mHardwareLock);
857 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
858 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
859 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
860 status_t result = dev->set_parameters(dev, keyValuePairs.string());
861 final_result = result ?: final_result;
862 }
863 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800864 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700865 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
866 AudioParameter param = AudioParameter(keyValuePairs);
867 String8 value;
868 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700869 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
870 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700871 for (size_t i = 0; i < mRecordThreads.size(); i++) {
872 sp<RecordThread> thread = mRecordThreads.valueAt(i);
873 RecordThread::RecordTrack *track = thread->track();
874 if (track != NULL) {
875 audio_devices_t device = (audio_devices_t)(
876 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700877 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700878 thread->setEffectSuspended(FX_IID_AEC,
879 suspend,
880 track->sessionId());
881 thread->setEffectSuspended(FX_IID_NS,
882 suspend,
883 track->sessionId());
884 }
885 }
Eric Laurentbee53372011-08-29 12:42:48 -0700886 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700887 }
888 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700889 String8 screenState;
890 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
891 bool isOff = screenState == "off";
892 if (isOff != (gScreenState & 1)) {
893 gScreenState = ((gScreenState & ~1) + 2) | isOff;
894 }
895 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700896 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700897 }
898
899 // hold a strong ref on thread in case closeOutput() or closeInput() is called
900 // and the thread is exited once the lock is released
901 sp<ThreadBase> thread;
902 {
903 Mutex::Autolock _l(mLock);
904 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -0700905 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700906 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800907 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700908 // indicate output device change to all input threads for pre processing
909 AudioParameter param = AudioParameter(keyValuePairs);
910 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700911 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
912 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700913 for (size_t i = 0; i < mRecordThreads.size(); i++) {
914 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
915 }
916 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700917 }
918 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800919 if (thread != 0) {
920 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700921 }
922 return BAD_VALUE;
923}
924
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800925String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700926{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800927// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700928// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
929
Eric Laurenta4c5a552012-03-29 10:12:40 -0700930 Mutex::Autolock _l(mLock);
931
Mathias Agopian65ab4712010-07-14 17:59:35 -0700932 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700933 String8 out_s8;
934
Dima Zavin799a70e2011-04-18 16:57:27 -0700935 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800936 char *s;
937 {
938 AutoMutex lock(mHardwareLock);
939 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700940 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800941 s = dev->get_parameters(dev, keys.string());
942 mHardwareStatus = AUDIO_HW_IDLE;
943 }
John Grossmanef7740b2012-02-09 11:28:36 -0800944 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700945 free(s);
946 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700947 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700948 }
949
Mathias Agopian65ab4712010-07-14 17:59:35 -0700950 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
951 if (playbackThread != NULL) {
952 return playbackThread->getParameters(keys);
953 }
954 RecordThread *recordThread = checkRecordThread_l(ioHandle);
955 if (recordThread != NULL) {
956 return recordThread->getParameters(keys);
957 }
958 return String8("");
959}
960
Glenn Kastendd8104c2012-07-02 12:42:44 -0700961size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
962 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700963{
Eric Laurenta1884f92011-08-23 08:25:03 -0700964 status_t ret = initCheck();
965 if (ret != NO_ERROR) {
966 return 0;
967 }
968
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800969 AutoMutex lock(mHardwareLock);
970 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700971 struct audio_config config = {
972 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -0700973 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700974 format: format,
975 };
976 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800977 mHardwareStatus = AUDIO_HW_IDLE;
978 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700979}
980
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800981unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700982{
983 if (ioHandle == 0) {
984 return 0;
985 }
986
987 Mutex::Autolock _l(mLock);
988
989 RecordThread *recordThread = checkRecordThread_l(ioHandle);
990 if (recordThread != NULL) {
991 return recordThread->getInputFramesLost();
992 }
993 return 0;
994}
995
996status_t AudioFlinger::setVoiceVolume(float value)
997{
Eric Laurenta1884f92011-08-23 08:25:03 -0700998 status_t ret = initCheck();
999 if (ret != NO_ERROR) {
1000 return ret;
1001 }
1002
Mathias Agopian65ab4712010-07-14 17:59:35 -07001003 // check calling permissions
1004 if (!settingsAllowed()) {
1005 return PERMISSION_DENIED;
1006 }
1007
1008 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001009 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -07001010 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001011 mHardwareStatus = AUDIO_HW_IDLE;
1012
1013 return ret;
1014}
1015
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001016status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1017 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001018{
1019 status_t status;
1020
1021 Mutex::Autolock _l(mLock);
1022
1023 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1024 if (playbackThread != NULL) {
1025 return playbackThread->getRenderPosition(halFrames, dspFrames);
1026 }
1027
1028 return BAD_VALUE;
1029}
1030
1031void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1032{
1033
1034 Mutex::Autolock _l(mLock);
1035
Glenn Kastenbb001922012-02-03 11:10:26 -08001036 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001037 if (mNotificationClients.indexOfKey(pid) < 0) {
1038 sp<NotificationClient> notificationClient = new NotificationClient(this,
1039 client,
1040 pid);
Steve Block3856b092011-10-20 11:56:00 +01001041 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001042
1043 mNotificationClients.add(pid, notificationClient);
1044
1045 sp<IBinder> binder = client->asBinder();
1046 binder->linkToDeath(notificationClient);
1047
1048 // the config change is always sent from playback or record threads to avoid deadlock
1049 // with AudioSystem::gLock
1050 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1051 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1052 }
1053
1054 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1055 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1056 }
1057 }
1058}
1059
1060void AudioFlinger::removeNotificationClient(pid_t pid)
1061{
1062 Mutex::Autolock _l(mLock);
1063
Glenn Kastena3b09252012-01-20 09:19:01 -08001064 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001065
Steve Block3856b092011-10-20 11:56:00 +01001066 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001067 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001068 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001069 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001070 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001071 ALOGV(" pid %d @ %d", ref->mPid, i);
1072 if (ref->mPid == pid) {
1073 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001074 mAudioSessionRefs.removeAt(i);
1075 delete ref;
1076 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001077 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001078 } else {
1079 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001080 }
1081 }
1082 if (removed) {
1083 purgeStaleEffects_l();
1084 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001085}
1086
1087// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001088void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001089{
1090 size_t size = mNotificationClients.size();
1091 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001092 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1093 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001094 }
1095}
1096
1097// removeClient_l() must be called with AudioFlinger::mLock held
1098void AudioFlinger::removeClient_l(pid_t pid)
1099{
Steve Block3856b092011-10-20 11:56:00 +01001100 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001101 mClients.removeItem(pid);
1102}
1103
Eric Laurent717e1282012-06-29 16:36:52 -07001104// getEffectThread_l() must be called with AudioFlinger::mLock held
1105sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1106{
1107 sp<PlaybackThread> thread;
1108
1109 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1110 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1111 ALOG_ASSERT(thread == 0);
1112 thread = mPlaybackThreads.valueAt(i);
1113 }
1114 }
1115
1116 return thread;
1117}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001118
1119// ----------------------------------------------------------------------------
1120
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001121AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1122 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001123 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001124 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001125 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001126 // mChannelMask
1127 mChannelCount(0),
1128 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1129 mParamStatus(NO_ERROR),
Glenn Kasten94479fd2012-07-09 15:39:54 -07001130 mStandby(false), mDevice((audio_devices_t) device), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001131 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001132{
1133}
1134
1135AudioFlinger::ThreadBase::~ThreadBase()
1136{
1137 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001138 // do not lock the mutex in destructor
1139 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001140 if (mPowerManager != 0) {
1141 sp<IBinder> binder = mPowerManager->asBinder();
1142 binder->unlinkToDeath(mDeathRecipient);
1143 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001144}
1145
1146void AudioFlinger::ThreadBase::exit()
1147{
Steve Block3856b092011-10-20 11:56:00 +01001148 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001149 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001150 // This lock prevents the following race in thread (uniprocessor for illustration):
1151 // if (!exitPending()) {
1152 // // context switch from here to exit()
1153 // // exit() calls requestExit(), what exitPending() observes
1154 // // exit() calls signal(), which is dropped since no waiters
1155 // // context switch back from exit() to here
1156 // mWaitWorkCV.wait(...);
1157 // // now thread is hung
1158 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001159 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001160 requestExit();
1161 mWaitWorkCV.signal();
1162 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001163 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1164 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001165 requestExitAndWait();
1166}
1167
Mathias Agopian65ab4712010-07-14 17:59:35 -07001168status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1169{
1170 status_t status;
1171
Steve Block3856b092011-10-20 11:56:00 +01001172 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001173 Mutex::Autolock _l(mLock);
1174
1175 mNewParameters.add(keyValuePairs);
1176 mWaitWorkCV.signal();
1177 // wait condition with timeout in case the thread loop has exited
1178 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001179 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001180 status = mParamStatus;
1181 mWaitWorkCV.signal();
1182 } else {
1183 status = TIMED_OUT;
1184 }
1185 return status;
1186}
1187
1188void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1189{
1190 Mutex::Autolock _l(mLock);
1191 sendConfigEvent_l(event, param);
1192}
1193
1194// sendConfigEvent_l() must be called with ThreadBase::mLock held
1195void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1196{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001197 ConfigEvent configEvent;
1198 configEvent.mEvent = event;
1199 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001200 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001201 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001202 mWaitWorkCV.signal();
1203}
1204
1205void AudioFlinger::ThreadBase::processConfigEvents()
1206{
1207 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001208 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001209 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001210 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001211 mConfigEvents.removeAt(0);
1212 // release mLock before locking AudioFlinger mLock: lock order is always
1213 // AudioFlinger then ThreadBase to avoid cross deadlock
1214 mLock.unlock();
1215 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001216 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001217 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001218 mLock.lock();
1219 }
1220 mLock.unlock();
1221}
1222
1223status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1224{
1225 const size_t SIZE = 256;
1226 char buffer[SIZE];
1227 String8 result;
1228
1229 bool locked = tryLock(mLock);
1230 if (!locked) {
1231 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1232 write(fd, buffer, strlen(buffer));
1233 }
1234
Eric Laurent612bbb52012-03-14 15:03:26 -07001235 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1236 result.append(buffer);
1237 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1238 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001239 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1240 result.append(buffer);
1241 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1242 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001243 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1244 result.append(buffer);
1245 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001246 result.append(buffer);
1247 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1248 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001249 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1250 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001251 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1252 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001253 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001254 result.append(buffer);
1255
1256 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1257 result.append(buffer);
1258 result.append(" Index Command");
1259 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1260 snprintf(buffer, SIZE, "\n %02d ", i);
1261 result.append(buffer);
1262 result.append(mNewParameters[i]);
1263 }
1264
1265 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1266 result.append(buffer);
1267 snprintf(buffer, SIZE, " Index event param\n");
1268 result.append(buffer);
1269 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001270 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001271 result.append(buffer);
1272 }
1273 result.append("\n");
1274
1275 write(fd, result.string(), result.size());
1276
1277 if (locked) {
1278 mLock.unlock();
1279 }
1280 return NO_ERROR;
1281}
1282
Eric Laurent1d2bff02011-07-24 17:49:51 -07001283status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1284{
1285 const size_t SIZE = 256;
1286 char buffer[SIZE];
1287 String8 result;
1288
1289 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1290 write(fd, buffer, strlen(buffer));
1291
1292 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1293 sp<EffectChain> chain = mEffectChains[i];
1294 if (chain != 0) {
1295 chain->dump(fd, args);
1296 }
1297 }
1298 return NO_ERROR;
1299}
1300
Eric Laurentfeb0db62011-07-22 09:04:31 -07001301void AudioFlinger::ThreadBase::acquireWakeLock()
1302{
1303 Mutex::Autolock _l(mLock);
1304 acquireWakeLock_l();
1305}
1306
1307void AudioFlinger::ThreadBase::acquireWakeLock_l()
1308{
1309 if (mPowerManager == 0) {
1310 // use checkService() to avoid blocking if power service is not up yet
1311 sp<IBinder> binder =
1312 defaultServiceManager()->checkService(String16("power"));
1313 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001314 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001315 } else {
1316 mPowerManager = interface_cast<IPowerManager>(binder);
1317 binder->linkToDeath(mDeathRecipient);
1318 }
1319 }
1320 if (mPowerManager != 0) {
1321 sp<IBinder> binder = new BBinder();
1322 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1323 binder,
1324 String16(mName));
1325 if (status == NO_ERROR) {
1326 mWakeLockToken = binder;
1327 }
Steve Block3856b092011-10-20 11:56:00 +01001328 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001329 }
1330}
1331
1332void AudioFlinger::ThreadBase::releaseWakeLock()
1333{
1334 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001335 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001336}
1337
1338void AudioFlinger::ThreadBase::releaseWakeLock_l()
1339{
1340 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001341 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001342 if (mPowerManager != 0) {
1343 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1344 }
1345 mWakeLockToken.clear();
1346 }
1347}
1348
1349void AudioFlinger::ThreadBase::clearPowerManager()
1350{
1351 Mutex::Autolock _l(mLock);
1352 releaseWakeLock_l();
1353 mPowerManager.clear();
1354}
1355
1356void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1357{
1358 sp<ThreadBase> thread = mThread.promote();
1359 if (thread != 0) {
1360 thread->clearPowerManager();
1361 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001362 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001363}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001364
Eric Laurent59255e42011-07-27 19:49:51 -07001365void AudioFlinger::ThreadBase::setEffectSuspended(
1366 const effect_uuid_t *type, bool suspend, int sessionId)
1367{
1368 Mutex::Autolock _l(mLock);
1369 setEffectSuspended_l(type, suspend, sessionId);
1370}
1371
1372void AudioFlinger::ThreadBase::setEffectSuspended_l(
1373 const effect_uuid_t *type, bool suspend, int sessionId)
1374{
Glenn Kasten090f0192012-01-30 13:00:02 -08001375 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001376 if (chain != 0) {
1377 if (type != NULL) {
1378 chain->setEffectSuspended_l(type, suspend);
1379 } else {
1380 chain->setEffectSuspendedAll_l(suspend);
1381 }
1382 }
1383
1384 updateSuspendedSessions_l(type, suspend, sessionId);
1385}
1386
1387void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1388{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001389 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001390 if (index < 0) {
1391 return;
1392 }
1393
1394 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1395 mSuspendedSessions.editValueAt(index);
1396
1397 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001398 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001399 for (int j = 0; j < desc->mRefCount; j++) {
1400 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1401 chain->setEffectSuspendedAll_l(true);
1402 } else {
Steve Block3856b092011-10-20 11:56:00 +01001403 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001404 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001405 chain->setEffectSuspended_l(&desc->mType, true);
1406 }
1407 }
1408 }
1409}
1410
Eric Laurent59255e42011-07-27 19:49:51 -07001411void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1412 bool suspend,
1413 int sessionId)
1414{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001415 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001416
1417 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1418
1419 if (suspend) {
1420 if (index >= 0) {
1421 sessionEffects = mSuspendedSessions.editValueAt(index);
1422 } else {
1423 mSuspendedSessions.add(sessionId, sessionEffects);
1424 }
1425 } else {
1426 if (index < 0) {
1427 return;
1428 }
1429 sessionEffects = mSuspendedSessions.editValueAt(index);
1430 }
1431
1432
1433 int key = EffectChain::kKeyForSuspendAll;
1434 if (type != NULL) {
1435 key = type->timeLow;
1436 }
1437 index = sessionEffects.indexOfKey(key);
1438
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001439 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001440 if (suspend) {
1441 if (index >= 0) {
1442 desc = sessionEffects.valueAt(index);
1443 } else {
1444 desc = new SuspendedSessionDesc();
1445 if (type != NULL) {
1446 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1447 }
1448 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001449 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001450 }
1451 desc->mRefCount++;
1452 } else {
1453 if (index < 0) {
1454 return;
1455 }
1456 desc = sessionEffects.valueAt(index);
1457 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001458 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001459 sessionEffects.removeItemsAt(index);
1460 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001461 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001462 sessionId);
1463 mSuspendedSessions.removeItem(sessionId);
1464 }
1465 }
1466 }
1467 if (!sessionEffects.isEmpty()) {
1468 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1469 }
1470}
1471
1472void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1473 bool enabled,
1474 int sessionId)
1475{
1476 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001477 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1478}
Eric Laurent59255e42011-07-27 19:49:51 -07001479
Eric Laurenta85a74a2011-10-19 11:44:54 -07001480void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1481 bool enabled,
1482 int sessionId)
1483{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001484 if (mType != RECORD) {
1485 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1486 // another session. This gives the priority to well behaved effect control panels
1487 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001488 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1489 // global effects
1490 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001491 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1492 }
1493 }
Eric Laurent59255e42011-07-27 19:49:51 -07001494
1495 sp<EffectChain> chain = getEffectChain_l(sessionId);
1496 if (chain != 0) {
1497 chain->checkSuspendOnEffectEnabled(effect, enabled);
1498 }
1499}
1500
Mathias Agopian65ab4712010-07-14 17:59:35 -07001501// ----------------------------------------------------------------------------
1502
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001503AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1504 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001505 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001506 uint32_t device,
1507 type_t type)
1508 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001509 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1510 // Assumes constructor is called by AudioFlinger with it's mLock held,
1511 // but it would be safer to explicitly pass initial masterMute as parameter
1512 mMasterMute(audioFlinger->masterMute_l()),
1513 // mStreamTypes[] initialized in constructor body
1514 mOutput(output),
1515 // Assumes constructor is called by AudioFlinger with it's mLock held,
1516 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001517 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001518 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001519 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001520 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001521 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001522 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001523 // index 0 is reserved for normal mixer's submix
1524 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001525{
Glenn Kasten480b4682012-02-28 12:30:08 -08001526 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001527
Mathias Agopian65ab4712010-07-14 17:59:35 -07001528 readOutputParameters();
1529
Glenn Kasten263709e2012-01-06 08:40:01 -08001530 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001531 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1532 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1533 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001534 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1535 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001536 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001537 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1538 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001539}
1540
1541AudioFlinger::PlaybackThread::~PlaybackThread()
1542{
1543 delete [] mMixBuffer;
1544}
1545
1546status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1547{
1548 dumpInternals(fd, args);
1549 dumpTracks(fd, args);
1550 dumpEffectChains(fd, args);
1551 return NO_ERROR;
1552}
1553
1554status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1555{
1556 const size_t SIZE = 256;
1557 char buffer[SIZE];
1558 String8 result;
1559
Glenn Kasten58912562012-04-03 10:45:00 -07001560 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1561 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1562 const stream_type_t *st = &mStreamTypes[i];
1563 if (i > 0) {
1564 result.appendFormat(", ");
1565 }
1566 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1567 if (st->mute) {
1568 result.append("M");
1569 }
1570 }
1571 result.append("\n");
1572 write(fd, result.string(), result.length());
1573 result.clear();
1574
Mathias Agopian65ab4712010-07-14 17:59:35 -07001575 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1576 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001577 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001578 for (size_t i = 0; i < mTracks.size(); ++i) {
1579 sp<Track> track = mTracks[i];
1580 if (track != 0) {
1581 track->dump(buffer, SIZE);
1582 result.append(buffer);
1583 }
1584 }
1585
1586 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1587 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001588 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001589 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001590 sp<Track> track = mActiveTracks[i].promote();
1591 if (track != 0) {
1592 track->dump(buffer, SIZE);
1593 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001594 }
1595 }
1596 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001597
1598 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1599 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1600 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1601 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1602
Mathias Agopian65ab4712010-07-14 17:59:35 -07001603 return NO_ERROR;
1604}
1605
Mathias Agopian65ab4712010-07-14 17:59:35 -07001606status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1607{
1608 const size_t SIZE = 256;
1609 char buffer[SIZE];
1610 String8 result;
1611
1612 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1613 result.append(buffer);
1614 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1615 result.append(buffer);
1616 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1617 result.append(buffer);
1618 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1619 result.append(buffer);
1620 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1621 result.append(buffer);
1622 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1623 result.append(buffer);
1624 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1625 result.append(buffer);
1626 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001627 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001628
1629 dumpBase(fd, args);
1630
1631 return NO_ERROR;
1632}
1633
1634// Thread virtuals
1635status_t AudioFlinger::PlaybackThread::readyToRun()
1636{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001637 status_t status = initCheck();
1638 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001639 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001640 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001641 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001642 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001643 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001644}
1645
1646void AudioFlinger::PlaybackThread::onFirstRef()
1647{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001648 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001649}
1650
1651// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001652sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001653 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001654 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001655 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001656 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001657 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001658 int frameCount,
1659 const sp<IMemory>& sharedBuffer,
1660 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001661 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001662 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001663 status_t *status)
1664{
1665 sp<Track> track;
1666 status_t lStatus;
1667
Glenn Kasten73d22752012-03-19 13:38:30 -07001668 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1669
1670 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001671 if (flags & IAudioFlinger::TRACK_FAST) {
1672 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001673 // not timed
1674 (!isTimed) &&
1675 // either of these use cases:
1676 (
1677 // use case 1: shared buffer with any frame count
1678 (
1679 (sharedBuffer != 0)
1680 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001681 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001682 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001683 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001684 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001685 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001686 )
1687 ) &&
1688 // PCM data
1689 audio_is_linear_pcm(format) &&
1690 // mono or stereo
1691 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1692 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001693#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001694 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001695 (sampleRate == mSampleRate) &&
1696#endif
1697 // normal mixer has an associated fast mixer
1698 hasFastMixer() &&
1699 // there are sufficient fast track slots available
1700 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001701 // FIXME test that MixerThread for this fast track has a capable output HAL
1702 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001703 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001704 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1705 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001706 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001707 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001708 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001709 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001710 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001711 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001712 "mFrameCount=%d format=%d isLinear=%d channelMask=%d sampleRate=%d mSampleRate=%d "
1713 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1714 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1715 audio_is_linear_pcm(format),
1716 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001717 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001718 // For compatibility with AudioTrack calculation, buffer depth is forced
1719 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1720 // This is probably too conservative, but legacy application code may depend on it.
1721 // If you change this calculation, also review the start threshold which is related.
1722 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1723 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1724 if (minBufCount < 2) {
1725 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001726 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001727 int minFrameCount = mNormalFrameCount * minBufCount;
1728 if (frameCount < minFrameCount) {
1729 frameCount = minFrameCount;
1730 }
1731 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001732 }
1733
Mathias Agopian65ab4712010-07-14 17:59:35 -07001734 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001735 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1736 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001737 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001738 "for output %p with format %d",
1739 sampleRate, format, channelMask, mOutput, mFormat);
1740 lStatus = BAD_VALUE;
1741 goto Exit;
1742 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001743 }
1744 } else {
1745 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1746 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001747 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001748 lStatus = BAD_VALUE;
1749 goto Exit;
1750 }
1751 }
1752
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001753 lStatus = initCheck();
1754 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001755 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001756 goto Exit;
1757 }
1758
1759 { // scope for mLock
1760 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001761
1762 // all tracks in same audio session must share the same routing strategy otherwise
1763 // conflicts will happen when tracks are moved from one output to another by audio policy
1764 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001765 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001766 for (size_t i = 0; i < mTracks.size(); ++i) {
1767 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001768 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001769 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001770 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001771 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001772 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001773 lStatus = BAD_VALUE;
1774 goto Exit;
1775 }
1776 }
1777 }
1778
John Grossman4ff14ba2012-02-08 16:37:41 -08001779 if (!isTimed) {
1780 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001781 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001782 } else {
1783 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1784 channelMask, frameCount, sharedBuffer, sessionId);
1785 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001786 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001787 lStatus = NO_MEMORY;
1788 goto Exit;
1789 }
1790 mTracks.add(track);
1791
1792 sp<EffectChain> chain = getEffectChain_l(sessionId);
1793 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001794 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001795 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001796 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001797 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001798 }
1799 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001800
Glenn Kasten3acbd052012-02-28 10:39:56 -08001801 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1802 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1803 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1804 // so ask activity manager to do this on our behalf
1805 int err = requestPriority(callingPid, tid, 1);
1806 if (err != 0) {
1807 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1808 1, callingPid, tid, err);
1809 }
1810 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001811
Mathias Agopian65ab4712010-07-14 17:59:35 -07001812 lStatus = NO_ERROR;
1813
1814Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001815 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001816 *status = lStatus;
1817 }
1818 return track;
1819}
1820
Eric Laurente737cda2012-05-22 18:55:44 -07001821uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1822{
1823 if (mFastMixer != NULL) {
1824 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1825 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1826 }
1827 return latency;
1828}
1829
1830uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1831{
1832 return latency;
1833}
1834
Mathias Agopian65ab4712010-07-14 17:59:35 -07001835uint32_t AudioFlinger::PlaybackThread::latency() const
1836{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001837 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001838 return latency_l();
1839}
1840uint32_t AudioFlinger::PlaybackThread::latency_l() const
1841{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001842 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001843 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001844 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001845 return 0;
1846 }
1847}
1848
Glenn Kasten6637baa2012-01-09 09:40:36 -08001849void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001850{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001851 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001852 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853}
1854
Glenn Kasten6637baa2012-01-09 09:40:36 -08001855void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001857 Mutex::Autolock _l(mLock);
1858 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001859}
1860
Glenn Kasten6637baa2012-01-09 09:40:36 -08001861void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001862{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001863 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001864 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001865}
1866
Glenn Kasten6637baa2012-01-09 09:40:36 -08001867void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001868{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001869 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001870 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001871}
1872
Glenn Kastenfff6d712012-01-12 16:38:12 -08001873float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001874{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001875 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001876 return mStreamTypes[stream].volume;
1877}
1878
Mathias Agopian65ab4712010-07-14 17:59:35 -07001879// addTrack_l() must be called with ThreadBase::mLock held
1880status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1881{
1882 status_t status = ALREADY_EXISTS;
1883
1884 // set retry count for buffer fill
1885 track->mRetryCount = kMaxTrackStartupRetries;
1886 if (mActiveTracks.indexOf(track) < 0) {
1887 // the track is newly added, make sure it fills up all its
1888 // buffers before playing. This is to ensure the client will
1889 // effectively get the latency it requested.
1890 track->mFillingUpStatus = Track::FS_FILLING;
1891 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001892 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001893 mActiveTracks.add(track);
1894 if (track->mainBuffer() != mMixBuffer) {
1895 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1896 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001897 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001898 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001899 }
1900 }
1901
1902 status = NO_ERROR;
1903 }
1904
Steve Block3856b092011-10-20 11:56:00 +01001905 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001906 mWaitWorkCV.broadcast();
1907
1908 return status;
1909}
1910
1911// destroyTrack_l() must be called with ThreadBase::mLock held
1912void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1913{
1914 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001915 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001916 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001917 removeTrack_l(track);
1918 }
1919}
1920
1921void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1922{
Eric Laurent29864602012-05-08 18:57:51 -07001923 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001924 mTracks.remove(track);
1925 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001926 // redundant as track is about to be destroyed, for dumpsys only
1927 track->mName = -1;
1928 if (track->isFastTrack()) {
1929 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001930 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001931 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1932 mFastTrackAvailMask |= 1 << index;
1933 // redundant as track is about to be destroyed, for dumpsys only
1934 track->mFastIndex = -1;
1935 }
Eric Laurentb469b942011-05-09 12:09:06 -07001936 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1937 if (chain != 0) {
1938 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001939 }
1940}
1941
1942String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1943{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001944 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001945 char *s;
1946
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001947 Mutex::Autolock _l(mLock);
1948 if (initCheck() != NO_ERROR) {
1949 return out_s8;
1950 }
1951
Dima Zavin799a70e2011-04-18 16:57:27 -07001952 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001953 out_s8 = String8(s);
1954 free(s);
1955 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001956}
1957
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001958// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001959void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1960 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001961 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001962
Steve Block3856b092011-10-20 11:56:00 +01001963 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001964
1965 switch (event) {
1966 case AudioSystem::OUTPUT_OPENED:
1967 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001968 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001969 desc.samplingRate = mSampleRate;
1970 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001971 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001972 desc.latency = latency();
1973 param2 = &desc;
1974 break;
1975
1976 case AudioSystem::STREAM_CONFIG_CHANGED:
1977 param2 = &param;
1978 case AudioSystem::OUTPUT_CLOSED:
1979 default:
1980 break;
1981 }
1982 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1983}
1984
1985void AudioFlinger::PlaybackThread::readOutputParameters()
1986{
Dima Zavin799a70e2011-04-18 16:57:27 -07001987 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001988 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1989 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001990 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001991 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001992 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001993 if (mFrameCount & 15) {
1994 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1995 mFrameCount);
1996 }
1997
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001998 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07001999 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002000 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002001 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002002 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2003 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2004 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2005 maxNormalFrameCount = maxNormalFrameCount & ~15;
2006 if (maxNormalFrameCount < minNormalFrameCount) {
2007 maxNormalFrameCount = minNormalFrameCount;
2008 }
2009 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2010 if (multiplier <= 1.0) {
2011 multiplier = 1.0;
2012 } else if (multiplier <= 2.0) {
2013 if (2 * mFrameCount <= maxNormalFrameCount) {
2014 multiplier = 2.0;
2015 } else {
2016 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2017 }
2018 } else {
2019 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2020 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2021 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2022 // FIXME this rounding up should not be done if no HAL SRC
2023 uint32_t truncMult = (uint32_t) multiplier;
2024 if ((truncMult & 1)) {
2025 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2026 ++truncMult;
2027 }
2028 }
2029 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002030 }
Glenn Kasten58912562012-04-03 10:45:00 -07002031 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002032 mNormalFrameCount = multiplier * mFrameCount;
2033 // round up to nearest 16 frames to satisfy AudioMixer
2034 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002035 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002036
Glenn Kastene9dd0172012-01-27 18:08:45 -08002037 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002038 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2039 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002040
Eric Laurentde070132010-07-13 04:45:46 -07002041 // force reconfiguration of effect chains and engines to take new buffer size and audio
2042 // parameters into account
2043 // Note that mLock is not held when readOutputParameters() is called from the constructor
2044 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2045 // matter.
2046 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2047 Vector< sp<EffectChain> > effectChains = mEffectChains;
2048 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002049 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002050 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002051}
2052
Eric Laurente737cda2012-05-22 18:55:44 -07002053
Mathias Agopian65ab4712010-07-14 17:59:35 -07002054status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2055{
Glenn Kastena0d68332012-01-27 16:47:15 -08002056 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002057 return BAD_VALUE;
2058 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002059 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002060 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002061 return INVALID_OPERATION;
2062 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002063 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002064
Dima Zavin799a70e2011-04-18 16:57:27 -07002065 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002066}
2067
Eric Laurent39e94f82010-07-28 01:32:47 -07002068uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002069{
2070 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002071 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002072 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002073 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002074 }
2075
2076 for (size_t i = 0; i < mTracks.size(); ++i) {
2077 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002078 if (sessionId == track->sessionId() &&
2079 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002080 result |= TRACK_SESSION;
2081 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002082 }
2083 }
2084
Eric Laurent39e94f82010-07-28 01:32:47 -07002085 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002086}
2087
Eric Laurentde070132010-07-13 04:45:46 -07002088uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2089{
Dima Zavinfce7a472011-04-19 22:30:36 -07002090 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002091 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002092 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2093 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002094 }
2095 for (size_t i = 0; i < mTracks.size(); i++) {
2096 sp<Track> track = mTracks[i];
2097 if (sessionId == track->sessionId() &&
2098 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002099 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002100 }
2101 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002102 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002103}
2104
Mathias Agopian65ab4712010-07-14 17:59:35 -07002105
Glenn Kastenaed850d2012-01-26 09:46:34 -08002106AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002107{
2108 Mutex::Autolock _l(mLock);
2109 return mOutput;
2110}
2111
2112AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2113{
2114 Mutex::Autolock _l(mLock);
2115 AudioStreamOut *output = mOutput;
2116 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002117 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2118 // must push a NULL and wait for ack
2119 mOutputSink.clear();
2120 mPipeSink.clear();
2121 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002122 return output;
2123}
2124
2125// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002126audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002127{
2128 if (mOutput == NULL) {
2129 return NULL;
2130 }
2131 return &mOutput->stream->common;
2132}
2133
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002134uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002135{
Eric Laurentab9071b2012-06-04 13:45:29 -07002136 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002137}
2138
Eric Laurenta011e352012-03-29 15:51:43 -07002139status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2140{
2141 if (!isValidSyncEvent(event)) {
2142 return BAD_VALUE;
2143 }
2144
2145 Mutex::Autolock _l(mLock);
2146
2147 for (size_t i = 0; i < mTracks.size(); ++i) {
2148 sp<Track> track = mTracks[i];
2149 if (event->triggerSession() == track->sessionId()) {
2150 track->setSyncEvent(event);
2151 return NO_ERROR;
2152 }
2153 }
2154
2155 return NAME_NOT_FOUND;
2156}
2157
2158bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2159{
2160 switch (event->type()) {
2161 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2162 return true;
2163 default:
2164 break;
2165 }
2166 return false;
2167}
2168
Eric Laurent44a957f2012-05-15 15:26:05 -07002169void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2170{
2171 size_t count = tracksToRemove.size();
2172 if (CC_UNLIKELY(count)) {
2173 for (size_t i = 0 ; i < count ; i++) {
2174 const sp<Track>& track = tracksToRemove.itemAt(i);
2175 if ((track->sharedBuffer() != 0) &&
2176 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2177 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2178 }
2179 }
2180 }
2181
2182}
2183
Mathias Agopian65ab4712010-07-14 17:59:35 -07002184// ----------------------------------------------------------------------------
2185
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002186AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002187 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002188 : PlaybackThread(audioFlinger, output, id, device, type),
2189 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002190 // mFastMixer below
2191 mFastMixerFutex(0)
2192 // mOutputSink below
2193 // mPipeSink below
2194 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002195{
Glenn Kasten58912562012-04-03 10:45:00 -07002196 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2197 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2198 "mFrameCount=%d, mNormalFrameCount=%d",
2199 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2200 mNormalFrameCount);
2201 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2202
Mathias Agopian65ab4712010-07-14 17:59:35 -07002203 // FIXME - Current mixer implementation only supports stereo output
2204 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002205 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002206 }
Glenn Kasten58912562012-04-03 10:45:00 -07002207
2208 // create an NBAIO sink for the HAL output stream, and negotiate
2209 mOutputSink = new AudioStreamOutSink(output->stream);
2210 size_t numCounterOffers = 0;
2211 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2212 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2213 ALOG_ASSERT(index == 0);
2214
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002215 // initialize fast mixer depending on configuration
2216 bool initFastMixer;
2217 switch (kUseFastMixer) {
2218 case FastMixer_Never:
2219 initFastMixer = false;
2220 break;
2221 case FastMixer_Always:
2222 initFastMixer = true;
2223 break;
2224 case FastMixer_Static:
2225 case FastMixer_Dynamic:
2226 initFastMixer = mFrameCount < mNormalFrameCount;
2227 break;
2228 }
2229 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002230
2231 // create a MonoPipe to connect our submix to FastMixer
2232 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002233 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2234 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2235 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2236 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002237 const NBAIO_Format offers[1] = {format};
2238 size_t numCounterOffers = 0;
2239 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2240 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002241 monoPipe->setAvgFrames((mScreenState & 1) ?
2242 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002243 mPipeSink = monoPipe;
2244
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002245#ifdef TEE_SINK_FRAMES
2246 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2247 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2248 numCounterOffers = 0;
2249 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2250 ALOG_ASSERT(index == 0);
2251 mTeeSink = teeSink;
2252 PipeReader *teeSource = new PipeReader(*teeSink);
2253 numCounterOffers = 0;
2254 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2255 ALOG_ASSERT(index == 0);
2256 mTeeSource = teeSource;
2257#endif
2258
Glenn Kasten58912562012-04-03 10:45:00 -07002259 // create fast mixer and configure it initially with just one fast track for our submix
2260 mFastMixer = new FastMixer();
2261 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002262#ifdef STATE_QUEUE_DUMP
2263 sq->setObserverDump(&mStateQueueObserverDump);
2264 sq->setMutatorDump(&mStateQueueMutatorDump);
2265#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002266 FastMixerState *state = sq->begin();
2267 FastTrack *fastTrack = &state->mFastTracks[0];
2268 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2269 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2270 fastTrack->mVolumeProvider = NULL;
2271 fastTrack->mGeneration++;
2272 state->mFastTracksGen++;
2273 state->mTrackMask = 1;
2274 // fast mixer will use the HAL output sink
2275 state->mOutputSink = mOutputSink.get();
2276 state->mOutputSinkGen++;
2277 state->mFrameCount = mFrameCount;
2278 state->mCommand = FastMixerState::COLD_IDLE;
2279 // already done in constructor initialization list
2280 //mFastMixerFutex = 0;
2281 state->mColdFutexAddr = &mFastMixerFutex;
2282 state->mColdGen++;
2283 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002284 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002285 sq->end();
2286 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2287
2288 // start the fast mixer
2289 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002290 pid_t tid = mFastMixer->getTid();
2291 int err = requestPriority(getpid_cached, tid, 2);
2292 if (err != 0) {
2293 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2294 2, getpid_cached, tid, err);
2295 }
Glenn Kasten58912562012-04-03 10:45:00 -07002296
Glenn Kastenc15d6652012-05-30 14:52:57 -07002297#ifdef AUDIO_WATCHDOG
2298 // create and start the watchdog
2299 mAudioWatchdog = new AudioWatchdog();
2300 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2301 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2302 tid = mAudioWatchdog->getTid();
2303 err = requestPriority(getpid_cached, tid, 1);
2304 if (err != 0) {
2305 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2306 1, getpid_cached, tid, err);
2307 }
2308#endif
2309
Glenn Kasten58912562012-04-03 10:45:00 -07002310 } else {
2311 mFastMixer = NULL;
2312 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002313
2314 switch (kUseFastMixer) {
2315 case FastMixer_Never:
2316 case FastMixer_Dynamic:
2317 mNormalSink = mOutputSink;
2318 break;
2319 case FastMixer_Always:
2320 mNormalSink = mPipeSink;
2321 break;
2322 case FastMixer_Static:
2323 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2324 break;
2325 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002326}
2327
2328AudioFlinger::MixerThread::~MixerThread()
2329{
Glenn Kasten58912562012-04-03 10:45:00 -07002330 if (mFastMixer != NULL) {
2331 FastMixerStateQueue *sq = mFastMixer->sq();
2332 FastMixerState *state = sq->begin();
2333 if (state->mCommand == FastMixerState::COLD_IDLE) {
2334 int32_t old = android_atomic_inc(&mFastMixerFutex);
2335 if (old == -1) {
2336 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2337 }
2338 }
2339 state->mCommand = FastMixerState::EXIT;
2340 sq->end();
2341 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2342 mFastMixer->join();
2343 // Though the fast mixer thread has exited, it's state queue is still valid.
2344 // We'll use that extract the final state which contains one remaining fast track
2345 // corresponding to our sub-mix.
2346 state = sq->begin();
2347 ALOG_ASSERT(state->mTrackMask == 1);
2348 FastTrack *fastTrack = &state->mFastTracks[0];
2349 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2350 delete fastTrack->mBufferProvider;
2351 sq->end(false /*didModify*/);
2352 delete mFastMixer;
Glenn Kastenc15d6652012-05-30 14:52:57 -07002353 if (mAudioWatchdog != 0) {
2354 mAudioWatchdog->requestExit();
2355 mAudioWatchdog->requestExitAndWait();
2356 mAudioWatchdog.clear();
2357 }
Glenn Kasten58912562012-04-03 10:45:00 -07002358 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002359 delete mAudioMixer;
2360}
2361
Glenn Kasten83efdd02012-02-24 07:21:32 -08002362class CpuStats {
2363public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002364 CpuStats();
2365 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002366#ifdef DEBUG_CPU_USAGE
2367private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002368 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2369 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2370
2371 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2372
2373 int mCpuNum; // thread's current CPU number
2374 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002375#endif
2376};
2377
Glenn Kasten190a46f2012-03-06 11:27:10 -08002378CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002379#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002380 : mCpuNum(-1), mCpukHz(-1)
2381#endif
2382{
2383}
2384
2385void CpuStats::sample(const String8 &title) {
2386#ifdef DEBUG_CPU_USAGE
2387 // get current thread's delta CPU time in wall clock ns
2388 double wcNs;
2389 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2390
2391 // record sample for wall clock statistics
2392 if (valid) {
2393 mWcStats.sample(wcNs);
2394 }
2395
2396 // get the current CPU number
2397 int cpuNum = sched_getcpu();
2398
2399 // get the current CPU frequency in kHz
2400 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2401
2402 // check if either CPU number or frequency changed
2403 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2404 mCpuNum = cpuNum;
2405 mCpukHz = cpukHz;
2406 // ignore sample for purposes of cycles
2407 valid = false;
2408 }
2409
2410 // if no change in CPU number or frequency, then record sample for cycle statistics
2411 if (valid && mCpukHz > 0) {
2412 double cycles = wcNs * cpukHz * 0.000001;
2413 mHzStats.sample(cycles);
2414 }
2415
2416 unsigned n = mWcStats.n();
2417 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002418 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002419 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002420 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2421 double perLoop = elapsed / (double) n;
2422 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002423 double perLoop1k = perLoop * 0.001;
2424 double mean = mWcStats.mean();
2425 double stddev = mWcStats.stddev();
2426 double minimum = mWcStats.minimum();
2427 double maximum = mWcStats.maximum();
2428 double meanCycles = mHzStats.mean();
2429 double stddevCycles = mHzStats.stddev();
2430 double minCycles = mHzStats.minimum();
2431 double maxCycles = mHzStats.maximum();
2432 mCpuUsage.resetElapsed();
2433 mWcStats.reset();
2434 mHzStats.reset();
2435 ALOGD("CPU usage for %s over past %.1f secs\n"
2436 " (%u mixer loops at %.1f mean ms per loop):\n"
2437 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2438 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2439 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2440 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002441 elapsed * .000000001, n, perLoop * .000001,
2442 mean * .001,
2443 stddev * .001,
2444 minimum * .001,
2445 maximum * .001,
2446 mean / perLoop100,
2447 stddev / perLoop100,
2448 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002449 maximum / perLoop100,
2450 meanCycles / perLoop1k,
2451 stddevCycles / perLoop1k,
2452 minCycles / perLoop1k,
2453 maxCycles / perLoop1k);
2454
Glenn Kasten83efdd02012-02-24 07:21:32 -08002455 }
2456 }
2457#endif
2458};
2459
Glenn Kasten37d825e2012-02-24 07:21:48 -08002460void AudioFlinger::PlaybackThread::checkSilentMode_l()
2461{
2462 if (!mMasterMute) {
2463 char value[PROPERTY_VALUE_MAX];
2464 if (property_get("ro.audio.silent", value, "0") > 0) {
2465 char *endptr;
2466 unsigned long ul = strtoul(value, &endptr, 0);
2467 if (*endptr == '\0' && ul != 0) {
2468 ALOGD("Silence is golden");
2469 // The setprop command will not allow a property to be changed after
2470 // the first time it is set, so we don't have to worry about un-muting.
2471 setMasterMute_l(true);
2472 }
2473 }
2474 }
2475}
2476
Glenn Kasten000f0e32012-03-01 17:10:56 -08002477bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002478{
2479 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002480
Glenn Kasten000f0e32012-03-01 17:10:56 -08002481 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002482
2483 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002484 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002485
Glenn Kasten000f0e32012-03-01 17:10:56 -08002486 // DUPLICATING
2487 // FIXME could this be made local to while loop?
2488 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002489
Glenn Kasten66fcab92012-02-24 14:59:21 -08002490 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002491 sleepTime = idleSleepTime;
2492
2493if (mType == MIXER) {
2494 sleepTimeShift = 0;
2495}
2496
Glenn Kasten83efdd02012-02-24 07:21:32 -08002497 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002498 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002499
Eric Laurentfeb0db62011-07-22 09:04:31 -07002500 acquireWakeLock();
2501
Mathias Agopian65ab4712010-07-14 17:59:35 -07002502 while (!exitPending())
2503 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002504 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002505
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002506 Vector< sp<EffectChain> > effectChains;
2507
Mathias Agopian65ab4712010-07-14 17:59:35 -07002508 processConfigEvents();
2509
Mathias Agopian65ab4712010-07-14 17:59:35 -07002510 { // scope for mLock
2511
2512 Mutex::Autolock _l(mLock);
2513
2514 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002515 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002516 }
2517
Glenn Kastenfa26a852012-03-06 11:28:04 -08002518 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002519
Mathias Agopian65ab4712010-07-14 17:59:35 -07002520 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002521 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002522 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002523 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002524
2525 threadLoop_standby();
2526
Mathias Agopian65ab4712010-07-14 17:59:35 -07002527 mStandby = true;
2528 mBytesWritten = 0;
2529 }
2530
Glenn Kasten3e074702012-02-28 18:40:35 -08002531 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002532 // we're about to wait, flush the binder command buffer
2533 IPCThreadState::self()->flushCommands();
2534
Glenn Kastenfa26a852012-03-06 11:28:04 -08002535 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002536
Mathias Agopian65ab4712010-07-14 17:59:35 -07002537 if (exitPending()) break;
2538
Eric Laurentfeb0db62011-07-22 09:04:31 -07002539 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002540 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002541 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002542 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002543 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002544 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002545
Eric Laurentda747442012-04-25 18:53:13 -07002546 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002547 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002548
Glenn Kasten37d825e2012-02-24 07:21:48 -08002549 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002550
Glenn Kasten000f0e32012-03-01 17:10:56 -08002551 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002552 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002553 if (mType == MIXER) {
2554 sleepTimeShift = 0;
2555 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002556
Mathias Agopian65ab4712010-07-14 17:59:35 -07002557 continue;
2558 }
2559 }
2560
Glenn Kasten81028042012-04-30 18:15:12 -07002561 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002562 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002563
2564 // prevent any changes in effect chain list and in each effect chain
2565 // during mixing and effect process as the audio buffers could be deleted
2566 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002567 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002568 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002569
Glenn Kastenfec279f2012-03-08 07:47:15 -08002570 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002571 threadLoop_mix();
2572 } else {
2573 threadLoop_sleepTime();
2574 }
2575
2576 if (mSuspended > 0) {
2577 sleepTime = suspendSleepTimeUs();
2578 }
2579
2580 // only process effects if we're going to write
2581 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002582 for (size_t i = 0; i < effectChains.size(); i ++) {
2583 effectChains[i]->process_l();
2584 }
2585 }
2586
2587 // enable changes in effect chain
2588 unlockEffectChains(effectChains);
2589
2590 // sleepTime == 0 means we must write to audio hardware
2591 if (sleepTime == 0) {
2592
2593 threadLoop_write();
2594
2595if (mType == MIXER) {
2596 // write blocked detection
2597 nsecs_t now = systemTime();
2598 nsecs_t delta = now - mLastWriteTime;
2599 if (!mStandby && delta > maxPeriod) {
2600 mNumDelayedWrites++;
2601 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002602#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002603 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002604#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002605 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2606 ns2ms(delta), mNumDelayedWrites, this);
2607 lastWarning = now;
2608 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002609 }
2610}
2611
2612 mStandby = false;
2613 } else {
2614 usleep(sleepTime);
2615 }
2616
Glenn Kasten58912562012-04-03 10:45:00 -07002617 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002618 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002619 // same lock. This will also mutate and push a new fast mixer state.
2620 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002621 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002622
Glenn Kastenfa26a852012-03-06 11:28:04 -08002623 // FIXME I don't understand the need for this here;
2624 // it was in the original code but maybe the
2625 // assignment in saveOutputTracks() makes this unnecessary?
2626 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002627
2628 // Effect chains will be actually deleted here if they were removed from
2629 // mEffectChains list during mixing or effects processing
2630 effectChains.clear();
2631
2632 // FIXME Note that the above .clear() is no longer necessary since effectChains
2633 // is now local to this block, but will keep it for now (at least until merge done).
2634 }
2635
2636if (mType == MIXER || mType == DIRECT) {
2637 // put output stream into standby mode
2638 if (!mStandby) {
2639 mOutput->stream->common.standby(&mOutput->stream->common);
2640 }
2641}
2642if (mType == DUPLICATING) {
2643 // for DuplicatingThread, standby mode is handled by the outputTracks
2644}
2645
2646 releaseWakeLock();
2647
2648 ALOGV("Thread %p type %d exiting", this, mType);
2649 return false;
2650}
2651
Glenn Kasten58912562012-04-03 10:45:00 -07002652void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2653{
Glenn Kasten58912562012-04-03 10:45:00 -07002654 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2655}
2656
2657void AudioFlinger::MixerThread::threadLoop_write()
2658{
2659 // FIXME we should only do one push per cycle; confirm this is true
2660 // Start the fast mixer if it's not already running
2661 if (mFastMixer != NULL) {
2662 FastMixerStateQueue *sq = mFastMixer->sq();
2663 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002664 if (state->mCommand != FastMixerState::MIX_WRITE &&
2665 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002666 if (state->mCommand == FastMixerState::COLD_IDLE) {
2667 int32_t old = android_atomic_inc(&mFastMixerFutex);
2668 if (old == -1) {
2669 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2670 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002671 if (mAudioWatchdog != 0) {
2672 mAudioWatchdog->resume();
2673 }
Glenn Kasten58912562012-04-03 10:45:00 -07002674 }
2675 state->mCommand = FastMixerState::MIX_WRITE;
2676 sq->end();
2677 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002678 if (kUseFastMixer == FastMixer_Dynamic) {
2679 mNormalSink = mPipeSink;
2680 }
Glenn Kasten58912562012-04-03 10:45:00 -07002681 } else {
2682 sq->end(false /*didModify*/);
2683 }
2684 }
2685 PlaybackThread::threadLoop_write();
2686}
2687
Glenn Kasten000f0e32012-03-01 17:10:56 -08002688// shared by MIXER and DIRECT, overridden by DUPLICATING
2689void AudioFlinger::PlaybackThread::threadLoop_write()
2690{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002691 // FIXME rewrite to reduce number of system calls
2692 mLastWriteTime = systemTime();
2693 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002694 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002695
Eric Laurent67c0a582012-05-01 19:31:12 -07002696 // If an NBAIO sink is present, use it to write the normal mixer's submix
2697 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002698#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002699 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002700#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002701 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002702#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002703 // update the setpoint when gScreenState changes
2704 uint32_t screenState = gScreenState;
2705 if (screenState != mScreenState) {
2706 mScreenState = screenState;
2707 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2708 if (pipe != NULL) {
2709 pipe->setAvgFrames((mScreenState & 1) ?
2710 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2711 }
2712 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002713 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002714#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002715 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002716#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002717 if (framesWritten > 0) {
2718 bytesWritten = framesWritten << mBitShift;
2719 } else {
2720 bytesWritten = framesWritten;
2721 }
2722 // otherwise use the HAL / AudioStreamOut directly
2723 } else {
2724 // Direct output thread.
2725 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002726 }
2727
Eric Laurent67c0a582012-05-01 19:31:12 -07002728 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002729 mNumWrites++;
2730 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002731}
2732
Glenn Kasten58912562012-04-03 10:45:00 -07002733void AudioFlinger::MixerThread::threadLoop_standby()
2734{
2735 // Idle the fast mixer if it's currently running
2736 if (mFastMixer != NULL) {
2737 FastMixerStateQueue *sq = mFastMixer->sq();
2738 FastMixerState *state = sq->begin();
2739 if (!(state->mCommand & FastMixerState::IDLE)) {
2740 state->mCommand = FastMixerState::COLD_IDLE;
2741 state->mColdFutexAddr = &mFastMixerFutex;
2742 state->mColdGen++;
2743 mFastMixerFutex = 0;
2744 sq->end();
2745 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2746 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002747 if (kUseFastMixer == FastMixer_Dynamic) {
2748 mNormalSink = mOutputSink;
2749 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002750 if (mAudioWatchdog != 0) {
2751 mAudioWatchdog->pause();
2752 }
Glenn Kasten58912562012-04-03 10:45:00 -07002753 } else {
2754 sq->end(false /*didModify*/);
2755 }
2756 }
2757 PlaybackThread::threadLoop_standby();
2758}
2759
Glenn Kasten000f0e32012-03-01 17:10:56 -08002760// shared by MIXER and DIRECT, overridden by DUPLICATING
2761void AudioFlinger::PlaybackThread::threadLoop_standby()
2762{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002763 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2764 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002765}
2766
2767void AudioFlinger::MixerThread::threadLoop_mix()
2768{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002769 // obtain the presentation timestamp of the next output buffer
2770 int64_t pts;
2771 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002772
Glenn Kasten952eeb22012-03-06 11:30:57 -08002773 if (NULL != mOutput->stream->get_next_write_timestamp) {
2774 status = mOutput->stream->get_next_write_timestamp(
2775 mOutput->stream, &pts);
2776 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002777
Glenn Kasten952eeb22012-03-06 11:30:57 -08002778 if (status != NO_ERROR) {
2779 pts = AudioBufferProvider::kInvalidPTS;
2780 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002781
Glenn Kasten952eeb22012-03-06 11:30:57 -08002782 // mix buffers...
2783 mAudioMixer->process(pts);
2784 // increase sleep time progressively when application underrun condition clears.
2785 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2786 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2787 // such that we would underrun the audio HAL.
2788 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2789 sleepTimeShift--;
2790 }
2791 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002792 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002793 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002794}
2795
2796void AudioFlinger::MixerThread::threadLoop_sleepTime()
2797{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002798 // If no tracks are ready, sleep once for the duration of an output
2799 // buffer size, then write 0s to the output
2800 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002801 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002802 sleepTime = activeSleepTime >> sleepTimeShift;
2803 if (sleepTime < kMinThreadSleepTimeUs) {
2804 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002805 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002806 // reduce sleep time in case of consecutive application underruns to avoid
2807 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2808 // duration we would end up writing less data than needed by the audio HAL if
2809 // the condition persists.
2810 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2811 sleepTimeShift++;
2812 }
2813 } else {
2814 sleepTime = idleSleepTime;
2815 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002816 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002817 memset (mMixBuffer, 0, mixBufferSize);
2818 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002819 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002820 }
2821 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002822}
2823
2824// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002825AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002826 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002827{
2828
Glenn Kasten29c23c32012-01-26 13:37:52 -08002829 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002830 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002831 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002832 size_t mixedTracks = 0;
2833 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002834 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002835 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002836 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002837
2838 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002839 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002840
Eric Laurent571d49c2010-08-11 05:20:11 -07002841 if (masterMute) {
2842 masterVolume = 0;
2843 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002844 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002845 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002846 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002847 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002848 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002849 masterVolume = (float)((v + (1 << 23)) >> 24);
2850 chain.clear();
2851 }
2852
Glenn Kasten288ed212012-04-25 17:52:27 -07002853 // prepare a new state to push
2854 FastMixerStateQueue *sq = NULL;
2855 FastMixerState *state = NULL;
2856 bool didModify = false;
2857 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2858 if (mFastMixer != NULL) {
2859 sq = mFastMixer->sq();
2860 state = sq->begin();
2861 }
2862
Mathias Agopian65ab4712010-07-14 17:59:35 -07002863 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002864 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002865 if (t == 0) continue;
2866
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002867 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002868 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002869
Glenn Kasten288ed212012-04-25 17:52:27 -07002870 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002871 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002872
2873 // It's theoretically possible (though unlikely) for a fast track to be created
2874 // and then removed within the same normal mix cycle. This is not a problem, as
2875 // the track never becomes active so it's fast mixer slot is never touched.
2876 // The converse, of removing an (active) track and then creating a new track
2877 // at the identical fast mixer slot within the same normal mix cycle,
2878 // is impossible because the slot isn't marked available until the end of each cycle.
2879 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002880 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2881 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002882 FastTrack *fastTrack = &state->mFastTracks[j];
2883
2884 // Determine whether the track is currently in underrun condition,
2885 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002886 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2887 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002888 uint32_t recentFull = (underruns.mBitFields.mFull -
2889 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2890 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2891 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2892 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2893 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2894 uint32_t recentUnderruns = recentPartial + recentEmpty;
2895 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002896 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002897 // or stopped which can occur when flush() is called while active
2898 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002899 track->mUnderrunCount += recentUnderruns;
2900 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002901
Glenn Kastend08f48c2012-05-01 18:14:02 -07002902 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002903 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002904 bool isActive = true;
2905 switch (track->mState) {
2906 case TrackBase::STOPPING_1:
2907 // track stays active in STOPPING_1 state until first underrun
2908 if (recentUnderruns > 0) {
2909 track->mState = TrackBase::STOPPING_2;
2910 }
2911 break;
2912 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002913 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002914 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002915 break;
2916 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002917 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002918 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002919 break;
2920 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002921 if (recentFull > 0 || recentPartial > 0) {
2922 // track has provided at least some frames recently: reset retry count
2923 track->mRetryCount = kMaxTrackRetries;
2924 }
2925 if (recentUnderruns == 0) {
2926 // no recent underruns: stay active
2927 break;
2928 }
2929 // there has recently been an underrun of some kind
2930 if (track->sharedBuffer() == 0) {
2931 // were any of the recent underruns "empty" (no frames available)?
2932 if (recentEmpty == 0) {
2933 // no, then ignore the partial underruns as they are allowed indefinitely
2934 break;
2935 }
2936 // there has recently been an "empty" underrun: decrement the retry counter
2937 if (--(track->mRetryCount) > 0) {
2938 break;
2939 }
2940 // indicate to client process that the track was disabled because of underrun;
2941 // it will then automatically call start() when data is available
2942 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2943 // remove from active list, but state remains ACTIVE [confusing but true]
2944 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002945 break;
2946 }
2947 // fall through
2948 case TrackBase::STOPPING_2:
2949 case TrackBase::PAUSED:
2950 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002951 case TrackBase::STOPPED:
2952 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07002953 // Check for presentation complete if track is inactive
2954 // We have consumed all the buffers of this track.
2955 // This would be incomplete if we auto-paused on underrun
2956 {
2957 size_t audioHALFrames =
2958 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2959 size_t framesWritten =
2960 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2961 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2962 // track stays in active list until presentation is complete
2963 break;
2964 }
2965 }
2966 if (track->isStopping_2()) {
2967 track->mState = TrackBase::STOPPED;
2968 }
2969 if (track->isStopped()) {
2970 // Can't reset directly, as fast mixer is still polling this track
2971 // track->reset();
2972 // So instead mark this track as needing to be reset after push with ack
2973 resetMask |= 1 << i;
2974 }
2975 isActive = false;
2976 break;
2977 case TrackBase::IDLE:
2978 default:
2979 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07002980 }
2981
2982 if (isActive) {
2983 // was it previously inactive?
2984 if (!(state->mTrackMask & (1 << j))) {
2985 ExtendedAudioBufferProvider *eabp = track;
2986 VolumeProvider *vp = track;
2987 fastTrack->mBufferProvider = eabp;
2988 fastTrack->mVolumeProvider = vp;
2989 fastTrack->mSampleRate = track->mSampleRate;
2990 fastTrack->mChannelMask = track->mChannelMask;
2991 fastTrack->mGeneration++;
2992 state->mTrackMask |= 1 << j;
2993 didModify = true;
2994 // no acknowledgement required for newly active tracks
2995 }
2996 // cache the combined master volume and stream type volume for fast mixer; this
2997 // lacks any synchronization or barrier so VolumeProvider may read a stale value
2998 track->mCachedVolume = track->isMuted() ?
2999 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3000 ++fastTracks;
3001 } else {
3002 // was it previously active?
3003 if (state->mTrackMask & (1 << j)) {
3004 fastTrack->mBufferProvider = NULL;
3005 fastTrack->mGeneration++;
3006 state->mTrackMask &= ~(1 << j);
3007 didModify = true;
3008 // If any fast tracks were removed, we must wait for acknowledgement
3009 // because we're about to decrement the last sp<> on those tracks.
3010 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003011 } else {
3012 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003013 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003014 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003015 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003016 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003017 }
3018 continue;
3019 }
3020
3021 { // local variable scope to avoid goto warning
3022
Mathias Agopian65ab4712010-07-14 17:59:35 -07003023 audio_track_cblk_t* cblk = track->cblk();
3024
3025 // The first time a track is added we wait
3026 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003027 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003028 // make sure that we have enough frames to mix one full buffer.
3029 // enforce this condition only once to enable draining the buffer in case the client
3030 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003031 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003032 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003033 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003034 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003035 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003036 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003037 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003038 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003039 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003040 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003041 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003042 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003043 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3044 // the minimum track buffer size is normally twice the number of frames necessary
3045 // to fill one buffer and the resampler should not leave more than one buffer worth
3046 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003047 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003048 }
3049 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003050 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003051 !track->isPaused() && !track->isTerminated())
3052 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003053 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003054
3055 mixedTracks++;
3056
3057 // track->mainBuffer() != mMixBuffer means there is an effect chain
3058 // connected to the track
3059 chain.clear();
3060 if (track->mainBuffer() != mMixBuffer) {
3061 chain = getEffectChain_l(track->sessionId());
3062 // Delegate volume control to effect in track effect chain if needed
3063 if (chain != 0) {
3064 tracksWithEffect++;
3065 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003066 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003067 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003068 }
3069 }
3070
3071
3072 int param = AudioMixer::VOLUME;
3073 if (track->mFillingUpStatus == Track::FS_FILLED) {
3074 // no ramp for the first volume setting
3075 track->mFillingUpStatus = Track::FS_ACTIVE;
3076 if (track->mState == TrackBase::RESUMING) {
3077 track->mState = TrackBase::ACTIVE;
3078 param = AudioMixer::RAMP_VOLUME;
3079 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003080 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003081 } else if (cblk->server != 0) {
3082 // If the track is stopped before the first frame was mixed,
3083 // do not apply ramp
3084 param = AudioMixer::RAMP_VOLUME;
3085 }
3086
3087 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003088 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003089 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003090 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003091 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003092 if (track->isPausing()) {
3093 track->setPaused();
3094 }
3095 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003096
Mathias Agopian65ab4712010-07-14 17:59:35 -07003097 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003098 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003099 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003100 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003101 vl = vlr & 0xFFFF;
3102 vr = vlr >> 16;
3103 // track volumes come from shared memory, so can't be trusted and must be clamped
3104 if (vl > MAX_GAIN_INT) {
3105 ALOGV("Track left volume out of range: %04X", vl);
3106 vl = MAX_GAIN_INT;
3107 }
3108 if (vr > MAX_GAIN_INT) {
3109 ALOGV("Track right volume out of range: %04X", vr);
3110 vr = MAX_GAIN_INT;
3111 }
3112 // now apply the master volume and stream type volume
3113 vl = (uint32_t)(v * vl) << 12;
3114 vr = (uint32_t)(v * vr) << 12;
3115 // assuming master volume and stream type volume each go up to 1.0,
3116 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003117
Glenn Kasten05632a52012-01-03 14:22:33 -08003118 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3119 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003120 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003121 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003122 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003123 }
3124 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003125 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003126 // Delegate volume control to effect in track effect chain if needed
3127 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3128 // Do not ramp volume if volume is controlled by effect
3129 param = AudioMixer::VOLUME;
3130 track->mHasVolumeController = true;
3131 } else {
3132 // force no volume ramp when volume controller was just disabled or removed
3133 // from effect chain to avoid volume spike
3134 if (track->mHasVolumeController) {
3135 param = AudioMixer::VOLUME;
3136 }
3137 track->mHasVolumeController = false;
3138 }
3139
3140 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003141 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003142 vl = (vl + (1 << 11)) >> 12;
3143 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3144 vr = (vr + (1 << 11)) >> 12;
3145 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003146
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003147 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 -07003148
Mathias Agopian65ab4712010-07-14 17:59:35 -07003149 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003150 mAudioMixer->setBufferProvider(name, track);
3151 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003152
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003153 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3154 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3155 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003156 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003157 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003158 AudioMixer::TRACK,
3159 AudioMixer::FORMAT, (void *)track->format());
3160 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003161 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003162 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003163 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003164 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003165 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003166 AudioMixer::RESAMPLE,
3167 AudioMixer::SAMPLE_RATE,
3168 (void *)(cblk->sampleRate));
3169 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003170 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003171 AudioMixer::TRACK,
3172 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3173 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003174 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003175 AudioMixer::TRACK,
3176 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3177
3178 // reset retry count
3179 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003180
Eric Laurent27741442012-01-17 19:20:12 -08003181 // If one track is ready, set the mixer ready if:
3182 // - the mixer was not ready during previous round OR
3183 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003184 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003185 mixerStatus != MIXER_TRACKS_ENABLED) {
3186 mixerStatus = MIXER_TRACKS_READY;
3187 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003188 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003189 // clear effect chain input buffer if an active track underruns to avoid sending
3190 // previous audio buffer again to effects
3191 chain = getEffectChain_l(track->sessionId());
3192 if (chain != 0) {
3193 chain->clearInputBuffer();
3194 }
3195
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003196 //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 -07003197 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3198 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003199 // We have consumed all the buffers of this track.
3200 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003201 // TODO: use actual buffer filling status instead of latency when available from
3202 // audio HAL
3203 size_t audioHALFrames =
3204 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3205 size_t framesWritten =
3206 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3207 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003208 if (track->isStopped()) {
3209 track->reset();
3210 }
Eric Laurenta011e352012-03-29 15:51:43 -07003211 tracksToRemove->add(track);
3212 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003213 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003214 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003215 // No buffers for this track. Give it a few chances to
3216 // fill a buffer, then remove it from active list.
3217 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003218 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003219 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003220 // indicate to client process that the track was disabled because of underrun;
3221 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003222 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003223 // If one track is not ready, mark the mixer also not ready if:
3224 // - the mixer was ready during previous round OR
3225 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003226 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003227 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003228 mixerStatus = MIXER_TRACKS_ENABLED;
3229 }
3230 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003231 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003232 }
Glenn Kasten58912562012-04-03 10:45:00 -07003233
3234 } // local variable scope to avoid goto warning
3235track_is_ready: ;
3236
Mathias Agopian65ab4712010-07-14 17:59:35 -07003237 }
3238
Glenn Kasten288ed212012-04-25 17:52:27 -07003239 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003240 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003241 if (didModify) {
3242 state->mFastTracksGen++;
3243 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3244 if (kUseFastMixer == FastMixer_Dynamic &&
3245 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3246 state->mCommand = FastMixerState::COLD_IDLE;
3247 state->mColdFutexAddr = &mFastMixerFutex;
3248 state->mColdGen++;
3249 mFastMixerFutex = 0;
3250 if (kUseFastMixer == FastMixer_Dynamic) {
3251 mNormalSink = mOutputSink;
3252 }
3253 // If we go into cold idle, need to wait for acknowledgement
3254 // so that fast mixer stops doing I/O.
3255 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003256 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003257 }
3258 sq->end();
3259 }
3260 if (sq != NULL) {
3261 sq->end(didModify);
3262 sq->push(block);
3263 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07003264 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3265 mAudioWatchdog->pause();
3266 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003267
3268 // Now perform the deferred reset on fast tracks that have stopped
3269 while (resetMask != 0) {
3270 size_t i = __builtin_ctz(resetMask);
3271 ALOG_ASSERT(i < count);
3272 resetMask &= ~(1 << i);
3273 sp<Track> t = mActiveTracks[i].promote();
3274 if (t == 0) continue;
3275 Track* track = t.get();
3276 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3277 track->reset();
3278 }
Glenn Kasten58912562012-04-03 10:45:00 -07003279
Mathias Agopian65ab4712010-07-14 17:59:35 -07003280 // remove all the tracks that need to be...
3281 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003282 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003283 for (size_t i=0 ; i<count ; i++) {
3284 const sp<Track>& track = tracksToRemove->itemAt(i);
3285 mActiveTracks.remove(track);
3286 if (track->mainBuffer() != mMixBuffer) {
3287 chain = getEffectChain_l(track->sessionId());
3288 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003289 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003290 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003291 }
3292 }
3293 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003294 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003295 }
3296 }
3297 }
3298
3299 // mix buffer must be cleared if all tracks are connected to an
3300 // effect chain as in this case the mixer will not write to
3301 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003302 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3303 // FIXME as a performance optimization, should remember previous zero status
3304 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003305 }
3306
Glenn Kasten58912562012-04-03 10:45:00 -07003307 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003308 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003309 if (fastTracks > 0) {
3310 mixerStatus = MIXER_TRACKS_READY;
3311 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003312 return mixerStatus;
3313}
3314
Glenn Kasten66fcab92012-02-24 14:59:21 -08003315/*
3316The derived values that are cached:
3317 - mixBufferSize from frame count * frame size
3318 - activeSleepTime from activeSleepTimeUs()
3319 - idleSleepTime from idleSleepTimeUs()
3320 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3321 - maxPeriod from frame count and sample rate (MIXER only)
3322
3323The parameters that affect these derived values are:
3324 - frame count
3325 - frame size
3326 - sample rate
3327 - device type: A2DP or not
3328 - device latency
3329 - format: PCM or not
3330 - active sleep time
3331 - idle sleep time
3332*/
3333
3334void AudioFlinger::PlaybackThread::cacheParameters_l()
3335{
Glenn Kasten58912562012-04-03 10:45:00 -07003336 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003337 activeSleepTime = activeSleepTimeUs();
3338 idleSleepTime = idleSleepTimeUs();
3339}
3340
Eric Laurent22167852012-06-20 12:26:32 -07003341void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003342{
Steve Block3856b092011-10-20 11:56:00 +01003343 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003344 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003345 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003346
Mathias Agopian65ab4712010-07-14 17:59:35 -07003347 size_t size = mTracks.size();
3348 for (size_t i = 0; i < size; i++) {
3349 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003350 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003351 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003352 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003353 }
3354 }
3355}
3356
Mathias Agopian65ab4712010-07-14 17:59:35 -07003357// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003358int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003359{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003360 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003361}
3362
3363// deleteTrackName_l() must be called with ThreadBase::mLock held
3364void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3365{
Steve Block3856b092011-10-20 11:56:00 +01003366 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003367 mAudioMixer->deleteTrackName(name);
3368}
3369
3370// checkForNewParameters_l() must be called with ThreadBase::mLock held
3371bool AudioFlinger::MixerThread::checkForNewParameters_l()
3372{
Glenn Kasten58912562012-04-03 10:45:00 -07003373 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3374 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003375 bool reconfig = false;
3376
3377 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003378
3379 if (mFastMixer != NULL) {
3380 FastMixerStateQueue *sq = mFastMixer->sq();
3381 FastMixerState *state = sq->begin();
3382 if (!(state->mCommand & FastMixerState::IDLE)) {
3383 previousCommand = state->mCommand;
3384 state->mCommand = FastMixerState::HOT_IDLE;
3385 sq->end();
3386 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3387 } else {
3388 sq->end(false /*didModify*/);
3389 }
3390 }
3391
Mathias Agopian65ab4712010-07-14 17:59:35 -07003392 status_t status = NO_ERROR;
3393 String8 keyValuePair = mNewParameters[0];
3394 AudioParameter param = AudioParameter(keyValuePair);
3395 int value;
3396
3397 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3398 reconfig = true;
3399 }
3400 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003401 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003402 status = BAD_VALUE;
3403 } else {
3404 reconfig = true;
3405 }
3406 }
3407 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003408 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003409 status = BAD_VALUE;
3410 } else {
3411 reconfig = true;
3412 }
3413 }
3414 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3415 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003416 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003417 // if frame count is changed after track creation
3418 if (!mTracks.isEmpty()) {
3419 status = INVALID_OPERATION;
3420 } else {
3421 reconfig = true;
3422 }
3423 }
3424 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003425#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003426 // when changing the audio output device, call addBatteryData to notify
3427 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003428 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003429 uint32_t params = 0;
3430 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003431 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003432 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3433 }
3434
3435 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003436 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003437 // check if any other device (except speaker) is on
3438 if (value & deviceWithoutSpeaker ) {
3439 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3440 }
3441
3442 if (params != 0) {
3443 addBatteryData(params);
3444 }
3445 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003446#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003447
Mathias Agopian65ab4712010-07-14 17:59:35 -07003448 // forward device change to effects that have requested to be
3449 // aware of attached audio device.
Glenn Kasten94479fd2012-07-09 15:39:54 -07003450 mDevice = (audio_devices_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003451 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003452 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003453 }
3454 }
3455
3456 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003457 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003458 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003459 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003460 mOutput->stream->common.standby(&mOutput->stream->common);
3461 mStandby = true;
3462 mBytesWritten = 0;
3463 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003464 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003465 }
3466 if (status == NO_ERROR && reconfig) {
3467 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003468 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3469 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003470 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003471 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003472 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003473 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003474 if (name < 0) break;
3475 mTracks[i]->mName = name;
3476 // limit track sample rate to 2 x new output sample rate
3477 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3478 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3479 }
3480 }
3481 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3482 }
3483 }
3484
3485 mNewParameters.removeAt(0);
3486
3487 mParamStatus = status;
3488 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003489 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3490 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003491 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003492 }
Glenn Kasten58912562012-04-03 10:45:00 -07003493
3494 if (!(previousCommand & FastMixerState::IDLE)) {
3495 ALOG_ASSERT(mFastMixer != NULL);
3496 FastMixerStateQueue *sq = mFastMixer->sq();
3497 FastMixerState *state = sq->begin();
3498 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3499 state->mCommand = previousCommand;
3500 sq->end();
3501 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3502 }
3503
Mathias Agopian65ab4712010-07-14 17:59:35 -07003504 return reconfig;
3505}
3506
3507status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3508{
3509 const size_t SIZE = 256;
3510 char buffer[SIZE];
3511 String8 result;
3512
3513 PlaybackThread::dumpInternals(fd, args);
3514
3515 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3516 result.append(buffer);
3517 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003518
3519 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3520 FastMixerDumpState copy = mFastMixerDumpState;
3521 copy.dump(fd);
3522
Glenn Kasten39993082012-05-31 13:40:27 -07003523#ifdef STATE_QUEUE_DUMP
3524 // Similar for state queue
3525 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3526 observerCopy.dump(fd);
3527 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3528 mutatorCopy.dump(fd);
3529#endif
3530
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003531 // Write the tee output to a .wav file
3532 NBAIO_Source *teeSource = mTeeSource.get();
3533 if (teeSource != NULL) {
3534 char teePath[64];
3535 struct timeval tv;
3536 gettimeofday(&tv, NULL);
3537 struct tm tm;
3538 localtime_r(&tv.tv_sec, &tm);
3539 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3540 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3541 if (teeFd >= 0) {
3542 char wavHeader[44];
3543 memcpy(wavHeader,
3544 "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",
3545 sizeof(wavHeader));
3546 NBAIO_Format format = teeSource->format();
3547 unsigned channelCount = Format_channelCount(format);
3548 ALOG_ASSERT(channelCount <= FCC_2);
3549 unsigned sampleRate = Format_sampleRate(format);
3550 wavHeader[22] = channelCount; // number of channels
3551 wavHeader[24] = sampleRate; // sample rate
3552 wavHeader[25] = sampleRate >> 8;
3553 wavHeader[32] = channelCount * 2; // block alignment
3554 write(teeFd, wavHeader, sizeof(wavHeader));
3555 size_t total = 0;
3556 bool firstRead = true;
3557 for (;;) {
3558#define TEE_SINK_READ 1024
3559 short buffer[TEE_SINK_READ * FCC_2];
3560 size_t count = TEE_SINK_READ;
3561 ssize_t actual = teeSource->read(buffer, count);
3562 bool wasFirstRead = firstRead;
3563 firstRead = false;
3564 if (actual <= 0) {
3565 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3566 continue;
3567 }
3568 break;
3569 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003570 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003571 write(teeFd, buffer, actual * channelCount * sizeof(short));
3572 total += actual;
3573 }
3574 lseek(teeFd, (off_t) 4, SEEK_SET);
3575 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3576 write(teeFd, &temp, sizeof(temp));
3577 lseek(teeFd, (off_t) 40, SEEK_SET);
3578 temp = total * channelCount * sizeof(short);
3579 write(teeFd, &temp, sizeof(temp));
3580 close(teeFd);
3581 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3582 } else {
3583 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3584 }
3585 }
3586
Glenn Kastenc15d6652012-05-30 14:52:57 -07003587 if (mAudioWatchdog != 0) {
3588 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3589 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3590 wdCopy.dump(fd);
3591 }
3592
Mathias Agopian65ab4712010-07-14 17:59:35 -07003593 return NO_ERROR;
3594}
3595
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003596uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003597{
Glenn Kasten58912562012-04-03 10:45:00 -07003598 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003599}
3600
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003601uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003602{
Glenn Kasten58912562012-04-03 10:45:00 -07003603 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003604}
3605
Glenn Kasten66fcab92012-02-24 14:59:21 -08003606void AudioFlinger::MixerThread::cacheParameters_l()
3607{
3608 PlaybackThread::cacheParameters_l();
3609
3610 // FIXME: Relaxed timing because of a certain device that can't meet latency
3611 // Should be reduced to 2x after the vendor fixes the driver issue
3612 // increase threshold again due to low power audio mode. The way this warning
3613 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003614 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003615}
3616
Mathias Agopian65ab4712010-07-14 17:59:35 -07003617// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003618AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3619 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003620 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003621 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003622{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003623}
3624
3625AudioFlinger::DirectOutputThread::~DirectOutputThread()
3626{
3627}
3628
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003629AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3630 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003631)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003632{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003633 sp<Track> trackToRemove;
3634
Glenn Kastenfec279f2012-03-08 07:47:15 -08003635 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003636
Glenn Kasten952eeb22012-03-06 11:30:57 -08003637 // find out which tracks need to be processed
3638 if (mActiveTracks.size() != 0) {
3639 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003640 // The track died recently
3641 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003642
Glenn Kasten952eeb22012-03-06 11:30:57 -08003643 Track* const track = t.get();
3644 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003645
Glenn Kasten952eeb22012-03-06 11:30:57 -08003646 // The first time a track is added we wait
3647 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003648 uint32_t minFrames;
3649 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3650 minFrames = mNormalFrameCount;
3651 } else {
3652 minFrames = 1;
3653 }
3654 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003655 !track->isPaused() && !track->isTerminated())
3656 {
3657 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003658
Glenn Kasten952eeb22012-03-06 11:30:57 -08003659 if (track->mFillingUpStatus == Track::FS_FILLED) {
3660 track->mFillingUpStatus = Track::FS_ACTIVE;
3661 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003662 if (track->mState == TrackBase::RESUMING) {
3663 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003664 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003665 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003666
Glenn Kasten952eeb22012-03-06 11:30:57 -08003667 // compute volume for this track
3668 float left, right;
3669 if (track->isMuted() || mMasterMute || track->isPausing() ||
3670 mStreamTypes[track->streamType()].mute) {
3671 left = right = 0;
3672 if (track->isPausing()) {
3673 track->setPaused();
3674 }
3675 } else {
3676 float typeVolume = mStreamTypes[track->streamType()].volume;
3677 float v = mMasterVolume * typeVolume;
3678 uint32_t vlr = cblk->getVolumeLR();
3679 float v_clamped = v * (vlr & 0xFFFF);
3680 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3681 left = v_clamped/MAX_GAIN;
3682 v_clamped = v * (vlr >> 16);
3683 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3684 right = v_clamped/MAX_GAIN;
3685 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003686
Glenn Kasten952eeb22012-03-06 11:30:57 -08003687 if (left != mLeftVolFloat || right != mRightVolFloat) {
3688 mLeftVolFloat = left;
3689 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003690
Glenn Kasten952eeb22012-03-06 11:30:57 -08003691 // Convert volumes from float to 8.24
3692 uint32_t vl = (uint32_t)(left * (1 << 24));
3693 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003694
Glenn Kasten952eeb22012-03-06 11:30:57 -08003695 // Delegate volume control to effect in track effect chain if needed
3696 // only one effect chain can be present on DirectOutputThread, so if
3697 // there is one, the track is connected to it
3698 if (!mEffectChains.isEmpty()) {
3699 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003700 mEffectChains[0]->setVolume_l(&vl, &vr);
3701 left = (float)vl / (1 << 24);
3702 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003703 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003704 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003705 }
3706
3707 // reset retry count
3708 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003709 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003710 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003711 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003712 // clear effect chain input buffer if an active track underruns to avoid sending
3713 // previous audio buffer again to effects
3714 if (!mEffectChains.isEmpty()) {
3715 mEffectChains[0]->clearInputBuffer();
3716 }
3717
Glenn Kasten952eeb22012-03-06 11:30:57 -08003718 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurent67c0a582012-05-01 19:31:12 -07003719 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3720 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003721 // We have consumed all the buffers of this track.
3722 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003723 // TODO: implement behavior for compressed audio
3724 size_t audioHALFrames =
3725 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3726 size_t framesWritten =
3727 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3728 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003729 if (track->isStopped()) {
3730 track->reset();
3731 }
Eric Laurenta011e352012-03-29 15:51:43 -07003732 trackToRemove = track;
3733 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003734 } else {
3735 // No buffers for this track. Give it a few chances to
3736 // fill a buffer, then remove it from active list.
3737 if (--(track->mRetryCount) <= 0) {
3738 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3739 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003740 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003741 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003742 }
3743 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003744 }
3745 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003746
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003747 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003748 // remove all the tracks that need to be...
3749 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003750 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003751 mActiveTracks.remove(trackToRemove);
3752 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003753 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003754 trackToRemove->sessionId());
3755 mEffectChains[0]->decActiveTrackCnt();
3756 }
3757 if (trackToRemove->isTerminated()) {
3758 removeTrack_l(trackToRemove);
3759 }
3760 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003761
Glenn Kastenfec279f2012-03-08 07:47:15 -08003762 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003763}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003764
Glenn Kasten000f0e32012-03-01 17:10:56 -08003765void AudioFlinger::DirectOutputThread::threadLoop_mix()
3766{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003767 AudioBufferProvider::Buffer buffer;
3768 size_t frameCount = mFrameCount;
3769 int8_t *curBuf = (int8_t *)mMixBuffer;
3770 // output audio to hardware
3771 while (frameCount) {
3772 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003773 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003774 if (CC_UNLIKELY(buffer.raw == NULL)) {
3775 memset(curBuf, 0, frameCount * mFrameSize);
3776 break;
3777 }
3778 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3779 frameCount -= buffer.frameCount;
3780 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003781 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003782 }
3783 sleepTime = 0;
3784 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003785 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003786
Glenn Kasten000f0e32012-03-01 17:10:56 -08003787}
3788
3789void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3790{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003791 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003792 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003793 sleepTime = activeSleepTime;
3794 } else {
3795 sleepTime = idleSleepTime;
3796 }
3797 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003798 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003799 sleepTime = 0;
3800 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003801}
3802
3803// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003804int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003805{
3806 return 0;
3807}
3808
3809// deleteTrackName_l() must be called with ThreadBase::mLock held
3810void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3811{
3812}
3813
3814// checkForNewParameters_l() must be called with ThreadBase::mLock held
3815bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3816{
3817 bool reconfig = false;
3818
3819 while (!mNewParameters.isEmpty()) {
3820 status_t status = NO_ERROR;
3821 String8 keyValuePair = mNewParameters[0];
3822 AudioParameter param = AudioParameter(keyValuePair);
3823 int value;
3824
3825 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3826 // do not accept frame count changes if tracks are open as the track buffer
3827 // size depends on frame count and correct behavior would not be garantied
3828 // if frame count is changed after track creation
3829 if (!mTracks.isEmpty()) {
3830 status = INVALID_OPERATION;
3831 } else {
3832 reconfig = true;
3833 }
3834 }
3835 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003836 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003837 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003838 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003839 mOutput->stream->common.standby(&mOutput->stream->common);
3840 mStandby = true;
3841 mBytesWritten = 0;
3842 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003843 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003844 }
3845 if (status == NO_ERROR && reconfig) {
3846 readOutputParameters();
3847 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3848 }
3849 }
3850
3851 mNewParameters.removeAt(0);
3852
3853 mParamStatus = status;
3854 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003855 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3856 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003857 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003858 }
3859 return reconfig;
3860}
3861
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003862uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003863{
3864 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003865 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003866 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003867 } else {
3868 time = 10000;
3869 }
3870 return time;
3871}
3872
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003873uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003874{
3875 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003876 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003877 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003878 } else {
3879 time = 10000;
3880 }
3881 return time;
3882}
3883
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003884uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003885{
3886 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003887 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003888 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3889 } else {
3890 time = 10000;
3891 }
3892 return time;
3893}
3894
Glenn Kasten66fcab92012-02-24 14:59:21 -08003895void AudioFlinger::DirectOutputThread::cacheParameters_l()
3896{
3897 PlaybackThread::cacheParameters_l();
3898
3899 // use shorter standby delay as on normal output to release
3900 // hardware resources as soon as possible
3901 standbyDelay = microseconds(activeSleepTime*2);
3902}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003903
Mathias Agopian65ab4712010-07-14 17:59:35 -07003904// ----------------------------------------------------------------------------
3905
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003906AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003907 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003908 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3909 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003910{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003911 addOutputTrack(mainThread);
3912}
3913
3914AudioFlinger::DuplicatingThread::~DuplicatingThread()
3915{
3916 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3917 mOutputTracks[i]->destroy();
3918 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003919}
3920
Glenn Kasten000f0e32012-03-01 17:10:56 -08003921void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003922{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003923 // mix buffers...
3924 if (outputsReady(outputTracks)) {
3925 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3926 } else {
3927 memset(mMixBuffer, 0, mixBufferSize);
3928 }
3929 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003930 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003931 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003932}
3933
3934void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3935{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003936 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003937 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003938 sleepTime = activeSleepTime;
3939 } else {
3940 sleepTime = idleSleepTime;
3941 }
3942 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003943 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3944 writeFrames = mNormalFrameCount;
3945 memset(mMixBuffer, 0, mixBufferSize);
3946 } else {
3947 // flush remaining overflow buffers in output tracks
3948 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003949 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003950 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003951 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003952}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003953
Glenn Kasten000f0e32012-03-01 17:10:56 -08003954void AudioFlinger::DuplicatingThread::threadLoop_write()
3955{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003956 for (size_t i = 0; i < outputTracks.size(); i++) {
3957 outputTracks[i]->write(mMixBuffer, writeFrames);
3958 }
3959 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003960}
Glenn Kasten688a6402012-02-29 07:57:06 -08003961
Glenn Kasten000f0e32012-03-01 17:10:56 -08003962void AudioFlinger::DuplicatingThread::threadLoop_standby()
3963{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003964 // DuplicatingThread implements standby by stopping all tracks
3965 for (size_t i = 0; i < outputTracks.size(); i++) {
3966 outputTracks[i]->stop();
3967 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003968}
3969
Glenn Kastenfa26a852012-03-06 11:28:04 -08003970void AudioFlinger::DuplicatingThread::saveOutputTracks()
3971{
3972 outputTracks = mOutputTracks;
3973}
3974
3975void AudioFlinger::DuplicatingThread::clearOutputTracks()
3976{
3977 outputTracks.clear();
3978}
3979
Mathias Agopian65ab4712010-07-14 17:59:35 -07003980void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3981{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003982 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003983 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07003984 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003985 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003986 this,
3987 mSampleRate,
3988 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003989 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003990 frameCount);
3991 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003992 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003993 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003994 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003995 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003996 }
3997}
3998
3999void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4000{
4001 Mutex::Autolock _l(mLock);
4002 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004003 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004004 mOutputTracks[i]->destroy();
4005 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004006 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004007 return;
4008 }
4009 }
Steve Block3856b092011-10-20 11:56:00 +01004010 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004011}
4012
Glenn Kasten438b0362012-03-06 11:24:48 -08004013// caller must hold mLock
4014void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004015{
4016 mWaitTimeMs = UINT_MAX;
4017 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4018 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004019 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004020 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4021 if (waitTimeMs < mWaitTimeMs) {
4022 mWaitTimeMs = waitTimeMs;
4023 }
4024 }
4025 }
4026}
4027
4028
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004029bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004030{
4031 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004032 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004033 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004034 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004035 return false;
4036 }
4037 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004038 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004039 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004040 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004041 return false;
4042 }
4043 }
4044 return true;
4045}
4046
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004047uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004048{
4049 return (mWaitTimeMs * 1000) / 2;
4050}
4051
Glenn Kasten66fcab92012-02-24 14:59:21 -08004052void AudioFlinger::DuplicatingThread::cacheParameters_l()
4053{
4054 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4055 updateWaitTime_l();
4056
4057 MixerThread::cacheParameters_l();
4058}
4059
Mathias Agopian65ab4712010-07-14 17:59:35 -07004060// ----------------------------------------------------------------------------
4061
4062// TrackBase constructor must be called with AudioFlinger::mLock held
4063AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004064 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004065 const sp<Client>& client,
4066 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004067 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004068 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004069 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004070 const sp<IMemory>& sharedBuffer,
4071 int sessionId)
4072 : RefBase(),
4073 mThread(thread),
4074 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004075 mCblk(NULL),
4076 // mBuffer
4077 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004078 mFrameCount(0),
4079 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004080 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004081 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004082 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004083 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004084 // mChannelCount
4085 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004086{
Steve Block3856b092011-10-20 11:56:00 +01004087 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004088
Steve Blockb8a80522011-12-20 16:23:08 +00004089 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004090 size_t size = sizeof(audio_track_cblk_t);
4091 uint8_t channelCount = popcount(channelMask);
4092 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4093 if (sharedBuffer == 0) {
4094 size += bufferSize;
4095 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004096
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004097 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004098 mCblkMemory = client->heap()->allocate(size);
4099 if (mCblkMemory != 0) {
4100 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004101 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004102 new(mCblk) audio_track_cblk_t();
4103 // clear all buffers
4104 mCblk->frameCount = frameCount;
4105 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004106// uncomment the following lines to quickly test 32-bit wraparound
4107// mCblk->user = 0xffff0000;
4108// mCblk->server = 0xffff0000;
4109// mCblk->userBase = 0xffff0000;
4110// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004111 mChannelCount = channelCount;
4112 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004113 if (sharedBuffer == 0) {
4114 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4115 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4116 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004117 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004118 mCblk->flags = CBLK_UNDERRUN_ON;
4119 } else {
4120 mBuffer = sharedBuffer->pointer();
4121 }
4122 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4123 }
4124 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004125 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004126 client->heap()->dump("AudioTrack");
4127 return;
4128 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004129 } else {
4130 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004131 // construct the shared structure in-place.
4132 new(mCblk) audio_track_cblk_t();
4133 // clear all buffers
4134 mCblk->frameCount = frameCount;
4135 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004136// uncomment the following lines to quickly test 32-bit wraparound
4137// mCblk->user = 0xffff0000;
4138// mCblk->server = 0xffff0000;
4139// mCblk->userBase = 0xffff0000;
4140// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004141 mChannelCount = channelCount;
4142 mChannelMask = channelMask;
4143 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4144 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4145 // Force underrun condition to avoid false underrun callback until first data is
4146 // written to buffer (other flags are cleared)
4147 mCblk->flags = CBLK_UNDERRUN_ON;
4148 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004149 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004150}
4151
4152AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4153{
Glenn Kastena0d68332012-01-27 16:47:15 -08004154 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004155 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004156 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004157 } else {
4158 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004159 }
4160 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004161 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004162 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004163 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004164 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004165 // If the client's reference count drops to zero, the associated destructor
4166 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4167 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004168 mClient.clear();
4169 }
4170}
4171
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004172// AudioBufferProvider interface
4173// getNextBuffer() = 0;
4174// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004175void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4176{
Glenn Kastene0feee32011-12-13 11:53:26 -08004177 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004178 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004179 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004180 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004181 buffer->frameCount = 0;
4182}
4183
4184bool AudioFlinger::ThreadBase::TrackBase::step() {
4185 bool result;
4186 audio_track_cblk_t* cblk = this->cblk();
4187
4188 result = cblk->stepServer(mFrameCount);
4189 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004190 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004191 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004192 }
4193 return result;
4194}
4195
4196void AudioFlinger::ThreadBase::TrackBase::reset() {
4197 audio_track_cblk_t* cblk = this->cblk();
4198
4199 cblk->user = 0;
4200 cblk->server = 0;
4201 cblk->userBase = 0;
4202 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004203 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004204 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004205}
4206
Mathias Agopian65ab4712010-07-14 17:59:35 -07004207int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4208 return (int)mCblk->sampleRate;
4209}
4210
Mathias Agopian65ab4712010-07-14 17:59:35 -07004211void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4212 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004213 size_t frameSize = cblk->frameSize;
4214 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4215 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004216
4217 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004218 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4219 "TrackBase::getBuffer buffer out of range:\n"
4220 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4221 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004222 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004223 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004224
4225 return bufferStart;
4226}
4227
Eric Laurenta011e352012-03-29 15:51:43 -07004228status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4229{
4230 mSyncEvents.add(event);
4231 return NO_ERROR;
4232}
4233
Mathias Agopian65ab4712010-07-14 17:59:35 -07004234// ----------------------------------------------------------------------------
4235
4236// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4237AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004238 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004239 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004240 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004241 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004242 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004243 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004244 int frameCount,
4245 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004246 int sessionId,
4247 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004248 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004249 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004250 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004251 // mRetryCount initialized later when needed
4252 mSharedBuffer(sharedBuffer),
4253 mStreamType(streamType),
4254 mName(-1), // see note below
4255 mMainBuffer(thread->mixBuffer()),
4256 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004257 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004258 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004259 mFlags(flags),
4260 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004261 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004262 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004263{
4264 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004265 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4266 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004267 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004268 // to avoid leaking a track name, do not allocate one unless there is an mCblk
4269 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004270 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004271 if (mName < 0) {
4272 ALOGE("no more track names available");
4273 return;
4274 }
4275 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004276 if (flags & IAudioFlinger::TRACK_FAST) {
4277 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4278 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4279 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004280 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004281 // FIXME This is too eager. We allocate a fast track index before the
4282 // fast track becomes active. Since fast tracks are a scarce resource,
4283 // this means we are potentially denying other more important fast tracks from
4284 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004285 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004286 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004287 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004288 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004289 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004290 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004291 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004292 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004293}
4294
4295AudioFlinger::PlaybackThread::Track::~Track()
4296{
Steve Block3856b092011-10-20 11:56:00 +01004297 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004298 sp<ThreadBase> thread = mThread.promote();
4299 if (thread != 0) {
4300 Mutex::Autolock _l(thread->mLock);
4301 mState = TERMINATED;
4302 }
4303}
4304
4305void AudioFlinger::PlaybackThread::Track::destroy()
4306{
4307 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4308 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004309 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004310 // we must acquire a strong reference on this Track before locking mLock
4311 // here so that the destructor is called only when exiting this function.
4312 // On the other hand, as long as Track::destroy() is only called by
4313 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4314 // this Track with its member mTrack.
4315 sp<Track> keep(this);
4316 { // scope for mLock
4317 sp<ThreadBase> thread = mThread.promote();
4318 if (thread != 0) {
4319 if (!isOutputTrack()) {
4320 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004321 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004322
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004323#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004324 // to track the speaker usage
4325 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004326#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004327 }
4328 AudioSystem::releaseOutput(thread->id());
4329 }
4330 Mutex::Autolock _l(thread->mLock);
4331 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4332 playbackThread->destroyTrack_l(this);
4333 }
4334 }
4335}
4336
Glenn Kasten288ed212012-04-25 17:52:27 -07004337/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4338{
Glenn Kastene213c862012-04-25 13:46:15 -07004339 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 -07004340 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004341}
4342
Mathias Agopian65ab4712010-07-14 17:59:35 -07004343void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4344{
Glenn Kasten83d86532012-01-17 14:39:34 -08004345 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004346 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004347 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004348 } else {
4349 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4350 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004351 track_state state = mState;
4352 char stateChar;
4353 switch (state) {
4354 case IDLE:
4355 stateChar = 'I';
4356 break;
4357 case TERMINATED:
4358 stateChar = 'T';
4359 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004360 case STOPPING_1:
4361 stateChar = 's';
4362 break;
4363 case STOPPING_2:
4364 stateChar = '5';
4365 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004366 case STOPPED:
4367 stateChar = 'S';
4368 break;
4369 case RESUMING:
4370 stateChar = 'R';
4371 break;
4372 case ACTIVE:
4373 stateChar = 'A';
4374 break;
4375 case PAUSING:
4376 stateChar = 'p';
4377 break;
4378 case PAUSED:
4379 stateChar = 'P';
4380 break;
Eric Laurent29864602012-05-08 18:57:51 -07004381 case FLUSHED:
4382 stateChar = 'F';
4383 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004384 default:
4385 stateChar = '?';
4386 break;
4387 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004388 char nowInUnderrun;
4389 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4390 case UNDERRUN_FULL:
4391 nowInUnderrun = ' ';
4392 break;
4393 case UNDERRUN_PARTIAL:
4394 nowInUnderrun = '<';
4395 break;
4396 case UNDERRUN_EMPTY:
4397 nowInUnderrun = '*';
4398 break;
4399 default:
4400 nowInUnderrun = '?';
4401 break;
4402 }
Glenn Kastene213c862012-04-25 13:46:15 -07004403 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4404 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004405 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004406 mStreamType,
4407 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004408 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004409 mSessionId,
4410 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004411 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004412 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004413 mMute,
4414 mFillingUpStatus,
4415 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004416 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4417 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004418 mCblk->server,
4419 mCblk->user,
4420 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004421 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004422 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004423 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004424 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004425}
4426
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004427// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004428status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004429 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004430{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004431 audio_track_cblk_t* cblk = this->cblk();
4432 uint32_t framesReady;
4433 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004434
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004435 // Check if last stepServer failed, try to step now
4436 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004437 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4438 // Since the fast mixer is higher priority than client callback thread,
4439 // it does not result in priority inversion for client.
4440 // But a non-blocking solution would be preferable to avoid
4441 // fast mixer being unable to tryLock(), and
4442 // to avoid the extra context switches if the client wakes up,
4443 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004444 if (!step()) goto getNextBuffer_exit;
4445 ALOGV("stepServer recovered");
4446 mStepServerFailed = false;
4447 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004448
Glenn Kasten288ed212012-04-25 17:52:27 -07004449 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004450 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004451
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004452 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004453 uint32_t s = cblk->server;
4454 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4455
4456 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4457 if (framesReq > framesReady) {
4458 framesReq = framesReady;
4459 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004460 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004461 framesReq = bufferEnd - s;
4462 }
4463
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004464 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004465 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004466 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004467 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004468
4469getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004470 buffer->raw = NULL;
4471 buffer->frameCount = 0;
4472 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4473 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004474}
4475
Glenn Kasten288ed212012-04-25 17:52:27 -07004476// Note that framesReady() takes a mutex on the control block using tryLock().
4477// This could result in priority inversion if framesReady() is called by the normal mixer,
4478// as the normal mixer thread runs at lower
4479// priority than the client's callback thread: there is a short window within framesReady()
4480// during which the normal mixer could be preempted, and the client callback would block.
4481// Another problem can occur if framesReady() is called by the fast mixer:
4482// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4483// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4484size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004485 return mCblk->framesReady();
4486}
4487
Glenn Kasten288ed212012-04-25 17:52:27 -07004488// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004489bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004490 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004491
John Grossman4ff14ba2012-02-08 16:37:41 -08004492 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004493 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4494 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004495 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004496 return true;
4497 }
4498 return false;
4499}
4500
Glenn Kasten3acbd052012-02-28 10:39:56 -08004501status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004502 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004503{
4504 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004505 ALOGV("start(%d), calling pid %d session %d",
4506 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004507
Mathias Agopian65ab4712010-07-14 17:59:35 -07004508 sp<ThreadBase> thread = mThread.promote();
4509 if (thread != 0) {
4510 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004511 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004512 // here the track could be either new, or restarted
4513 // in both cases "unstop" the track
4514 if (mState == PAUSED) {
4515 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004516 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004517 } else {
4518 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004519 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004520 }
4521
4522 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4523 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004524 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004525 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004526
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004527#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004528 // to track the speaker usage
4529 if (status == NO_ERROR) {
4530 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4531 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004532#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004533 }
4534 if (status == NO_ERROR) {
4535 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4536 playbackThread->addTrack_l(this);
4537 } else {
4538 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004539 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004540 }
4541 } else {
4542 status = BAD_VALUE;
4543 }
4544 return status;
4545}
4546
4547void AudioFlinger::PlaybackThread::Track::stop()
4548{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004549 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004550 sp<ThreadBase> thread = mThread.promote();
4551 if (thread != 0) {
4552 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004553 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004554 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004555 // If the track is not active (PAUSED and buffers full), flush buffers
4556 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4557 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4558 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004559 mState = STOPPED;
4560 } else if (!isFastTrack()) {
4561 mState = STOPPED;
4562 } else {
4563 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4564 // and then to STOPPED and reset() when presentation is complete
4565 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004566 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004567 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004568 }
4569 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4570 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004571 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004572 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004573
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004574#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004575 // to track the speaker usage
4576 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004577#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004578 }
4579 }
4580}
4581
4582void AudioFlinger::PlaybackThread::Track::pause()
4583{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004584 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004585 sp<ThreadBase> thread = mThread.promote();
4586 if (thread != 0) {
4587 Mutex::Autolock _l(thread->mLock);
4588 if (mState == ACTIVE || mState == RESUMING) {
4589 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004590 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004591 if (!isOutputTrack()) {
4592 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004593 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004594 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004595
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004596#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004597 // to track the speaker usage
4598 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004599#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004600 }
4601 }
4602 }
4603}
4604
4605void AudioFlinger::PlaybackThread::Track::flush()
4606{
Steve Block3856b092011-10-20 11:56:00 +01004607 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004608 sp<ThreadBase> thread = mThread.promote();
4609 if (thread != 0) {
4610 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004611 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4612 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004613 return;
4614 }
4615 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004616 // FLUSHED state
4617 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004618 // do not reset the track if it is still in the process of being stopped or paused.
4619 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004620 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004621 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004622 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4623 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4624 reset();
4625 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004626 }
4627}
4628
4629void AudioFlinger::PlaybackThread::Track::reset()
4630{
4631 // Do not reset twice to avoid discarding data written just after a flush and before
4632 // the audioflinger thread detects the track is stopped.
4633 if (!mResetDone) {
4634 TrackBase::reset();
4635 // Force underrun condition to avoid false underrun callback until first data is
4636 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004637 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4638 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004639 mFillingUpStatus = FS_FILLING;
4640 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004641 if (mState == FLUSHED) {
4642 mState = IDLE;
4643 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004644 }
4645}
4646
4647void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4648{
4649 mMute = muted;
4650}
4651
Mathias Agopian65ab4712010-07-14 17:59:35 -07004652status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4653{
4654 status_t status = DEAD_OBJECT;
4655 sp<ThreadBase> thread = mThread.promote();
4656 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004657 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004658 sp<AudioFlinger> af = mClient->audioFlinger();
4659
4660 Mutex::Autolock _l(af->mLock);
4661
4662 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004663
Eric Laurent109347d2012-07-02 12:31:03 -07004664 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004665 Mutex::Autolock _dl(playbackThread->mLock);
4666 Mutex::Autolock _sl(srcThread->mLock);
4667 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4668 if (chain == 0) {
4669 return INVALID_OPERATION;
4670 }
4671
4672 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4673 if (effect == 0) {
4674 return INVALID_OPERATION;
4675 }
4676 srcThread->removeEffect_l(effect);
4677 playbackThread->addEffect_l(effect);
4678 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4679 if (effect->state() == EffectModule::ACTIVE ||
4680 effect->state() == EffectModule::STOPPING) {
4681 effect->start();
4682 }
4683
4684 sp<EffectChain> dstChain = effect->chain().promote();
4685 if (dstChain == 0) {
4686 srcThread->addEffect_l(effect);
4687 return INVALID_OPERATION;
4688 }
4689 AudioSystem::unregisterEffect(effect->id());
4690 AudioSystem::registerEffect(&effect->desc(),
4691 srcThread->id(),
4692 dstChain->strategy(),
4693 AUDIO_SESSION_OUTPUT_MIX,
4694 effect->id());
4695 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004696 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004697 }
4698 return status;
4699}
4700
4701void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4702{
4703 mAuxEffectId = EffectId;
4704 mAuxBuffer = buffer;
4705}
4706
Eric Laurenta011e352012-03-29 15:51:43 -07004707bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4708 size_t audioHalFrames)
4709{
4710 // a track is considered presented when the total number of frames written to audio HAL
4711 // corresponds to the number of frames written when presentationComplete() is called for the
4712 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4713 if (mPresentationCompleteFrames == 0) {
4714 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4715 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4716 mPresentationCompleteFrames, audioHalFrames);
4717 }
4718 if (framesWritten >= mPresentationCompleteFrames) {
4719 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4720 mSessionId, framesWritten);
4721 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004722 return true;
4723 }
4724 return false;
4725}
4726
4727void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4728{
4729 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4730 if (mSyncEvents[i]->type() == type) {
4731 mSyncEvents[i]->trigger();
4732 mSyncEvents.removeAt(i);
4733 i--;
4734 }
4735 }
4736}
4737
Glenn Kasten58912562012-04-03 10:45:00 -07004738// implement VolumeBufferProvider interface
4739
4740uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4741{
4742 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4743 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4744 uint32_t vlr = mCblk->getVolumeLR();
4745 uint32_t vl = vlr & 0xFFFF;
4746 uint32_t vr = vlr >> 16;
4747 // track volumes come from shared memory, so can't be trusted and must be clamped
4748 if (vl > MAX_GAIN_INT) {
4749 vl = MAX_GAIN_INT;
4750 }
4751 if (vr > MAX_GAIN_INT) {
4752 vr = MAX_GAIN_INT;
4753 }
4754 // now apply the cached master volume and stream type volume;
4755 // this is trusted but lacks any synchronization or barrier so may be stale
4756 float v = mCachedVolume;
4757 vl *= v;
4758 vr *= v;
4759 // re-combine into U4.16
4760 vlr = (vr << 16) | (vl & 0xFFFF);
4761 // FIXME look at mute, pause, and stop flags
4762 return vlr;
4763}
Eric Laurenta011e352012-03-29 15:51:43 -07004764
Eric Laurent29864602012-05-08 18:57:51 -07004765status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4766{
4767 if (mState == TERMINATED || mState == PAUSED ||
4768 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4769 (mState == STOPPED)))) {
4770 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4771 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4772 event->cancel();
4773 return INVALID_OPERATION;
4774 }
4775 TrackBase::setSyncEvent(event);
4776 return NO_ERROR;
4777}
4778
John Grossman4ff14ba2012-02-08 16:37:41 -08004779// timed audio tracks
4780
4781sp<AudioFlinger::PlaybackThread::TimedTrack>
4782AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004783 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004784 const sp<Client>& client,
4785 audio_stream_type_t streamType,
4786 uint32_t sampleRate,
4787 audio_format_t format,
4788 uint32_t channelMask,
4789 int frameCount,
4790 const sp<IMemory>& sharedBuffer,
4791 int sessionId) {
4792 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004793 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004794
Glenn Kastena0356762012-03-19 10:38:51 -07004795 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004796 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4797 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004798}
4799
4800AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004801 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004802 const sp<Client>& client,
4803 audio_stream_type_t streamType,
4804 uint32_t sampleRate,
4805 audio_format_t format,
4806 uint32_t channelMask,
4807 int frameCount,
4808 const sp<IMemory>& sharedBuffer,
4809 int sessionId)
4810 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004811 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004812 mQueueHeadInFlight(false),
4813 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004814 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004815 mTimedSilenceBuffer(NULL),
4816 mTimedSilenceBufferSize(0),
4817 mTimedAudioOutputOnTime(false),
4818 mMediaTimeTransformValid(false)
4819{
4820 LocalClock lc;
4821 mLocalTimeFreq = lc.getLocalFreq();
4822
4823 mLocalTimeToSampleTransform.a_zero = 0;
4824 mLocalTimeToSampleTransform.b_zero = 0;
4825 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4826 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4827 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4828 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004829
4830 mMediaTimeToSampleTransform.a_zero = 0;
4831 mMediaTimeToSampleTransform.b_zero = 0;
4832 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4833 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4834 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4835 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004836}
4837
4838AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4839 mClient->releaseTimedTrack();
4840 delete [] mTimedSilenceBuffer;
4841}
4842
4843status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4844 size_t size, sp<IMemory>* buffer) {
4845
4846 Mutex::Autolock _l(mTimedBufferQueueLock);
4847
4848 trimTimedBufferQueue_l();
4849
4850 // lazily initialize the shared memory heap for timed buffers
4851 if (mTimedMemoryDealer == NULL) {
4852 const int kTimedBufferHeapSize = 512 << 10;
4853
4854 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4855 "AudioFlingerTimed");
4856 if (mTimedMemoryDealer == NULL)
4857 return NO_MEMORY;
4858 }
4859
4860 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4861 if (newBuffer == NULL) {
4862 newBuffer = mTimedMemoryDealer->allocate(size);
4863 if (newBuffer == NULL)
4864 return NO_MEMORY;
4865 }
4866
4867 *buffer = newBuffer;
4868 return NO_ERROR;
4869}
4870
4871// caller must hold mTimedBufferQueueLock
4872void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4873 int64_t mediaTimeNow;
4874 {
4875 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4876 if (!mMediaTimeTransformValid)
4877 return;
4878
4879 int64_t targetTimeNow;
4880 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4881 ? mCCHelper.getCommonTime(&targetTimeNow)
4882 : mCCHelper.getLocalTime(&targetTimeNow);
4883
4884 if (OK != res)
4885 return;
4886
4887 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4888 &mediaTimeNow)) {
4889 return;
4890 }
4891 }
4892
John Grossman1c345192012-03-27 14:00:17 -07004893 size_t trimEnd;
4894 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004895 int64_t bufEnd;
4896
John Grossmanc95cfbb2012-04-12 11:53:11 -07004897 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4898 // We have a next buffer. Just use its PTS as the PTS of the frame
4899 // following the last frame in this buffer. If the stream is sparse
4900 // (ie, there are deliberate gaps left in the stream which should be
4901 // filled with silence by the TimedAudioTrack), then this can result
4902 // in one extra buffer being left un-trimmed when it could have
4903 // been. In general, this is not typical, and we would rather
4904 // optimized away the TS calculation below for the more common case
4905 // where PTSes are contiguous.
4906 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4907 } else {
4908 // We have no next buffer. Compute the PTS of the frame following
4909 // the last frame in this buffer by computing the duration of of
4910 // this frame in media time units and adding it to the PTS of the
4911 // buffer.
4912 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4913 / mCblk->frameSize;
4914
4915 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4916 &bufEnd)) {
4917 ALOGE("Failed to convert frame count of %lld to media time"
4918 " duration" " (scale factor %d/%u) in %s",
4919 frameCount,
4920 mMediaTimeToSampleTransform.a_to_b_numer,
4921 mMediaTimeToSampleTransform.a_to_b_denom,
4922 __PRETTY_FUNCTION__);
4923 break;
4924 }
4925 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004926 }
John Grossman9fbdee12012-03-26 17:51:46 -07004927
4928 if (bufEnd > mediaTimeNow)
4929 break;
4930
4931 // Is the buffer we want to use in the middle of a mix operation right
4932 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4933 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004934 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004935 mTrimQueueHeadOnRelease = true;
4936 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004937 }
4938
John Grossman9fbdee12012-03-26 17:51:46 -07004939 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004940 if (trimStart < trimEnd) {
4941 // Update the bookkeeping for framesReady()
4942 for (size_t i = trimStart; i < trimEnd; ++i) {
4943 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4944 }
4945
4946 // Now actually remove the buffers from the queue.
4947 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004948 }
4949}
4950
John Grossman1c345192012-03-27 14:00:17 -07004951void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4952 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004953 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4954 "%s called (reason \"%s\"), but timed buffer queue has no"
4955 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004956
4957 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4958 mTimedBufferQueue.removeAt(0);
4959}
4960
4961void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4962 const TimedBuffer& buf,
4963 const char* logTag) {
4964 uint32_t bufBytes = buf.buffer()->size();
4965 uint32_t consumedAlready = buf.position();
4966
Eric Laurentb388e532012-04-14 13:32:48 -07004967 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004968 "Bad bookkeeping while updating frames pending. Timed buffer is"
4969 " only %u bytes long, but claims to have consumed %u"
4970 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004971 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004972
4973 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004974 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4975 "Bad bookkeeping while updating frames pending. Should have at"
4976 " least %u queued frames, but we think we have only %u. (update"
4977 " reason: \"%s\")",
4978 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004979
4980 mFramesPendingInQueue -= bufFrames;
4981}
4982
John Grossman4ff14ba2012-02-08 16:37:41 -08004983status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4984 const sp<IMemory>& buffer, int64_t pts) {
4985
4986 {
4987 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4988 if (!mMediaTimeTransformValid)
4989 return INVALID_OPERATION;
4990 }
4991
4992 Mutex::Autolock _l(mTimedBufferQueueLock);
4993
John Grossman1c345192012-03-27 14:00:17 -07004994 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4995 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004996 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4997
4998 return NO_ERROR;
4999}
5000
5001status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5002 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5003
John Grossman1c345192012-03-27 14:00:17 -07005004 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5005 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5006 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005007
5008 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5009 target == TimedAudioTrack::COMMON_TIME)) {
5010 return BAD_VALUE;
5011 }
5012
5013 Mutex::Autolock lock(mMediaTimeTransformLock);
5014 mMediaTimeTransform = xform;
5015 mMediaTimeTransformTarget = target;
5016 mMediaTimeTransformValid = true;
5017
5018 return NO_ERROR;
5019}
5020
5021#define min(a, b) ((a) < (b) ? (a) : (b))
5022
5023// implementation of getNextBuffer for tracks whose buffers have timestamps
5024status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5025 AudioBufferProvider::Buffer* buffer, int64_t pts)
5026{
5027 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005028 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005029 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005030 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005031 return INVALID_OPERATION;
5032 }
5033
John Grossman4ff14ba2012-02-08 16:37:41 -08005034 Mutex::Autolock _l(mTimedBufferQueueLock);
5035
John Grossman9fbdee12012-03-26 17:51:46 -07005036 ALOG_ASSERT(!mQueueHeadInFlight,
5037 "getNextBuffer called without releaseBuffer!");
5038
John Grossman4ff14ba2012-02-08 16:37:41 -08005039 while (true) {
5040
5041 // if we have no timed buffers, then fail
5042 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005043 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005044 buffer->frameCount = 0;
5045 return NOT_ENOUGH_DATA;
5046 }
5047
5048 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5049
5050 // calculate the PTS of the head of the timed buffer queue expressed in
5051 // local time
5052 int64_t headLocalPTS;
5053 {
5054 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5055
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005056 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005057
5058 if (mMediaTimeTransform.a_to_b_denom == 0) {
5059 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005060 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005061 return NO_ERROR;
5062 }
5063
5064 int64_t transformedPTS;
5065 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5066 &transformedPTS)) {
5067 // the transform failed. this shouldn't happen, but if it does
5068 // then just drop this buffer
5069 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005070 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005071 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005072 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005073 return NO_ERROR;
5074 }
5075
5076 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5077 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5078 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005079 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005080 buffer->frameCount = 0;
5081 return INVALID_OPERATION;
5082 }
5083 } else {
5084 headLocalPTS = transformedPTS;
5085 }
5086 }
5087
5088 // adjust the head buffer's PTS to reflect the portion of the head buffer
5089 // that has already been consumed
5090 int64_t effectivePTS = headLocalPTS +
5091 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5092
5093 // Calculate the delta in samples between the head of the input buffer
5094 // queue and the start of the next output buffer that will be written.
5095 // If the transformation fails because of over or underflow, it means
5096 // that the sample's position in the output stream is so far out of
5097 // whack that it should just be dropped.
5098 int64_t sampleDelta;
5099 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5100 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005101 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5102 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005103 continue;
5104 }
5105 if (!mLocalTimeToSampleTransform.doForwardTransform(
5106 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005107 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005108 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005109 continue;
5110 }
5111
John Grossman1c345192012-03-27 14:00:17 -07005112 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5113 " sampleDelta=[%d.%08x]",
5114 head.pts(), head.position(), pts,
5115 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5116 + (sampleDelta >> 32)),
5117 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005118
5119 // if the delta between the ideal placement for the next input sample and
5120 // the current output position is within this threshold, then we will
5121 // concatenate the next input samples to the previous output
5122 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005123 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005124
5125 // if this is the first buffer of audio that we're emitting from this track
5126 // then it should be almost exactly on time.
5127 const int64_t kSampleStartupThreshold = 1LL << 32;
5128
5129 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005130 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005131 // the next input is close enough to being on time, so concatenate it
5132 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005133 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005134
John Grossman1c345192012-03-27 14:00:17 -07005135 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5136 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005137 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005138 }
5139
5140 // Looks like our output is not on time. Reset our on timed status.
5141 // Next time we mix samples from our input queue, then should be within
5142 // the StartupThreshold.
5143 mTimedAudioOutputOnTime = false;
5144 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005145 // the gap between the current output position and the proper start of
5146 // the next input sample is too big, so fill it with silence
5147 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5148
John Grossman9fbdee12012-03-26 17:51:46 -07005149 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005150 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5151 return NO_ERROR;
5152 } else {
5153 // the next input sample is late
5154 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5155 size_t onTimeSamplePosition =
5156 head.position() + lateFrames * mCblk->frameSize;
5157
5158 if (onTimeSamplePosition > head.buffer()->size()) {
5159 // all the remaining samples in the head are too late, so
5160 // drop it and move on
5161 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005162 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005163 continue;
5164 } else {
5165 // skip over the late samples
5166 head.setPosition(onTimeSamplePosition);
5167
5168 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005169 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005170
5171 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5172 return NO_ERROR;
5173 }
5174 }
5175 }
5176}
5177
5178// Yield samples from the timed buffer queue head up to the given output
5179// buffer's capacity.
5180//
5181// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005182void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005183 AudioBufferProvider::Buffer* buffer) {
5184
5185 const TimedBuffer& head = mTimedBufferQueue[0];
5186
5187 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5188 head.position());
5189
5190 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5191 mCblk->frameSize);
5192 size_t framesRequested = buffer->frameCount;
5193 buffer->frameCount = min(framesLeftInHead, framesRequested);
5194
John Grossman9fbdee12012-03-26 17:51:46 -07005195 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005196 mTimedAudioOutputOnTime = true;
5197}
5198
5199// Yield samples of silence up to the given output buffer's capacity
5200//
5201// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005202void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005203 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5204
5205 // lazily allocate a buffer filled with silence
5206 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5207 delete [] mTimedSilenceBuffer;
5208 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5209 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5210 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5211 }
5212
5213 buffer->raw = mTimedSilenceBuffer;
5214 size_t framesRequested = buffer->frameCount;
5215 buffer->frameCount = min(numFrames, framesRequested);
5216
5217 mTimedAudioOutputOnTime = false;
5218}
5219
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005220// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005221void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5222 AudioBufferProvider::Buffer* buffer) {
5223
5224 Mutex::Autolock _l(mTimedBufferQueueLock);
5225
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005226 // If the buffer which was just released is part of the buffer at the head
5227 // of the queue, be sure to update the amt of the buffer which has been
5228 // consumed. If the buffer being returned is not part of the head of the
5229 // queue, its either because the buffer is part of the silence buffer, or
5230 // because the head of the timed queue was trimmed after the mixer called
5231 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005232 if (buffer->raw == mTimedSilenceBuffer) {
5233 ALOG_ASSERT(!mQueueHeadInFlight,
5234 "Queue head in flight during release of silence buffer!");
5235 goto done;
5236 }
5237
5238 ALOG_ASSERT(mQueueHeadInFlight,
5239 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5240 " head in flight.");
5241
5242 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005243 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005244
5245 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005246 void* end = reinterpret_cast<void*>(
5247 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5248 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005249
John Grossman9fbdee12012-03-26 17:51:46 -07005250 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5251 "released buffer not within the head of the timed buffer"
5252 " queue; qHead = [%p, %p], released buffer = %p",
5253 start, end, buffer->raw);
5254
5255 head.setPosition(head.position() +
5256 (buffer->frameCount * mCblk->frameSize));
5257 mQueueHeadInFlight = false;
5258
John Grossman1c345192012-03-27 14:00:17 -07005259 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5260 "Bad bookkeeping during releaseBuffer! Should have at"
5261 " least %u queued frames, but we think we have only %u",
5262 buffer->frameCount, mFramesPendingInQueue);
5263
5264 mFramesPendingInQueue -= buffer->frameCount;
5265
John Grossman9fbdee12012-03-26 17:51:46 -07005266 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5267 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005268 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005269 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005270 }
John Grossman9fbdee12012-03-26 17:51:46 -07005271 } else {
5272 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5273 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005274 }
5275
John Grossman9fbdee12012-03-26 17:51:46 -07005276done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005277 buffer->raw = 0;
5278 buffer->frameCount = 0;
5279}
5280
Glenn Kasten288ed212012-04-25 17:52:27 -07005281size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005282 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005283 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005284}
5285
5286AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5287 : mPTS(0), mPosition(0) {}
5288
5289AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5290 const sp<IMemory>& buffer, int64_t pts)
5291 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5292
Mathias Agopian65ab4712010-07-14 17:59:35 -07005293// ----------------------------------------------------------------------------
5294
5295// RecordTrack constructor must be called with AudioFlinger::mLock held
5296AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005297 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005298 const sp<Client>& client,
5299 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005300 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005301 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005302 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005303 int sessionId)
5304 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005305 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005306 mOverflow(false)
5307{
5308 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005309 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5310 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5311 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5312 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5313 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5314 } else {
5315 mCblk->frameSize = sizeof(int8_t);
5316 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005317 }
5318}
5319
5320AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5321{
5322 sp<ThreadBase> thread = mThread.promote();
5323 if (thread != 0) {
5324 AudioSystem::releaseInput(thread->id());
5325 }
5326}
5327
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005328// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005329status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005330{
5331 audio_track_cblk_t* cblk = this->cblk();
5332 uint32_t framesAvail;
5333 uint32_t framesReq = buffer->frameCount;
5334
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005335 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005336 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005337 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005338 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005339 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005340 }
5341
5342 framesAvail = cblk->framesAvailable_l();
5343
Glenn Kastenf6b16782011-12-15 09:51:17 -08005344 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005345 uint32_t s = cblk->server;
5346 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5347
5348 if (framesReq > framesAvail) {
5349 framesReq = framesAvail;
5350 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005351 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005352 framesReq = bufferEnd - s;
5353 }
5354
5355 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005356 buffer->frameCount = framesReq;
5357 return NO_ERROR;
5358 }
5359
5360getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005361 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005362 buffer->frameCount = 0;
5363 return NOT_ENOUGH_DATA;
5364}
5365
Glenn Kasten3acbd052012-02-28 10:39:56 -08005366status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005367 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005368{
5369 sp<ThreadBase> thread = mThread.promote();
5370 if (thread != 0) {
5371 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005372 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005373 } else {
5374 return BAD_VALUE;
5375 }
5376}
5377
5378void AudioFlinger::RecordThread::RecordTrack::stop()
5379{
5380 sp<ThreadBase> thread = mThread.promote();
5381 if (thread != 0) {
5382 RecordThread *recordThread = (RecordThread *)thread.get();
5383 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005384 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005385 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005386 // read from buffer
5387 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005388 }
5389}
5390
5391void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5392{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005393 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005394 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005395 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005396 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005397 mSessionId,
5398 mFrameCount,
5399 mState,
5400 mCblk->sampleRate,
5401 mCblk->server,
5402 mCblk->user);
5403}
5404
5405
5406// ----------------------------------------------------------------------------
5407
5408AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005409 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005410 DuplicatingThread *sourceThread,
5411 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005412 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005413 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005414 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005415 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5416 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005417 mActive(false), mSourceThread(sourceThread)
5418{
5419
Mathias Agopian65ab4712010-07-14 17:59:35 -07005420 if (mCblk != NULL) {
5421 mCblk->flags |= CBLK_DIRECTION_OUT;
5422 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005423 mOutBuffer.frameCount = 0;
5424 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005425 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005426 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5427 mCblk, mBuffer, mCblk->buffers,
5428 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005429 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005430 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005431 }
5432}
5433
5434AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5435{
5436 clearBufferQueue();
5437}
5438
Glenn Kasten3acbd052012-02-28 10:39:56 -08005439status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005440 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005441{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005442 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005443 if (status != NO_ERROR) {
5444 return status;
5445 }
5446
5447 mActive = true;
5448 mRetryCount = 127;
5449 return status;
5450}
5451
5452void AudioFlinger::PlaybackThread::OutputTrack::stop()
5453{
5454 Track::stop();
5455 clearBufferQueue();
5456 mOutBuffer.frameCount = 0;
5457 mActive = false;
5458}
5459
5460bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5461{
5462 Buffer *pInBuffer;
5463 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005464 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005465 bool outputBufferFull = false;
5466 inBuffer.frameCount = frames;
5467 inBuffer.i16 = data;
5468
5469 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5470
5471 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005472 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005473 sp<ThreadBase> thread = mThread.promote();
5474 if (thread != 0) {
5475 MixerThread *mixerThread = (MixerThread *)thread.get();
5476 if (mCblk->frameCount > frames){
5477 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5478 uint32_t startFrames = (mCblk->frameCount - frames);
5479 pInBuffer = new Buffer;
5480 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5481 pInBuffer->frameCount = startFrames;
5482 pInBuffer->i16 = pInBuffer->mBuffer;
5483 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5484 mBufferQueue.add(pInBuffer);
5485 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005486 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005487 }
5488 }
5489 }
5490 }
5491
5492 while (waitTimeLeftMs) {
5493 // First write pending buffers, then new data
5494 if (mBufferQueue.size()) {
5495 pInBuffer = mBufferQueue.itemAt(0);
5496 } else {
5497 pInBuffer = &inBuffer;
5498 }
5499
5500 if (pInBuffer->frameCount == 0) {
5501 break;
5502 }
5503
5504 if (mOutBuffer.frameCount == 0) {
5505 mOutBuffer.frameCount = pInBuffer->frameCount;
5506 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005507 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005508 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005509 outputBufferFull = true;
5510 break;
5511 }
5512 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5513 if (waitTimeLeftMs >= waitTimeMs) {
5514 waitTimeLeftMs -= waitTimeMs;
5515 } else {
5516 waitTimeLeftMs = 0;
5517 }
5518 }
5519
5520 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5521 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5522 mCblk->stepUser(outFrames);
5523 pInBuffer->frameCount -= outFrames;
5524 pInBuffer->i16 += outFrames * channelCount;
5525 mOutBuffer.frameCount -= outFrames;
5526 mOutBuffer.i16 += outFrames * channelCount;
5527
5528 if (pInBuffer->frameCount == 0) {
5529 if (mBufferQueue.size()) {
5530 mBufferQueue.removeAt(0);
5531 delete [] pInBuffer->mBuffer;
5532 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005533 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005534 } else {
5535 break;
5536 }
5537 }
5538 }
5539
5540 // If we could not write all frames, allocate a buffer and queue it for next time.
5541 if (inBuffer.frameCount) {
5542 sp<ThreadBase> thread = mThread.promote();
5543 if (thread != 0 && !thread->standby()) {
5544 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5545 pInBuffer = new Buffer;
5546 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5547 pInBuffer->frameCount = inBuffer.frameCount;
5548 pInBuffer->i16 = pInBuffer->mBuffer;
5549 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5550 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005551 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005552 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005553 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005554 }
5555 }
5556 }
5557
5558 // Calling write() with a 0 length buffer, means that no more data will be written:
5559 // If no more buffers are pending, fill output track buffer to make sure it is started
5560 // by output mixer.
5561 if (frames == 0 && mBufferQueue.size() == 0) {
5562 if (mCblk->user < mCblk->frameCount) {
5563 frames = mCblk->frameCount - mCblk->user;
5564 pInBuffer = new Buffer;
5565 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5566 pInBuffer->frameCount = frames;
5567 pInBuffer->i16 = pInBuffer->mBuffer;
5568 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5569 mBufferQueue.add(pInBuffer);
5570 } else if (mActive) {
5571 stop();
5572 }
5573 }
5574
5575 return outputBufferFull;
5576}
5577
5578status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5579{
5580 int active;
5581 status_t result;
5582 audio_track_cblk_t* cblk = mCblk;
5583 uint32_t framesReq = buffer->frameCount;
5584
Steve Block3856b092011-10-20 11:56:00 +01005585// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005586 buffer->frameCount = 0;
5587
5588 uint32_t framesAvail = cblk->framesAvailable();
5589
5590
5591 if (framesAvail == 0) {
5592 Mutex::Autolock _l(cblk->lock);
5593 goto start_loop_here;
5594 while (framesAvail == 0) {
5595 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005596 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005597 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005598 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005599 }
5600 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5601 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005602 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005603 }
5604 // read the server count again
5605 start_loop_here:
5606 framesAvail = cblk->framesAvailable_l();
5607 }
5608 }
5609
5610// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005611// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005612// }
5613
5614 if (framesReq > framesAvail) {
5615 framesReq = framesAvail;
5616 }
5617
5618 uint32_t u = cblk->user;
5619 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5620
Marco Nelissena1472d92012-03-30 14:36:54 -07005621 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005622 framesReq = bufferEnd - u;
5623 }
5624
5625 buffer->frameCount = framesReq;
5626 buffer->raw = (void *)cblk->buffer(u);
5627 return NO_ERROR;
5628}
5629
5630
5631void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5632{
5633 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005634
5635 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005636 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005637 delete [] pBuffer->mBuffer;
5638 delete pBuffer;
5639 }
5640 mBufferQueue.clear();
5641}
5642
5643// ----------------------------------------------------------------------------
5644
5645AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5646 : RefBase(),
5647 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005648 // 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 -07005649 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005650 mPid(pid),
5651 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005652{
5653 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5654}
5655
5656// Client destructor must be called with AudioFlinger::mLock held
5657AudioFlinger::Client::~Client()
5658{
5659 mAudioFlinger->removeClient_l(mPid);
5660}
5661
Glenn Kasten435dbe62012-01-30 10:15:48 -08005662sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005663{
5664 return mMemoryDealer;
5665}
5666
John Grossman4ff14ba2012-02-08 16:37:41 -08005667// Reserve one of the limited slots for a timed audio track associated
5668// with this client
5669bool AudioFlinger::Client::reserveTimedTrack()
5670{
5671 const int kMaxTimedTracksPerClient = 4;
5672
5673 Mutex::Autolock _l(mTimedTrackLock);
5674
5675 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5676 ALOGW("can not create timed track - pid %d has exceeded the limit",
5677 mPid);
5678 return false;
5679 }
5680
5681 mTimedTrackCount++;
5682 return true;
5683}
5684
5685// Release a slot for a timed audio track
5686void AudioFlinger::Client::releaseTimedTrack()
5687{
5688 Mutex::Autolock _l(mTimedTrackLock);
5689 mTimedTrackCount--;
5690}
5691
Mathias Agopian65ab4712010-07-14 17:59:35 -07005692// ----------------------------------------------------------------------------
5693
5694AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5695 const sp<IAudioFlingerClient>& client,
5696 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005697 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005698{
5699}
5700
5701AudioFlinger::NotificationClient::~NotificationClient()
5702{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005703}
5704
5705void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5706{
5707 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005708 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005709}
5710
5711// ----------------------------------------------------------------------------
5712
5713AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5714 : BnAudioTrack(),
5715 mTrack(track)
5716{
5717}
5718
5719AudioFlinger::TrackHandle::~TrackHandle() {
5720 // just stop the track on deletion, associated resources
5721 // will be freed from the main thread once all pending buffers have
5722 // been played. Unless it's not in the active track list, in which
5723 // case we free everything now...
5724 mTrack->destroy();
5725}
5726
Glenn Kasten90716c52012-01-26 13:40:12 -08005727sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5728 return mTrack->getCblk();
5729}
5730
Glenn Kasten3acbd052012-02-28 10:39:56 -08005731status_t AudioFlinger::TrackHandle::start() {
5732 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005733}
5734
5735void AudioFlinger::TrackHandle::stop() {
5736 mTrack->stop();
5737}
5738
5739void AudioFlinger::TrackHandle::flush() {
5740 mTrack->flush();
5741}
5742
5743void AudioFlinger::TrackHandle::mute(bool e) {
5744 mTrack->mute(e);
5745}
5746
5747void AudioFlinger::TrackHandle::pause() {
5748 mTrack->pause();
5749}
5750
Mathias Agopian65ab4712010-07-14 17:59:35 -07005751status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5752{
5753 return mTrack->attachAuxEffect(EffectId);
5754}
5755
John Grossman4ff14ba2012-02-08 16:37:41 -08005756status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5757 sp<IMemory>* buffer) {
5758 if (!mTrack->isTimedTrack())
5759 return INVALID_OPERATION;
5760
5761 PlaybackThread::TimedTrack* tt =
5762 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5763 return tt->allocateTimedBuffer(size, buffer);
5764}
5765
5766status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5767 int64_t pts) {
5768 if (!mTrack->isTimedTrack())
5769 return INVALID_OPERATION;
5770
5771 PlaybackThread::TimedTrack* tt =
5772 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5773 return tt->queueTimedBuffer(buffer, pts);
5774}
5775
5776status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5777 const LinearTransform& xform, int target) {
5778
5779 if (!mTrack->isTimedTrack())
5780 return INVALID_OPERATION;
5781
5782 PlaybackThread::TimedTrack* tt =
5783 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5784 return tt->setMediaTimeTransform(
5785 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5786}
5787
Mathias Agopian65ab4712010-07-14 17:59:35 -07005788status_t AudioFlinger::TrackHandle::onTransact(
5789 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5790{
5791 return BnAudioTrack::onTransact(code, data, reply, flags);
5792}
5793
5794// ----------------------------------------------------------------------------
5795
5796sp<IAudioRecord> AudioFlinger::openRecord(
5797 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005798 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005799 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005800 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005801 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005802 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005803 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005804 int *sessionId,
5805 status_t *status)
5806{
5807 sp<RecordThread::RecordTrack> recordTrack;
5808 sp<RecordHandle> recordHandle;
5809 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005810 status_t lStatus;
5811 RecordThread *thread;
5812 size_t inFrameCount;
5813 int lSessionId;
5814
5815 // check calling permissions
5816 if (!recordingAllowed()) {
5817 lStatus = PERMISSION_DENIED;
5818 goto Exit;
5819 }
5820
5821 // add client to list
5822 { // scope for mLock
5823 Mutex::Autolock _l(mLock);
5824 thread = checkRecordThread_l(input);
5825 if (thread == NULL) {
5826 lStatus = BAD_VALUE;
5827 goto Exit;
5828 }
5829
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005830 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005831
5832 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005833 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005834 lSessionId = *sessionId;
5835 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005836 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005837 if (sessionId != NULL) {
5838 *sessionId = lSessionId;
5839 }
5840 }
5841 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005842 recordTrack = thread->createRecordTrack_l(client,
5843 sampleRate,
5844 format,
5845 channelMask,
5846 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005847 lSessionId,
5848 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005849 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005850 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005851 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5852 // destructor is called by the TrackBase destructor with mLock held
5853 client.clear();
5854 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005855 goto Exit;
5856 }
5857
5858 // return to handle to client
5859 recordHandle = new RecordHandle(recordTrack);
5860 lStatus = NO_ERROR;
5861
5862Exit:
5863 if (status) {
5864 *status = lStatus;
5865 }
5866 return recordHandle;
5867}
5868
5869// ----------------------------------------------------------------------------
5870
5871AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5872 : BnAudioRecord(),
5873 mRecordTrack(recordTrack)
5874{
5875}
5876
5877AudioFlinger::RecordHandle::~RecordHandle() {
5878 stop();
5879}
5880
Glenn Kasten90716c52012-01-26 13:40:12 -08005881sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5882 return mRecordTrack->getCblk();
5883}
5884
Glenn Kasten3acbd052012-02-28 10:39:56 -08005885status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005886 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005887 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005888}
5889
5890void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005891 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005892 mRecordTrack->stop();
5893}
5894
Mathias Agopian65ab4712010-07-14 17:59:35 -07005895status_t AudioFlinger::RecordHandle::onTransact(
5896 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5897{
5898 return BnAudioRecord::onTransact(code, data, reply, flags);
5899}
5900
5901// ----------------------------------------------------------------------------
5902
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005903AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5904 AudioStreamIn *input,
5905 uint32_t sampleRate,
5906 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005907 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005908 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005909 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005910 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5911 // mRsmpInIndex and mInputBytes set by readInputParameters()
5912 mReqChannelCount(popcount(channels)),
5913 mReqSampleRate(sampleRate)
5914 // mBytesRead is only meaningful while active, and so is cleared in start()
5915 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005916{
Glenn Kasten480b4682012-02-28 12:30:08 -08005917 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005918
Mathias Agopian65ab4712010-07-14 17:59:35 -07005919 readInputParameters();
5920}
5921
5922
5923AudioFlinger::RecordThread::~RecordThread()
5924{
5925 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005926 delete mResampler;
5927 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005928}
5929
5930void AudioFlinger::RecordThread::onFirstRef()
5931{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005932 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005933}
5934
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005935status_t AudioFlinger::RecordThread::readyToRun()
5936{
5937 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005938 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005939 return status;
5940}
5941
Mathias Agopian65ab4712010-07-14 17:59:35 -07005942bool AudioFlinger::RecordThread::threadLoop()
5943{
5944 AudioBufferProvider::Buffer buffer;
5945 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005946 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005947
Eric Laurent44d98482010-09-30 16:12:31 -07005948 nsecs_t lastWarning = 0;
5949
Eric Laurentfeb0db62011-07-22 09:04:31 -07005950 acquireWakeLock();
5951
Mathias Agopian65ab4712010-07-14 17:59:35 -07005952 // start recording
5953 while (!exitPending()) {
5954
5955 processConfigEvents();
5956
5957 { // scope for mLock
5958 Mutex::Autolock _l(mLock);
5959 checkForNewParameters_l();
5960 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5961 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005962 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005963 mStandby = true;
5964 }
5965
5966 if (exitPending()) break;
5967
Eric Laurentfeb0db62011-07-22 09:04:31 -07005968 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005969 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005970 // go to sleep
5971 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005972 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005973 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005974 continue;
5975 }
5976 if (mActiveTrack != 0) {
5977 if (mActiveTrack->mState == TrackBase::PAUSING) {
5978 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005979 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005980 mStandby = true;
5981 }
5982 mActiveTrack.clear();
5983 mStartStopCond.broadcast();
5984 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5985 if (mReqChannelCount != mActiveTrack->channelCount()) {
5986 mActiveTrack.clear();
5987 mStartStopCond.broadcast();
5988 } else if (mBytesRead != 0) {
5989 // record start succeeds only if first read from audio input
5990 // succeeds
5991 if (mBytesRead > 0) {
5992 mActiveTrack->mState = TrackBase::ACTIVE;
5993 } else {
5994 mActiveTrack.clear();
5995 }
5996 mStartStopCond.broadcast();
5997 }
5998 mStandby = false;
5999 }
6000 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006001 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006002 }
6003
6004 if (mActiveTrack != 0) {
6005 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6006 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006007 unlockEffectChains(effectChains);
6008 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006009 continue;
6010 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006011 for (size_t i = 0; i < effectChains.size(); i ++) {
6012 effectChains[i]->process_l();
6013 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006014
Mathias Agopian65ab4712010-07-14 17:59:35 -07006015 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006016 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006017 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006018 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006019 // no resampling
6020 while (framesOut) {
6021 size_t framesIn = mFrameCount - mRsmpInIndex;
6022 if (framesIn) {
6023 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6024 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6025 if (framesIn > framesOut)
6026 framesIn = framesOut;
6027 mRsmpInIndex += framesIn;
6028 framesOut -= framesIn;
6029 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006030 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006031 memcpy(dst, src, framesIn * mFrameSize);
6032 } else {
6033 int16_t *src16 = (int16_t *)src;
6034 int16_t *dst16 = (int16_t *)dst;
6035 if (mChannelCount == 1) {
6036 while (framesIn--) {
6037 *dst16++ = *src16;
6038 *dst16++ = *src16++;
6039 }
6040 } else {
6041 while (framesIn--) {
6042 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
6043 src16 += 2;
6044 }
6045 }
6046 }
6047 }
6048 if (framesOut && mFrameCount == mRsmpInIndex) {
6049 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006050 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006051 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006052 framesOut = 0;
6053 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006054 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006055 mRsmpInIndex = 0;
6056 }
6057 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006058 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006059 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6060 // Force input into standby so that it tries to
6061 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006062 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006063 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006064 }
6065 mRsmpInIndex = mFrameCount;
6066 framesOut = 0;
6067 buffer.frameCount = 0;
6068 }
6069 }
6070 }
6071 } else {
6072 // resampling
6073
6074 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6075 // alter output frame count as if we were expecting stereo samples
6076 if (mChannelCount == 1 && mReqChannelCount == 1) {
6077 framesOut >>= 1;
6078 }
6079 mResampler->resample(mRsmpOutBuffer, framesOut, this);
6080 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6081 // are 32 bit aligned which should be always true.
6082 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006083 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006084 // the resampler always outputs stereo samples: do post stereo to mono conversion
6085 int16_t *src = (int16_t *)mRsmpOutBuffer;
6086 int16_t *dst = buffer.i16;
6087 while (framesOut--) {
6088 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
6089 src += 2;
6090 }
6091 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006092 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006093 }
6094
6095 }
Eric Laurenta011e352012-03-29 15:51:43 -07006096 if (mFramestoDrop == 0) {
6097 mActiveTrack->releaseBuffer(&buffer);
6098 } else {
6099 if (mFramestoDrop > 0) {
6100 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006101 if (mFramestoDrop <= 0) {
6102 clearSyncStartEvent();
6103 }
6104 } else {
6105 mFramestoDrop += buffer.frameCount;
6106 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6107 mSyncStartEvent->isCancelled()) {
6108 ALOGW("Synced record %s, session %d, trigger session %d",
6109 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6110 mActiveTrack->sessionId(),
6111 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6112 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006113 }
6114 }
6115 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006116 mActiveTrack->overflow();
6117 }
6118 // client isn't retrieving buffers fast enough
6119 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006120 if (!mActiveTrack->setOverflow()) {
6121 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006122 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006123 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006124 lastWarning = now;
6125 }
6126 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006127 // Release the processor for a while before asking for a new buffer.
6128 // This will give the application more chance to read from the buffer and
6129 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006130 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006131 }
6132 }
Eric Laurentec437d82011-07-26 20:54:46 -07006133 // enable changes in effect chain
6134 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006135 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006136 }
6137
6138 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006139 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006140 }
6141 mActiveTrack.clear();
6142
6143 mStartStopCond.broadcast();
6144
Eric Laurentfeb0db62011-07-22 09:04:31 -07006145 releaseWakeLock();
6146
Steve Block3856b092011-10-20 11:56:00 +01006147 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006148 return false;
6149}
6150
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006151
6152sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6153 const sp<AudioFlinger::Client>& client,
6154 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006155 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006156 int channelMask,
6157 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006158 int sessionId,
6159 status_t *status)
6160{
6161 sp<RecordTrack> track;
6162 status_t lStatus;
6163
6164 lStatus = initCheck();
6165 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006166 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006167 goto Exit;
6168 }
6169
6170 { // scope for mLock
6171 Mutex::Autolock _l(mLock);
6172
6173 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006174 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006175
Glenn Kasten7378ca52012-01-20 13:44:40 -08006176 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006177 lStatus = NO_MEMORY;
6178 goto Exit;
6179 }
6180
6181 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006182 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6183 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006184 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006185 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6186 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006187 }
6188 lStatus = NO_ERROR;
6189
6190Exit:
6191 if (status) {
6192 *status = lStatus;
6193 }
6194 return track;
6195}
6196
Eric Laurenta011e352012-03-29 15:51:43 -07006197status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006198 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006199 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006200{
Glenn Kasten58912562012-04-03 10:45:00 -07006201 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006202 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006203 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006204
6205 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006206 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006207 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6208 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6209 triggerSession,
6210 recordTrack->sessionId(),
6211 syncStartEventCallback,
6212 this);
Eric Laurent29864602012-05-08 18:57:51 -07006213 // Sync event can be cancelled by the trigger session if the track is not in a
6214 // compatible state in which case we start record immediately
6215 if (mSyncStartEvent->isCancelled()) {
6216 clearSyncStartEvent();
6217 } else {
6218 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6219 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6220 }
Eric Laurenta011e352012-03-29 15:51:43 -07006221 }
6222
Mathias Agopian65ab4712010-07-14 17:59:35 -07006223 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006224 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006225 if (mActiveTrack != 0) {
6226 if (recordTrack != mActiveTrack.get()) {
6227 status = -EBUSY;
6228 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6229 mActiveTrack->mState = TrackBase::ACTIVE;
6230 }
6231 return status;
6232 }
6233
6234 recordTrack->mState = TrackBase::IDLE;
6235 mActiveTrack = recordTrack;
6236 mLock.unlock();
6237 status_t status = AudioSystem::startInput(mId);
6238 mLock.lock();
6239 if (status != NO_ERROR) {
6240 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006241 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006242 return status;
6243 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006244 mRsmpInIndex = mFrameCount;
6245 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006246 if (mResampler != NULL) {
6247 mResampler->reset();
6248 }
6249 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006250 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006251 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006252 mWaitWorkCV.signal();
6253 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006254 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006255 mActiveTrack.clear();
6256 status = INVALID_OPERATION;
6257 goto startError;
6258 }
6259 mStartStopCond.wait(mLock);
6260 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006261 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006262 status = BAD_VALUE;
6263 goto startError;
6264 }
Steve Block3856b092011-10-20 11:56:00 +01006265 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006266 return status;
6267 }
6268startError:
6269 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006270 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006271 return status;
6272}
6273
Eric Laurenta011e352012-03-29 15:51:43 -07006274void AudioFlinger::RecordThread::clearSyncStartEvent()
6275{
6276 if (mSyncStartEvent != 0) {
6277 mSyncStartEvent->cancel();
6278 }
6279 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006280 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006281}
6282
6283void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6284{
6285 sp<SyncEvent> strongEvent = event.promote();
6286
6287 if (strongEvent != 0) {
6288 RecordThread *me = (RecordThread *)strongEvent->cookie();
6289 me->handleSyncStartEvent(strongEvent);
6290 }
6291}
6292
6293void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6294{
Eric Laurent29864602012-05-08 18:57:51 -07006295 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006296 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6297 // from audio HAL
6298 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006299 }
6300}
6301
Mathias Agopian65ab4712010-07-14 17:59:35 -07006302void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006303 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006304 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006305 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006306 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006307 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6308 mActiveTrack->mState = TrackBase::PAUSING;
6309 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006310 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006311 return;
6312 }
6313 mStartStopCond.wait(mLock);
6314 // if we have been restarted, recordTrack == mActiveTrack.get() here
6315 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6316 mLock.unlock();
6317 AudioSystem::stopInput(mId);
6318 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006319 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006320 }
6321 }
6322 }
6323}
6324
Eric Laurenta011e352012-03-29 15:51:43 -07006325bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6326{
6327 return false;
6328}
6329
6330status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6331{
6332 if (!isValidSyncEvent(event)) {
6333 return BAD_VALUE;
6334 }
6335
6336 Mutex::Autolock _l(mLock);
6337
6338 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6339 mTrack->setSyncEvent(event);
6340 return NO_ERROR;
6341 }
6342 return NAME_NOT_FOUND;
6343}
6344
Mathias Agopian65ab4712010-07-14 17:59:35 -07006345status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6346{
6347 const size_t SIZE = 256;
6348 char buffer[SIZE];
6349 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006350
6351 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6352 result.append(buffer);
6353
6354 if (mActiveTrack != 0) {
6355 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006356 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006357 mActiveTrack->dump(buffer, SIZE);
6358 result.append(buffer);
6359
6360 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6361 result.append(buffer);
6362 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6363 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006364 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006365 result.append(buffer);
6366 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6367 result.append(buffer);
6368 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6369 result.append(buffer);
6370
6371
6372 } else {
6373 result.append("No record client\n");
6374 }
6375 write(fd, result.string(), result.size());
6376
6377 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006378 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006379
6380 return NO_ERROR;
6381}
6382
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006383// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006384status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006385{
6386 size_t framesReq = buffer->frameCount;
6387 size_t framesReady = mFrameCount - mRsmpInIndex;
6388 int channelCount;
6389
6390 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006391 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006392 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006393 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006394 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6395 // Force input into standby so that it tries to
6396 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006397 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006398 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006399 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006400 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006401 buffer->frameCount = 0;
6402 return NOT_ENOUGH_DATA;
6403 }
6404 mRsmpInIndex = 0;
6405 framesReady = mFrameCount;
6406 }
6407
6408 if (framesReq > framesReady) {
6409 framesReq = framesReady;
6410 }
6411
6412 if (mChannelCount == 1 && mReqChannelCount == 2) {
6413 channelCount = 1;
6414 } else {
6415 channelCount = 2;
6416 }
6417 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6418 buffer->frameCount = framesReq;
6419 return NO_ERROR;
6420}
6421
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006422// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006423void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6424{
6425 mRsmpInIndex += buffer->frameCount;
6426 buffer->frameCount = 0;
6427}
6428
6429bool AudioFlinger::RecordThread::checkForNewParameters_l()
6430{
6431 bool reconfig = false;
6432
6433 while (!mNewParameters.isEmpty()) {
6434 status_t status = NO_ERROR;
6435 String8 keyValuePair = mNewParameters[0];
6436 AudioParameter param = AudioParameter(keyValuePair);
6437 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006438 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006439 int reqSamplingRate = mReqSampleRate;
6440 int reqChannelCount = mReqChannelCount;
6441
6442 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6443 reqSamplingRate = value;
6444 reconfig = true;
6445 }
6446 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006447 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006448 reconfig = true;
6449 }
6450 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006451 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006452 reconfig = true;
6453 }
6454 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6455 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006456 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006457 // if frame count is changed after track creation
6458 if (mActiveTrack != 0) {
6459 status = INVALID_OPERATION;
6460 } else {
6461 reconfig = true;
6462 }
6463 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006464 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6465 // forward device change to effects that have requested to be
6466 // aware of attached audio device.
6467 for (size_t i = 0; i < mEffectChains.size(); i++) {
6468 mEffectChains[i]->setDevice_l(value);
6469 }
6470 // store input device and output device but do not forward output device to audio HAL.
6471 // Note that status is ignored by the caller for output device
6472 // (see AudioFlinger::setParameters()
Glenn Kasten94479fd2012-07-09 15:39:54 -07006473 uint32_t /*audio_devices_t*/ newDevice = mDevice;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006474 if (value & AUDIO_DEVICE_OUT_ALL) {
Glenn Kasten01542f22012-07-02 12:46:15 -07006475 newDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006476 status = BAD_VALUE;
6477 } else {
Glenn Kasten01542f22012-07-02 12:46:15 -07006478 newDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006479 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6480 if (mTrack != NULL) {
6481 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006482 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006483 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6484 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6485 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006486 }
Glenn Kasten01542f22012-07-02 12:46:15 -07006487 newDevice |= value;
Glenn Kasten94479fd2012-07-09 15:39:54 -07006488 mDevice = (audio_devices_t) newDevice; // since mDevice is read by other threads, only write to it once
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006489 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006490 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006491 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006492 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006493 mInput->stream->common.standby(&mInput->stream->common);
6494 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6495 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006496 }
6497 if (reconfig) {
6498 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006499 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006500 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006501 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006502 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6503 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006504 status = NO_ERROR;
6505 }
6506 if (status == NO_ERROR) {
6507 readInputParameters();
6508 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6509 }
6510 }
6511 }
6512
6513 mNewParameters.removeAt(0);
6514
6515 mParamStatus = status;
6516 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006517 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6518 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006519 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006520 }
6521 return reconfig;
6522}
6523
6524String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6525{
Dima Zavinfce7a472011-04-19 22:30:36 -07006526 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006527 String8 out_s8 = String8();
6528
6529 Mutex::Autolock _l(mLock);
6530 if (initCheck() != NO_ERROR) {
6531 return out_s8;
6532 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006533
Dima Zavin799a70e2011-04-18 16:57:27 -07006534 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006535 out_s8 = String8(s);
6536 free(s);
6537 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006538}
6539
6540void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6541 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006542 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006543
6544 switch (event) {
6545 case AudioSystem::INPUT_OPENED:
6546 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006547 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006548 desc.samplingRate = mSampleRate;
6549 desc.format = mFormat;
6550 desc.frameCount = mFrameCount;
6551 desc.latency = 0;
6552 param2 = &desc;
6553 break;
6554
6555 case AudioSystem::INPUT_CLOSED:
6556 default:
6557 break;
6558 }
6559 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6560}
6561
6562void AudioFlinger::RecordThread::readInputParameters()
6563{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006564 delete mRsmpInBuffer;
6565 // mRsmpInBuffer is always assigned a new[] below
6566 delete mRsmpOutBuffer;
6567 mRsmpOutBuffer = NULL;
6568 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006569 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006570
Dima Zavin799a70e2011-04-18 16:57:27 -07006571 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006572 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6573 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006574 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006575 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006576 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006577 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006578 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006579 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6580
Glenn Kasten53d76db2012-03-08 12:32:47 -08006581 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006582 {
6583 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006584 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6585 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006586 if (mChannelCount == 1 && mReqChannelCount == 2) {
6587 channelCount = 1;
6588 } else {
6589 channelCount = 2;
6590 }
6591 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6592 mResampler->setSampleRate(mSampleRate);
6593 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6594 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6595
6596 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6597 if (mChannelCount == 1 && mReqChannelCount == 1) {
6598 mFrameCount >>= 1;
6599 }
6600
6601 }
6602 mRsmpInIndex = mFrameCount;
6603}
6604
6605unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6606{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006607 Mutex::Autolock _l(mLock);
6608 if (initCheck() != NO_ERROR) {
6609 return 0;
6610 }
6611
Dima Zavin799a70e2011-04-18 16:57:27 -07006612 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006613}
6614
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006615uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6616{
6617 Mutex::Autolock _l(mLock);
6618 uint32_t result = 0;
6619 if (getEffectChain_l(sessionId) != 0) {
6620 result = EFFECT_SESSION;
6621 }
6622
6623 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6624 result |= TRACK_SESSION;
6625 }
6626
6627 return result;
6628}
6629
Eric Laurent59bd0da2011-08-01 09:52:20 -07006630AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6631{
6632 Mutex::Autolock _l(mLock);
6633 return mTrack;
6634}
6635
Glenn Kastenaed850d2012-01-26 09:46:34 -08006636AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006637{
6638 Mutex::Autolock _l(mLock);
6639 return mInput;
6640}
6641
6642AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6643{
6644 Mutex::Autolock _l(mLock);
6645 AudioStreamIn *input = mInput;
6646 mInput = NULL;
6647 return input;
6648}
6649
6650// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006651audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006652{
6653 if (mInput == NULL) {
6654 return NULL;
6655 }
6656 return &mInput->stream->common;
6657}
6658
6659
Mathias Agopian65ab4712010-07-14 17:59:35 -07006660// ----------------------------------------------------------------------------
6661
Eric Laurenta4c5a552012-03-29 10:12:40 -07006662audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6663{
6664 if (!settingsAllowed()) {
6665 return 0;
6666 }
6667 Mutex::Autolock _l(mLock);
6668 return loadHwModule_l(name);
6669}
6670
6671// loadHwModule_l() must be called with AudioFlinger::mLock held
6672audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6673{
6674 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6675 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6676 ALOGW("loadHwModule() module %s already loaded", name);
6677 return mAudioHwDevs.keyAt(i);
6678 }
6679 }
6680
Eric Laurenta4c5a552012-03-29 10:12:40 -07006681 audio_hw_device_t *dev;
6682
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006683 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006684 if (rc) {
6685 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6686 return 0;
6687 }
6688
6689 mHardwareStatus = AUDIO_HW_INIT;
6690 rc = dev->init_check(dev);
6691 mHardwareStatus = AUDIO_HW_IDLE;
6692 if (rc) {
6693 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6694 return 0;
6695 }
6696
6697 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6698 (NULL != dev->set_master_volume)) {
6699 AutoMutex lock(mHardwareLock);
6700 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6701 dev->set_master_volume(dev, mMasterVolume);
6702 mHardwareStatus = AUDIO_HW_IDLE;
6703 }
6704
6705 audio_module_handle_t handle = nextUniqueId();
6706 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6707
6708 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006709 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006710
6711 return handle;
6712
6713}
6714
6715audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6716 audio_devices_t *pDevices,
6717 uint32_t *pSamplingRate,
6718 audio_format_t *pFormat,
6719 audio_channel_mask_t *pChannelMask,
6720 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006721 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006722{
6723 status_t status;
6724 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006725 struct audio_config config = {
6726 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6727 channel_mask: pChannelMask ? *pChannelMask : 0,
6728 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6729 };
6730 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006731 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006732
Eric Laurenta4c5a552012-03-29 10:12:40 -07006733 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6734 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006735 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006736 config.sample_rate,
6737 config.format,
6738 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006739 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006740
6741 if (pDevices == NULL || *pDevices == 0) {
6742 return 0;
6743 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006744
Mathias Agopian65ab4712010-07-14 17:59:35 -07006745 Mutex::Autolock _l(mLock);
6746
Eric Laurenta4c5a552012-03-29 10:12:40 -07006747 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006748 if (outHwDev == NULL)
6749 return 0;
6750
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006751 audio_io_handle_t id = nextUniqueId();
6752
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006753 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006754
6755 status = outHwDev->open_output_stream(outHwDev,
6756 id,
6757 *pDevices,
6758 (audio_output_flags_t)flags,
6759 &config,
6760 &outStream);
6761
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006762 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006763 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006764 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006765 config.sample_rate,
6766 config.format,
6767 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006768 status);
6769
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006770 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006771 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006772
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006773 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006774 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6775 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006776 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006777 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006778 } else {
6779 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006780 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006781 }
6782 mPlaybackThreads.add(id, thread);
6783
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006784 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6785 if (pFormat != NULL) *pFormat = config.format;
6786 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006787 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006788
6789 // notify client processes of the new output creation
6790 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006791
6792 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006793 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006794 ALOGI("Using module %d has the primary audio interface", module);
6795 mPrimaryHardwareDev = outHwDev;
6796
6797 AutoMutex lock(mHardwareLock);
6798 mHardwareStatus = AUDIO_HW_SET_MODE;
6799 outHwDev->set_mode(outHwDev, mMode);
6800
6801 // Determine the level of master volume support the primary audio HAL has,
6802 // and set the initial master volume at the same time.
6803 float initialVolume = 1.0;
6804 mMasterVolumeSupportLvl = MVS_NONE;
6805
6806 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6807 if ((NULL != outHwDev->get_master_volume) &&
6808 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6809 mMasterVolumeSupportLvl = MVS_FULL;
6810 } else {
6811 mMasterVolumeSupportLvl = MVS_SETONLY;
6812 initialVolume = 1.0;
6813 }
6814
6815 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6816 if ((NULL == outHwDev->set_master_volume) ||
6817 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6818 mMasterVolumeSupportLvl = MVS_NONE;
6819 }
6820 // now that we have a primary device, initialize master volume on other devices
6821 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6822 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6823
6824 if ((dev != mPrimaryHardwareDev) &&
6825 (NULL != dev->set_master_volume)) {
6826 dev->set_master_volume(dev, initialVolume);
6827 }
6828 }
6829 mHardwareStatus = AUDIO_HW_IDLE;
6830 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6831 ? initialVolume
6832 : 1.0;
6833 mMasterVolume = initialVolume;
6834 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006835 return id;
6836 }
6837
6838 return 0;
6839}
6840
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006841audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6842 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006843{
6844 Mutex::Autolock _l(mLock);
6845 MixerThread *thread1 = checkMixerThread_l(output1);
6846 MixerThread *thread2 = checkMixerThread_l(output2);
6847
6848 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006849 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006850 return 0;
6851 }
6852
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006853 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006854 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6855 thread->addOutputTrack(thread2);
6856 mPlaybackThreads.add(id, thread);
6857 // notify client processes of the new output creation
6858 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6859 return id;
6860}
6861
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006862status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006863{
6864 // keep strong reference on the playback thread so that
6865 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006866 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006867 {
6868 Mutex::Autolock _l(mLock);
6869 thread = checkPlaybackThread_l(output);
6870 if (thread == NULL) {
6871 return BAD_VALUE;
6872 }
6873
Steve Block3856b092011-10-20 11:56:00 +01006874 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006875
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006876 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006877 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006878 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006879 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6880 dupThread->removeOutputTrack((MixerThread *)thread.get());
6881 }
6882 }
6883 }
Glenn Kastena1117922012-01-26 10:53:32 -08006884 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006885 mPlaybackThreads.removeItem(output);
6886 }
6887 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006888 // The thread entity (active unit of execution) is no longer running here,
6889 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006890
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006891 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006892 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006893 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006894 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006895 out->hwDev->close_output_stream(out->hwDev, out->stream);
6896 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006897 }
6898 return NO_ERROR;
6899}
6900
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006901status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006902{
6903 Mutex::Autolock _l(mLock);
6904 PlaybackThread *thread = checkPlaybackThread_l(output);
6905
6906 if (thread == NULL) {
6907 return BAD_VALUE;
6908 }
6909
Steve Block3856b092011-10-20 11:56:00 +01006910 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006911 thread->suspend();
6912
6913 return NO_ERROR;
6914}
6915
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006916status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006917{
6918 Mutex::Autolock _l(mLock);
6919 PlaybackThread *thread = checkPlaybackThread_l(output);
6920
6921 if (thread == NULL) {
6922 return BAD_VALUE;
6923 }
6924
Steve Block3856b092011-10-20 11:56:00 +01006925 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006926
6927 thread->restore();
6928
6929 return NO_ERROR;
6930}
6931
Eric Laurenta4c5a552012-03-29 10:12:40 -07006932audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6933 audio_devices_t *pDevices,
6934 uint32_t *pSamplingRate,
6935 audio_format_t *pFormat,
6936 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006937{
6938 status_t status;
6939 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006940 struct audio_config config = {
6941 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6942 channel_mask: pChannelMask ? *pChannelMask : 0,
6943 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6944 };
6945 uint32_t reqSamplingRate = config.sample_rate;
6946 audio_format_t reqFormat = config.format;
6947 audio_channel_mask_t reqChannels = config.channel_mask;
6948 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006949 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006950
6951 if (pDevices == NULL || *pDevices == 0) {
6952 return 0;
6953 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006954
Mathias Agopian65ab4712010-07-14 17:59:35 -07006955 Mutex::Autolock _l(mLock);
6956
Eric Laurenta4c5a552012-03-29 10:12:40 -07006957 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006958 if (inHwDev == NULL)
6959 return 0;
6960
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006961 audio_io_handle_t id = nextUniqueId();
6962
6963 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006964 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006965 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006966 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006967 config.sample_rate,
6968 config.format,
6969 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006970 status);
6971
6972 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6973 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6974 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006975 if (status == BAD_VALUE &&
6976 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6977 (config.sample_rate <= 2 * reqSamplingRate) &&
6978 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01006979 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006980 inStream = NULL;
6981 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006982 }
6983
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006984 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006985 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6986
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006987 // Start record thread
6988 // RecorThread require both input and output device indication to forward to audio
6989 // pre processing modules
6990 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6991 thread = new RecordThread(this,
6992 input,
6993 reqSamplingRate,
6994 reqChannels,
6995 id,
6996 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006997 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006998 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006999 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007000 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007001 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007002
Dima Zavin799a70e2011-04-18 16:57:27 -07007003 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007004
7005 // notify client processes of the new input creation
7006 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7007 return id;
7008 }
7009
7010 return 0;
7011}
7012
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007013status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007014{
7015 // keep strong reference on the record thread so that
7016 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007017 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007018 {
7019 Mutex::Autolock _l(mLock);
7020 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007021 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007022 return BAD_VALUE;
7023 }
7024
Steve Block3856b092011-10-20 11:56:00 +01007025 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007026 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007027 mRecordThreads.removeItem(input);
7028 }
7029 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007030 // The thread entity (active unit of execution) is no longer running here,
7031 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007032
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007033 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007034 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007035 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07007036 in->hwDev->close_input_stream(in->hwDev, in->stream);
7037 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007038
7039 return NO_ERROR;
7040}
7041
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007042status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007043{
7044 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007045 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007046
7047 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7048 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007049 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007050 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007051
7052 return NO_ERROR;
7053}
7054
7055
7056int AudioFlinger::newAudioSessionId()
7057{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007058 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007059}
7060
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007061void AudioFlinger::acquireAudioSessionId(int audioSession)
7062{
7063 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007064 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007065 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007066 size_t num = mAudioSessionRefs.size();
7067 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007068 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007069 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7070 ref->mCnt++;
7071 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007072 return;
7073 }
7074 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007075 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7076 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007077}
7078
7079void AudioFlinger::releaseAudioSessionId(int audioSession)
7080{
7081 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007082 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007083 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007084 size_t num = mAudioSessionRefs.size();
7085 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007086 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007087 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7088 ref->mCnt--;
7089 ALOGV(" decremented refcount to %d", ref->mCnt);
7090 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007091 mAudioSessionRefs.removeAt(i);
7092 delete ref;
7093 purgeStaleEffects_l();
7094 }
7095 return;
7096 }
7097 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007098 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007099}
7100
7101void AudioFlinger::purgeStaleEffects_l() {
7102
Steve Block3856b092011-10-20 11:56:00 +01007103 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007104
7105 Vector< sp<EffectChain> > chains;
7106
7107 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7108 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7109 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7110 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007111 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7112 chains.push(ec);
7113 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007114 }
7115 }
7116 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7117 sp<RecordThread> t = mRecordThreads.valueAt(i);
7118 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7119 sp<EffectChain> ec = t->mEffectChains[j];
7120 chains.push(ec);
7121 }
7122 }
7123
7124 for (size_t i = 0; i < chains.size(); i++) {
7125 sp<EffectChain> ec = chains[i];
7126 int sessionid = ec->sessionId();
7127 sp<ThreadBase> t = ec->mThread.promote();
7128 if (t == 0) {
7129 continue;
7130 }
7131 size_t numsessionrefs = mAudioSessionRefs.size();
7132 bool found = false;
7133 for (size_t k = 0; k < numsessionrefs; k++) {
7134 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007135 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007136 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007137 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007138 found = true;
7139 break;
7140 }
7141 }
7142 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007143 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007144 // remove all effects from the chain
7145 while (ec->mEffects.size()) {
7146 sp<EffectModule> effect = ec->mEffects[0];
7147 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007148 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007149 if (effect->purgeHandles()) {
7150 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007151 }
7152 AudioSystem::unregisterEffect(effect->id());
7153 }
7154 }
7155 }
7156 return;
7157}
7158
Mathias Agopian65ab4712010-07-14 17:59:35 -07007159// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007160AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007161{
Glenn Kastena1117922012-01-26 10:53:32 -08007162 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007163}
7164
7165// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007166AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007167{
7168 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007169 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007170}
7171
7172// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007173AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007174{
Glenn Kastena1117922012-01-26 10:53:32 -08007175 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007176}
7177
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007178uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007179{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007180 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007181}
7182
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007183AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007184{
7185 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7186 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007187 AudioStreamOut *output = thread->getOutput();
7188 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007189 return thread;
7190 }
7191 }
7192 return NULL;
7193}
7194
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007195uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007196{
7197 PlaybackThread *thread = primaryPlaybackThread_l();
7198
7199 if (thread == NULL) {
7200 return 0;
7201 }
7202
7203 return thread->device();
7204}
7205
Eric Laurenta011e352012-03-29 15:51:43 -07007206sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7207 int triggerSession,
7208 int listenerSession,
7209 sync_event_callback_t callBack,
7210 void *cookie)
7211{
7212 Mutex::Autolock _l(mLock);
7213
7214 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7215 status_t playStatus = NAME_NOT_FOUND;
7216 status_t recStatus = NAME_NOT_FOUND;
7217 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7218 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7219 if (playStatus == NO_ERROR) {
7220 return event;
7221 }
7222 }
7223 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7224 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7225 if (recStatus == NO_ERROR) {
7226 return event;
7227 }
7228 }
7229 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7230 mPendingSyncEvents.add(event);
7231 } else {
7232 ALOGV("createSyncEvent() invalid event %d", event->type());
7233 event.clear();
7234 }
7235 return event;
7236}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007237
Mathias Agopian65ab4712010-07-14 17:59:35 -07007238// ----------------------------------------------------------------------------
7239// Effect management
7240// ----------------------------------------------------------------------------
7241
7242
Glenn Kastenf587ba52012-01-26 16:25:10 -08007243status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007244{
7245 Mutex::Autolock _l(mLock);
7246 return EffectQueryNumberEffects(numEffects);
7247}
7248
Glenn Kastenf587ba52012-01-26 16:25:10 -08007249status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007250{
7251 Mutex::Autolock _l(mLock);
7252 return EffectQueryEffect(index, descriptor);
7253}
7254
Glenn Kasten5e92a782012-01-30 07:40:52 -08007255status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007256 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007257{
7258 Mutex::Autolock _l(mLock);
7259 return EffectGetDescriptor(pUuid, descriptor);
7260}
7261
7262
Mathias Agopian65ab4712010-07-14 17:59:35 -07007263sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7264 effect_descriptor_t *pDesc,
7265 const sp<IEffectClient>& effectClient,
7266 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007267 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007268 int sessionId,
7269 status_t *status,
7270 int *id,
7271 int *enabled)
7272{
7273 status_t lStatus = NO_ERROR;
7274 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007275 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007276
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007277 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007278 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007279
7280 if (pDesc == NULL) {
7281 lStatus = BAD_VALUE;
7282 goto Exit;
7283 }
7284
Eric Laurent84e9a102010-09-23 16:10:16 -07007285 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007286 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007287 lStatus = PERMISSION_DENIED;
7288 goto Exit;
7289 }
7290
Dima Zavinfce7a472011-04-19 22:30:36 -07007291 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007292 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007293 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007294 lStatus = PERMISSION_DENIED;
7295 goto Exit;
7296 }
7297
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007298 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007299 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007300 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007301 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007302 lStatus = BAD_VALUE;
7303 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007304 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007305 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007306 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007307 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007308 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007309 }
7310 }
7311
Mathias Agopian65ab4712010-07-14 17:59:35 -07007312 {
7313 Mutex::Autolock _l(mLock);
7314
Mathias Agopian65ab4712010-07-14 17:59:35 -07007315
7316 if (!EffectIsNullUuid(&pDesc->uuid)) {
7317 // if uuid is specified, request effect descriptor
7318 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7319 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007320 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007321 goto Exit;
7322 }
7323 } else {
7324 // if uuid is not specified, look for an available implementation
7325 // of the required type in effect factory
7326 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007327 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007328 lStatus = BAD_VALUE;
7329 goto Exit;
7330 }
7331 uint32_t numEffects = 0;
7332 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007333 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007334 bool found = false;
7335
7336 lStatus = EffectQueryNumberEffects(&numEffects);
7337 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007338 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007339 goto Exit;
7340 }
7341 for (uint32_t i = 0; i < numEffects; i++) {
7342 lStatus = EffectQueryEffect(i, &desc);
7343 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007344 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007345 continue;
7346 }
7347 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7348 // If matching type found save effect descriptor. If the session is
7349 // 0 and the effect is not auxiliary, continue enumeration in case
7350 // an auxiliary version of this effect type is available
7351 found = true;
7352 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07007353 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007354 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7355 break;
7356 }
7357 }
7358 }
7359 if (!found) {
7360 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007361 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007362 goto Exit;
7363 }
7364 // For same effect type, chose auxiliary version over insert version if
7365 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007366 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007367 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7368 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7369 }
7370 }
7371
7372 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007373 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007374 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7375 lStatus = INVALID_OPERATION;
7376 goto Exit;
7377 }
7378
Eric Laurent59255e42011-07-27 19:49:51 -07007379 // check recording permission for visualizer
7380 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7381 !recordingAllowed()) {
7382 lStatus = PERMISSION_DENIED;
7383 goto Exit;
7384 }
7385
Mathias Agopian65ab4712010-07-14 17:59:35 -07007386 // return effect descriptor
7387 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7388
7389 // If output is not specified try to find a matching audio session ID in one of the
7390 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007391 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7392 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007393 // Note: io is never 0 when creating an effect on an input
7394 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007395 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007396 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7397 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007398 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007399 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007400 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007401 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007402 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007403 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7404 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7405 io = mRecordThreads.keyAt(i);
7406 break;
7407 }
7408 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007409 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007410 // If no output thread contains the requested session ID, default to
7411 // first output. The effect chain will be moved to the correct output
7412 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007413 if (io == 0 && mPlaybackThreads.size()) {
7414 io = mPlaybackThreads.keyAt(0);
7415 }
Steve Block3856b092011-10-20 11:56:00 +01007416 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007417 }
7418 ThreadBase *thread = checkRecordThread_l(io);
7419 if (thread == NULL) {
7420 thread = checkPlaybackThread_l(io);
7421 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007422 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007423 lStatus = BAD_VALUE;
7424 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007425 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007426 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007427
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007428 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007429
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007430 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007431 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7432 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007433 if (handle != 0 && id != NULL) {
7434 *id = handle->id();
7435 }
7436 }
7437
7438Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007439 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007440 *status = lStatus;
7441 }
7442 return handle;
7443}
7444
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007445status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7446 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007447{
Steve Block3856b092011-10-20 11:56:00 +01007448 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007449 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007450 Mutex::Autolock _l(mLock);
7451 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007452 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007453 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007454 }
Eric Laurentde070132010-07-13 04:45:46 -07007455 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7456 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007457 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007458 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007459 }
Eric Laurentde070132010-07-13 04:45:46 -07007460 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7461 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007462 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007463 return BAD_VALUE;
7464 }
7465
7466 Mutex::Autolock _dl(dstThread->mLock);
7467 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007468 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007469
Mathias Agopian65ab4712010-07-14 17:59:35 -07007470 return NO_ERROR;
7471}
7472
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007473// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007474status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007475 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007476 AudioFlinger::PlaybackThread *dstThread,
7477 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007478{
Steve Block3856b092011-10-20 11:56:00 +01007479 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007480 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007481
Eric Laurent59255e42011-07-27 19:49:51 -07007482 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007483 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007484 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007485 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007486 return INVALID_OPERATION;
7487 }
7488
Eric Laurent39e94f82010-07-28 01:32:47 -07007489 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007490 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007491 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007492 // removed.
7493 srcThread->removeEffectChain_l(chain);
7494
7495 // transfer all effects one by one so that new effect chain is created on new thread with
7496 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007497 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007498 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007499 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007500 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7501 while (effect != 0) {
7502 srcThread->removeEffect_l(effect);
7503 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007504 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7505 if (effect->state() == EffectModule::ACTIVE ||
7506 effect->state() == EffectModule::STOPPING) {
7507 effect->start();
7508 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007509 // if the move request is not received from audio policy manager, the effect must be
7510 // re-registered with the new strategy and output
7511 if (dstChain == 0) {
7512 dstChain = effect->chain().promote();
7513 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007514 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007515 srcThread->addEffect_l(effect);
7516 return NO_INIT;
7517 }
7518 strategy = dstChain->strategy();
7519 }
7520 if (reRegister) {
7521 AudioSystem::unregisterEffect(effect->id());
7522 AudioSystem::registerEffect(&effect->desc(),
7523 dstOutput,
7524 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007525 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007526 effect->id());
7527 }
Eric Laurentde070132010-07-13 04:45:46 -07007528 effect = chain->getEffectFromId_l(0);
7529 }
7530
7531 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007532}
7533
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007534
Mathias Agopian65ab4712010-07-14 17:59:35 -07007535// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007536sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007537 const sp<AudioFlinger::Client>& client,
7538 const sp<IEffectClient>& effectClient,
7539 int32_t priority,
7540 int sessionId,
7541 effect_descriptor_t *desc,
7542 int *enabled,
7543 status_t *status
7544 )
7545{
7546 sp<EffectModule> effect;
7547 sp<EffectHandle> handle;
7548 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007549 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007550 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007551 bool effectCreated = false;
7552 bool effectRegistered = false;
7553
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007554 lStatus = initCheck();
7555 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007556 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007557 goto Exit;
7558 }
7559
7560 // Do not allow effects with session ID 0 on direct output or duplicating threads
7561 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007562 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007563 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007564 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007565 lStatus = BAD_VALUE;
7566 goto Exit;
7567 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007568 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007569 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007570 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007571 desc->name, desc->flags, mType);
7572 lStatus = BAD_VALUE;
7573 goto Exit;
7574 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007575
Steve Block3856b092011-10-20 11:56:00 +01007576 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007577
7578 { // scope for mLock
7579 Mutex::Autolock _l(mLock);
7580
7581 // check for existing effect chain with the requested audio session
7582 chain = getEffectChain_l(sessionId);
7583 if (chain == 0) {
7584 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007585 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007586 chain = new EffectChain(this, sessionId);
7587 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007588 chain->setStrategy(getStrategyForSession_l(sessionId));
7589 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007590 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007591 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007592 }
7593
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007594 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007595
7596 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007597 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007598 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007599 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007600 if (lStatus != NO_ERROR) {
7601 goto Exit;
7602 }
7603 effectRegistered = true;
7604 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007605 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007606 lStatus = effect->status();
7607 if (lStatus != NO_ERROR) {
7608 goto Exit;
7609 }
Eric Laurentcab11242010-07-15 12:50:15 -07007610 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007611 if (lStatus != NO_ERROR) {
7612 goto Exit;
7613 }
7614 effectCreated = true;
7615
7616 effect->setDevice(mDevice);
7617 effect->setMode(mAudioFlinger->getMode());
7618 }
7619 // create effect handle and connect it to effect module
7620 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007621 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007622 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007623 *enabled = (int)effect->isEnabled();
7624 }
7625 }
7626
7627Exit:
7628 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007629 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007630 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007631 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007632 }
7633 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007634 AudioSystem::unregisterEffect(effect->id());
7635 }
7636 if (chainCreated) {
7637 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007638 }
7639 handle.clear();
7640 }
7641
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007642 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007643 *status = lStatus;
7644 }
7645 return handle;
7646}
7647
Eric Laurent717e1282012-06-29 16:36:52 -07007648sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7649{
7650 Mutex::Autolock _l(mLock);
7651 return getEffect_l(sessionId, effectId);
7652}
7653
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007654sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7655{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007656 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007657 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007658}
7659
Eric Laurentde070132010-07-13 04:45:46 -07007660// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7661// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007662status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007663{
7664 // check for existing effect chain with the requested audio session
7665 int sessionId = effect->sessionId();
7666 sp<EffectChain> chain = getEffectChain_l(sessionId);
7667 bool chainCreated = false;
7668
7669 if (chain == 0) {
7670 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007671 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007672 chain = new EffectChain(this, sessionId);
7673 addEffectChain_l(chain);
7674 chain->setStrategy(getStrategyForSession_l(sessionId));
7675 chainCreated = true;
7676 }
Steve Block3856b092011-10-20 11:56:00 +01007677 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007678
7679 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007680 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007681 this, effect->desc().name, chain.get());
7682 return BAD_VALUE;
7683 }
7684
7685 status_t status = chain->addEffect_l(effect);
7686 if (status != NO_ERROR) {
7687 if (chainCreated) {
7688 removeEffectChain_l(chain);
7689 }
7690 return status;
7691 }
7692
7693 effect->setDevice(mDevice);
7694 effect->setMode(mAudioFlinger->getMode());
7695 return NO_ERROR;
7696}
7697
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007698void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007699
Steve Block3856b092011-10-20 11:56:00 +01007700 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007701 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007702 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7703 detachAuxEffect_l(effect->id());
7704 }
7705
7706 sp<EffectChain> chain = effect->chain().promote();
7707 if (chain != 0) {
7708 // remove effect chain if removing last effect
7709 if (chain->removeEffect_l(effect) == 0) {
7710 removeEffectChain_l(chain);
7711 }
7712 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007713 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007714 }
7715}
7716
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007717void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007718 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007719{
7720 effectChains = mEffectChains;
7721 for (size_t i = 0; i < mEffectChains.size(); i++) {
7722 mEffectChains[i]->lock();
7723 }
7724}
7725
7726void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007727 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007728{
7729 for (size_t i = 0; i < effectChains.size(); i++) {
7730 effectChains[i]->unlock();
7731 }
7732}
7733
7734sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7735{
7736 Mutex::Autolock _l(mLock);
7737 return getEffectChain_l(sessionId);
7738}
7739
7740sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7741{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007742 size_t size = mEffectChains.size();
7743 for (size_t i = 0; i < size; i++) {
7744 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007745 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007746 }
7747 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007748 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007749}
7750
Glenn Kastenf78aee72012-01-04 11:00:47 -08007751void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007752{
7753 Mutex::Autolock _l(mLock);
7754 size_t size = mEffectChains.size();
7755 for (size_t i = 0; i < size; i++) {
7756 mEffectChains[i]->setMode_l(mode);
7757 }
7758}
7759
7760void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007761 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007762 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007763
Mathias Agopian65ab4712010-07-14 17:59:35 -07007764 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007765 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007766 // delete the effect module if removing last handle on it
7767 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007768 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007769 removeEffect_l(effect);
7770 AudioSystem::unregisterEffect(effect->id());
7771 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007772 }
7773}
7774
7775status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7776{
7777 int session = chain->sessionId();
7778 int16_t *buffer = mMixBuffer;
7779 bool ownsBuffer = false;
7780
Steve Block3856b092011-10-20 11:56:00 +01007781 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007782 if (session > 0) {
7783 // Only one effect chain can be present in direct output thread and it uses
7784 // the mix buffer as input
7785 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007786 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007787 buffer = new int16_t[numSamples];
7788 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007789 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007790 ownsBuffer = true;
7791 }
7792
7793 // Attach all tracks with same session ID to this chain.
7794 for (size_t i = 0; i < mTracks.size(); ++i) {
7795 sp<Track> track = mTracks[i];
7796 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007797 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007798 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007799 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007800 }
7801 }
7802
7803 // indicate all active tracks in the chain
7804 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7805 sp<Track> track = mActiveTracks[i].promote();
7806 if (track == 0) continue;
7807 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007808 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007809 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007810 }
7811 }
7812 }
7813
7814 chain->setInBuffer(buffer, ownsBuffer);
7815 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007816 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007817 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007818 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7819 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007820 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007821 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7822 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007823 // Effect chain for other sessions are inserted at beginning of effect
7824 // chains list to be processed before output mix effects. Relative order between other
7825 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007826 size_t size = mEffectChains.size();
7827 size_t i = 0;
7828 for (i = 0; i < size; i++) {
7829 if (mEffectChains[i]->sessionId() < session) break;
7830 }
7831 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007832 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007833
7834 return NO_ERROR;
7835}
7836
7837size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7838{
7839 int session = chain->sessionId();
7840
Steve Block3856b092011-10-20 11:56:00 +01007841 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007842
7843 for (size_t i = 0; i < mEffectChains.size(); i++) {
7844 if (chain == mEffectChains[i]) {
7845 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007846 // detach all active tracks from the chain
7847 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7848 sp<Track> track = mActiveTracks[i].promote();
7849 if (track == 0) continue;
7850 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007851 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007852 chain.get(), session);
7853 chain->decActiveTrackCnt();
7854 }
7855 }
7856
Mathias Agopian65ab4712010-07-14 17:59:35 -07007857 // detach all tracks with same session ID from this chain
7858 for (size_t i = 0; i < mTracks.size(); ++i) {
7859 sp<Track> track = mTracks[i];
7860 if (session == track->sessionId()) {
7861 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007862 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007863 }
7864 }
Eric Laurentde070132010-07-13 04:45:46 -07007865 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007866 }
7867 }
7868 return mEffectChains.size();
7869}
7870
Eric Laurentde070132010-07-13 04:45:46 -07007871status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7872 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007873{
7874 Mutex::Autolock _l(mLock);
7875 return attachAuxEffect_l(track, EffectId);
7876}
7877
Eric Laurentde070132010-07-13 04:45:46 -07007878status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7879 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007880{
7881 status_t status = NO_ERROR;
7882
7883 if (EffectId == 0) {
7884 track->setAuxBuffer(0, NULL);
7885 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007886 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7887 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007888 if (effect != 0) {
7889 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7890 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7891 } else {
7892 status = INVALID_OPERATION;
7893 }
7894 } else {
7895 status = BAD_VALUE;
7896 }
7897 }
7898 return status;
7899}
7900
7901void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7902{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007903 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007904 sp<Track> track = mTracks[i];
7905 if (track->auxEffectId() == effectId) {
7906 attachAuxEffect_l(track, 0);
7907 }
7908 }
7909}
7910
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007911status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7912{
7913 // only one chain per input thread
7914 if (mEffectChains.size() != 0) {
7915 return INVALID_OPERATION;
7916 }
Steve Block3856b092011-10-20 11:56:00 +01007917 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007918
7919 chain->setInBuffer(NULL);
7920 chain->setOutBuffer(NULL);
7921
Eric Laurent59255e42011-07-27 19:49:51 -07007922 checkSuspendOnAddEffectChain_l(chain);
7923
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007924 mEffectChains.add(chain);
7925
7926 return NO_ERROR;
7927}
7928
7929size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7930{
Steve Block3856b092011-10-20 11:56:00 +01007931 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007932 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007933 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7934 chain.get(), mEffectChains.size(), this);
7935 if (mEffectChains.size() == 1) {
7936 mEffectChains.removeAt(0);
7937 }
7938 return 0;
7939}
7940
Mathias Agopian65ab4712010-07-14 17:59:35 -07007941// ----------------------------------------------------------------------------
7942// EffectModule implementation
7943// ----------------------------------------------------------------------------
7944
7945#undef LOG_TAG
7946#define LOG_TAG "AudioFlinger::EffectModule"
7947
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007948AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007949 const wp<AudioFlinger::EffectChain>& chain,
7950 effect_descriptor_t *desc,
7951 int id,
7952 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07007953 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
7954 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
7955 // mDescriptor is set below
7956 // mConfig is set by configure() and not used before then
7957 mEffectInterface(NULL),
7958 mStatus(NO_INIT), mState(IDLE),
7959 // mMaxDisableWaitCnt is set by configure() and not used before then
7960 // mDisableWaitCnt is set by process() and updateState() and not used before then
7961 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007962{
Steve Block3856b092011-10-20 11:56:00 +01007963 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007964 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007965 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007966 return;
7967 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007968
7969 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7970
7971 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007972 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007973
7974 if (mStatus != NO_ERROR) {
7975 return;
7976 }
7977 lStatus = init();
7978 if (lStatus < 0) {
7979 mStatus = lStatus;
7980 goto Error;
7981 }
7982
Steve Block3856b092011-10-20 11:56:00 +01007983 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007984 return;
7985Error:
7986 EffectRelease(mEffectInterface);
7987 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007988 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007989}
7990
7991AudioFlinger::EffectModule::~EffectModule()
7992{
Steve Block3856b092011-10-20 11:56:00 +01007993 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007994 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007995 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7996 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7997 sp<ThreadBase> thread = mThread.promote();
7998 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007999 audio_stream_t *stream = thread->stream();
8000 if (stream != NULL) {
8001 stream->remove_audio_effect(stream, mEffectInterface);
8002 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008003 }
8004 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008005 // release effect engine
8006 EffectRelease(mEffectInterface);
8007 }
8008}
8009
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008010status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008011{
8012 status_t status;
8013
8014 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008015 int priority = handle->priority();
8016 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008017 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008018 size_t i;
8019 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008020 EffectHandle *h = mHandles[i];
8021 if (h == NULL || h->destroyed_l()) continue;
8022 // first non destroyed handle is considered in control
8023 if (controlHandle == NULL)
8024 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008025 if (h->priority() <= priority) break;
8026 }
8027 // if inserted in first place, move effect control from previous owner to this handle
8028 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008029 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008030 if (controlHandle != NULL) {
8031 enabled = controlHandle->enabled();
8032 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008033 }
Eric Laurent59255e42011-07-27 19:49:51 -07008034 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008035 status = NO_ERROR;
8036 } else {
8037 status = ALREADY_EXISTS;
8038 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008039 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008040 mHandles.insertAt(handle, i);
8041 return status;
8042}
8043
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008044size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008045{
8046 Mutex::Autolock _l(mLock);
8047 size_t size = mHandles.size();
8048 size_t i;
8049 for (i = 0; i < size; i++) {
8050 if (mHandles[i] == handle) break;
8051 }
8052 if (i == size) {
8053 return size;
8054 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008055 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008056
Mathias Agopian65ab4712010-07-14 17:59:35 -07008057 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008058 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008059 if (i == 0) {
8060 EffectHandle *h = controlHandle_l();
8061 if (h != NULL) {
8062 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008063 }
8064 }
8065
Eric Laurentec437d82011-07-26 20:54:46 -07008066 // Prevent calls to process() and other functions on effect interface from now on.
8067 // The effect engine will be released by the destructor when the last strong reference on
8068 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008069 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008070 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008071 }
8072
Mathias Agopian65ab4712010-07-14 17:59:35 -07008073 return size;
8074}
8075
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008076// must be called with EffectModule::mLock held
8077AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008078{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008079 // the first valid handle in the list has control over the module
8080 for (size_t i = 0; i < mHandles.size(); i++) {
8081 EffectHandle *h = mHandles[i];
8082 if (h != NULL && !h->destroyed_l()) {
8083 return h;
8084 }
8085 }
8086
8087 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008088}
8089
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008090size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008091{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008092 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008093 // keep a strong reference on this EffectModule to avoid calling the
8094 // destructor before we exit
8095 sp<EffectModule> keep(this);
8096 {
8097 sp<ThreadBase> thread = mThread.promote();
8098 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008099 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008100 }
8101 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008102 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008103}
8104
8105void AudioFlinger::EffectModule::updateState() {
8106 Mutex::Autolock _l(mLock);
8107
8108 switch (mState) {
8109 case RESTART:
8110 reset_l();
8111 // FALL THROUGH
8112
8113 case STARTING:
8114 // clear auxiliary effect input buffer for next accumulation
8115 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8116 memset(mConfig.inputCfg.buffer.raw,
8117 0,
8118 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8119 }
8120 start_l();
8121 mState = ACTIVE;
8122 break;
8123 case STOPPING:
8124 stop_l();
8125 mDisableWaitCnt = mMaxDisableWaitCnt;
8126 mState = STOPPED;
8127 break;
8128 case STOPPED:
8129 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8130 // turn off sequence.
8131 if (--mDisableWaitCnt == 0) {
8132 reset_l();
8133 mState = IDLE;
8134 }
8135 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008136 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008137 break;
8138 }
8139}
8140
8141void AudioFlinger::EffectModule::process()
8142{
8143 Mutex::Autolock _l(mLock);
8144
Eric Laurentec437d82011-07-26 20:54:46 -07008145 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008146 mConfig.inputCfg.buffer.raw == NULL ||
8147 mConfig.outputCfg.buffer.raw == NULL) {
8148 return;
8149 }
8150
Eric Laurent8f45bd72010-08-31 13:50:07 -07008151 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008152 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8153 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008154 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008155 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008156 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008157 }
8158
8159 // do the actual processing in the effect engine
8160 int ret = (*mEffectInterface)->process(mEffectInterface,
8161 &mConfig.inputCfg.buffer,
8162 &mConfig.outputCfg.buffer);
8163
8164 // force transition to IDLE state when engine is ready
8165 if (mState == STOPPED && ret == -ENODATA) {
8166 mDisableWaitCnt = 1;
8167 }
8168
8169 // clear auxiliary effect input buffer for next accumulation
8170 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008171 memset(mConfig.inputCfg.buffer.raw, 0,
8172 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008173 }
8174 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008175 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8176 // If an insert effect is idle and input buffer is different from output buffer,
8177 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008178 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008179 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008180 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8181 int16_t *in = mConfig.inputCfg.buffer.s16;
8182 int16_t *out = mConfig.outputCfg.buffer.s16;
8183 for (size_t i = 0; i < frameCnt; i++) {
8184 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008185 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008186 }
8187 }
8188}
8189
8190void AudioFlinger::EffectModule::reset_l()
8191{
8192 if (mEffectInterface == NULL) {
8193 return;
8194 }
8195 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8196}
8197
8198status_t AudioFlinger::EffectModule::configure()
8199{
8200 uint32_t channels;
8201 if (mEffectInterface == NULL) {
8202 return NO_INIT;
8203 }
8204
8205 sp<ThreadBase> thread = mThread.promote();
8206 if (thread == 0) {
8207 return DEAD_OBJECT;
8208 }
8209
8210 // TODO: handle configuration of effects replacing track process
8211 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008212 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008213 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07008214 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008215 }
8216
8217 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008218 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008219 } else {
8220 mConfig.inputCfg.channels = channels;
8221 }
8222 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07008223 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8224 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008225 mConfig.inputCfg.samplingRate = thread->sampleRate();
8226 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8227 mConfig.inputCfg.bufferProvider.cookie = NULL;
8228 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8229 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8230 mConfig.outputCfg.bufferProvider.cookie = NULL;
8231 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8232 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8233 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8234 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008235 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008236 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008237 // - in other sessions:
8238 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8239 // other effect: overwrites output buffer: input buffer == output buffer
8240 // Auxiliary effect:
8241 // accumulates in output buffer: input buffer != output buffer
8242 // Therefore: accumulate <=> input buffer != output buffer
8243 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8244 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8245 } else {
8246 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8247 }
8248 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8249 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8250 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8251 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8252
Steve Block3856b092011-10-20 11:56:00 +01008253 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008254 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8255
Mathias Agopian65ab4712010-07-14 17:59:35 -07008256 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008257 uint32_t size = sizeof(int);
8258 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008259 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008260 sizeof(effect_config_t),
8261 &mConfig,
8262 &size,
8263 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008264 if (status == 0) {
8265 status = cmdStatus;
8266 }
8267
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008268 if (status == 0 &&
8269 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8270 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8271 effect_param_t *p = (effect_param_t *)buf32;
8272
8273 p->psize = sizeof(uint32_t);
8274 p->vsize = sizeof(uint32_t);
8275 size = sizeof(int);
8276 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8277
8278 uint32_t latency = 0;
8279 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8280 if (pbt != NULL) {
8281 latency = pbt->latency_l();
8282 }
8283
8284 *((int32_t *)p->data + 1)= latency;
8285 (*mEffectInterface)->command(mEffectInterface,
8286 EFFECT_CMD_SET_PARAM,
8287 sizeof(effect_param_t) + 8,
8288 &buf32,
8289 &size,
8290 &cmdStatus);
8291 }
8292
Mathias Agopian65ab4712010-07-14 17:59:35 -07008293 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8294 (1000 * mConfig.outputCfg.buffer.frameCount);
8295
8296 return status;
8297}
8298
8299status_t AudioFlinger::EffectModule::init()
8300{
8301 Mutex::Autolock _l(mLock);
8302 if (mEffectInterface == NULL) {
8303 return NO_INIT;
8304 }
8305 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008306 uint32_t size = sizeof(status_t);
8307 status_t status = (*mEffectInterface)->command(mEffectInterface,
8308 EFFECT_CMD_INIT,
8309 0,
8310 NULL,
8311 &size,
8312 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008313 if (status == 0) {
8314 status = cmdStatus;
8315 }
8316 return status;
8317}
8318
Eric Laurentec35a142011-10-05 17:42:25 -07008319status_t AudioFlinger::EffectModule::start()
8320{
8321 Mutex::Autolock _l(mLock);
8322 return start_l();
8323}
8324
Mathias Agopian65ab4712010-07-14 17:59:35 -07008325status_t AudioFlinger::EffectModule::start_l()
8326{
8327 if (mEffectInterface == NULL) {
8328 return NO_INIT;
8329 }
8330 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008331 uint32_t size = sizeof(status_t);
8332 status_t status = (*mEffectInterface)->command(mEffectInterface,
8333 EFFECT_CMD_ENABLE,
8334 0,
8335 NULL,
8336 &size,
8337 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008338 if (status == 0) {
8339 status = cmdStatus;
8340 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008341 if (status == 0 &&
8342 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8343 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8344 sp<ThreadBase> thread = mThread.promote();
8345 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008346 audio_stream_t *stream = thread->stream();
8347 if (stream != NULL) {
8348 stream->add_audio_effect(stream, mEffectInterface);
8349 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008350 }
8351 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008352 return status;
8353}
8354
Eric Laurentec437d82011-07-26 20:54:46 -07008355status_t AudioFlinger::EffectModule::stop()
8356{
8357 Mutex::Autolock _l(mLock);
8358 return stop_l();
8359}
8360
Mathias Agopian65ab4712010-07-14 17:59:35 -07008361status_t AudioFlinger::EffectModule::stop_l()
8362{
8363 if (mEffectInterface == NULL) {
8364 return NO_INIT;
8365 }
8366 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008367 uint32_t size = sizeof(status_t);
8368 status_t status = (*mEffectInterface)->command(mEffectInterface,
8369 EFFECT_CMD_DISABLE,
8370 0,
8371 NULL,
8372 &size,
8373 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008374 if (status == 0) {
8375 status = cmdStatus;
8376 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008377 if (status == 0 &&
8378 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8379 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8380 sp<ThreadBase> thread = mThread.promote();
8381 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008382 audio_stream_t *stream = thread->stream();
8383 if (stream != NULL) {
8384 stream->remove_audio_effect(stream, mEffectInterface);
8385 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008386 }
8387 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008388 return status;
8389}
8390
Eric Laurent25f43952010-07-28 05:40:18 -07008391status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8392 uint32_t cmdSize,
8393 void *pCmdData,
8394 uint32_t *replySize,
8395 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008396{
8397 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008398// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008399
Eric Laurentec437d82011-07-26 20:54:46 -07008400 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008401 return NO_INIT;
8402 }
Eric Laurent25f43952010-07-28 05:40:18 -07008403 status_t status = (*mEffectInterface)->command(mEffectInterface,
8404 cmdCode,
8405 cmdSize,
8406 pCmdData,
8407 replySize,
8408 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008409 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008410 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008411 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008412 EffectHandle *h = mHandles[i];
8413 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008414 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8415 }
8416 }
8417 }
8418 return status;
8419}
8420
8421status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8422{
8423 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008424 return setEnabled_l(enabled);
8425}
8426
8427// must be called with EffectModule::mLock held
8428status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8429{
8430
Steve Block3856b092011-10-20 11:56:00 +01008431 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008432
8433 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008434 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8435 if (enabled && status != NO_ERROR) {
8436 return status;
8437 }
8438
Mathias Agopian65ab4712010-07-14 17:59:35 -07008439 switch (mState) {
8440 // going from disabled to enabled
8441 case IDLE:
8442 mState = STARTING;
8443 break;
8444 case STOPPED:
8445 mState = RESTART;
8446 break;
8447 case STOPPING:
8448 mState = ACTIVE;
8449 break;
8450
8451 // going from enabled to disabled
8452 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008453 mState = STOPPED;
8454 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008455 case STARTING:
8456 mState = IDLE;
8457 break;
8458 case ACTIVE:
8459 mState = STOPPING;
8460 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008461 case DESTROYED:
8462 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008463 }
8464 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008465 EffectHandle *h = mHandles[i];
8466 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008467 h->setEnabled(enabled);
8468 }
8469 }
8470 }
8471 return NO_ERROR;
8472}
8473
Glenn Kastenc59c0042012-02-02 14:06:11 -08008474bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008475{
8476 switch (mState) {
8477 case RESTART:
8478 case STARTING:
8479 case ACTIVE:
8480 return true;
8481 case IDLE:
8482 case STOPPING:
8483 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008484 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008485 default:
8486 return false;
8487 }
8488}
8489
Glenn Kastenc59c0042012-02-02 14:06:11 -08008490bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008491{
8492 switch (mState) {
8493 case RESTART:
8494 case ACTIVE:
8495 case STOPPING:
8496 case STOPPED:
8497 return true;
8498 case IDLE:
8499 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008500 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008501 default:
8502 return false;
8503 }
8504}
8505
Mathias Agopian65ab4712010-07-14 17:59:35 -07008506status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8507{
8508 Mutex::Autolock _l(mLock);
8509 status_t status = NO_ERROR;
8510
8511 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8512 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008513 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008514 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8515 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008516 status_t cmdStatus;
8517 uint32_t volume[2];
8518 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008519 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008520 volume[0] = *left;
8521 volume[1] = *right;
8522 if (controller) {
8523 pVolume = volume;
8524 }
Eric Laurent25f43952010-07-28 05:40:18 -07008525 status = (*mEffectInterface)->command(mEffectInterface,
8526 EFFECT_CMD_SET_VOLUME,
8527 size,
8528 volume,
8529 &size,
8530 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008531 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8532 *left = volume[0];
8533 *right = volume[1];
8534 }
8535 }
8536 return status;
8537}
8538
8539status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8540{
8541 Mutex::Autolock _l(mLock);
8542 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008543 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8544 // audio pre processing modules on RecordThread can receive both output and
8545 // input device indication in the same call
8546 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8547 if (dev) {
8548 status_t cmdStatus;
8549 uint32_t size = sizeof(status_t);
8550
8551 status = (*mEffectInterface)->command(mEffectInterface,
8552 EFFECT_CMD_SET_DEVICE,
8553 sizeof(uint32_t),
8554 &dev,
8555 &size,
8556 &cmdStatus);
8557 if (status == NO_ERROR) {
8558 status = cmdStatus;
8559 }
8560 }
8561 dev = device & AUDIO_DEVICE_IN_ALL;
8562 if (dev) {
8563 status_t cmdStatus;
8564 uint32_t size = sizeof(status_t);
8565
8566 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8567 EFFECT_CMD_SET_INPUT_DEVICE,
8568 sizeof(uint32_t),
8569 &dev,
8570 &size,
8571 &cmdStatus);
8572 if (status2 == NO_ERROR) {
8573 status2 = cmdStatus;
8574 }
8575 if (status == NO_ERROR) {
8576 status = status2;
8577 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008578 }
8579 }
8580 return status;
8581}
8582
Glenn Kastenf78aee72012-01-04 11:00:47 -08008583status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008584{
8585 Mutex::Autolock _l(mLock);
8586 status_t status = NO_ERROR;
8587 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008588 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008589 uint32_t size = sizeof(status_t);
8590 status = (*mEffectInterface)->command(mEffectInterface,
8591 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008592 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008593 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008594 &size,
8595 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008596 if (status == NO_ERROR) {
8597 status = cmdStatus;
8598 }
8599 }
8600 return status;
8601}
8602
Eric Laurent59255e42011-07-27 19:49:51 -07008603void AudioFlinger::EffectModule::setSuspended(bool suspended)
8604{
8605 Mutex::Autolock _l(mLock);
8606 mSuspended = suspended;
8607}
Glenn Kastena3a85482012-01-04 11:01:11 -08008608
8609bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008610{
8611 Mutex::Autolock _l(mLock);
8612 return mSuspended;
8613}
8614
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008615bool AudioFlinger::EffectModule::purgeHandles()
8616{
8617 bool enabled = false;
8618 Mutex::Autolock _l(mLock);
8619 for (size_t i = 0; i < mHandles.size(); i++) {
8620 EffectHandle *handle = mHandles[i];
8621 if (handle != NULL && !handle->destroyed_l()) {
8622 handle->effect().clear();
8623 if (handle->hasControl()) {
8624 enabled = handle->enabled();
8625 }
8626 }
8627 }
8628 return enabled;
8629}
8630
Mathias Agopian65ab4712010-07-14 17:59:35 -07008631status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8632{
8633 const size_t SIZE = 256;
8634 char buffer[SIZE];
8635 String8 result;
8636
8637 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8638 result.append(buffer);
8639
8640 bool locked = tryLock(mLock);
8641 // failed to lock - AudioFlinger is probably deadlocked
8642 if (!locked) {
8643 result.append("\t\tCould not lock Fx mutex:\n");
8644 }
8645
8646 result.append("\t\tSession Status State Engine:\n");
8647 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8648 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8649 result.append(buffer);
8650
8651 result.append("\t\tDescriptor:\n");
8652 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8653 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8654 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8655 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8656 result.append(buffer);
8657 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8658 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8659 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8660 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8661 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008662 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008663 mDescriptor.apiVersion,
8664 mDescriptor.flags);
8665 result.append(buffer);
8666 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8667 mDescriptor.name);
8668 result.append(buffer);
8669 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8670 mDescriptor.implementor);
8671 result.append(buffer);
8672
8673 result.append("\t\t- Input configuration:\n");
8674 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8675 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8676 (uint32_t)mConfig.inputCfg.buffer.raw,
8677 mConfig.inputCfg.buffer.frameCount,
8678 mConfig.inputCfg.samplingRate,
8679 mConfig.inputCfg.channels,
8680 mConfig.inputCfg.format);
8681 result.append(buffer);
8682
8683 result.append("\t\t- Output configuration:\n");
8684 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8685 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8686 (uint32_t)mConfig.outputCfg.buffer.raw,
8687 mConfig.outputCfg.buffer.frameCount,
8688 mConfig.outputCfg.samplingRate,
8689 mConfig.outputCfg.channels,
8690 mConfig.outputCfg.format);
8691 result.append(buffer);
8692
8693 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8694 result.append(buffer);
8695 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8696 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008697 EffectHandle *handle = mHandles[i];
8698 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008699 handle->dump(buffer, SIZE);
8700 result.append(buffer);
8701 }
8702 }
8703
8704 result.append("\n");
8705
8706 write(fd, result.string(), result.length());
8707
8708 if (locked) {
8709 mLock.unlock();
8710 }
8711
8712 return NO_ERROR;
8713}
8714
8715// ----------------------------------------------------------------------------
8716// EffectHandle implementation
8717// ----------------------------------------------------------------------------
8718
8719#undef LOG_TAG
8720#define LOG_TAG "AudioFlinger::EffectHandle"
8721
8722AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8723 const sp<AudioFlinger::Client>& client,
8724 const sp<IEffectClient>& effectClient,
8725 int32_t priority)
8726 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008727 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008728 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008729{
Steve Block3856b092011-10-20 11:56:00 +01008730 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008731
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008732 if (client == 0) {
8733 return;
8734 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008735 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8736 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8737 if (mCblkMemory != 0) {
8738 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8739
Glenn Kastena0d68332012-01-27 16:47:15 -08008740 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008741 new(mCblk) effect_param_cblk_t();
8742 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008743 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008744 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008745 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008746 return;
8747 }
8748}
8749
8750AudioFlinger::EffectHandle::~EffectHandle()
8751{
Steve Block3856b092011-10-20 11:56:00 +01008752 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008753
8754 if (mEffect == 0) {
8755 mDestroyed = true;
8756 return;
8757 }
8758 mEffect->lock();
8759 mDestroyed = true;
8760 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008761 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008762}
8763
8764status_t AudioFlinger::EffectHandle::enable()
8765{
Steve Block3856b092011-10-20 11:56:00 +01008766 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008767 if (!mHasControl) return INVALID_OPERATION;
8768 if (mEffect == 0) return DEAD_OBJECT;
8769
Eric Laurentdb7c0792011-08-10 10:37:50 -07008770 if (mEnabled) {
8771 return NO_ERROR;
8772 }
8773
Eric Laurent59255e42011-07-27 19:49:51 -07008774 mEnabled = true;
8775
8776 sp<ThreadBase> thread = mEffect->thread().promote();
8777 if (thread != 0) {
8778 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8779 }
8780
8781 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8782 if (mEffect->suspended()) {
8783 return NO_ERROR;
8784 }
8785
Eric Laurentdb7c0792011-08-10 10:37:50 -07008786 status_t status = mEffect->setEnabled(true);
8787 if (status != NO_ERROR) {
8788 if (thread != 0) {
8789 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8790 }
8791 mEnabled = false;
8792 }
8793 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008794}
8795
8796status_t AudioFlinger::EffectHandle::disable()
8797{
Steve Block3856b092011-10-20 11:56:00 +01008798 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008799 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008800 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008801
Eric Laurentdb7c0792011-08-10 10:37:50 -07008802 if (!mEnabled) {
8803 return NO_ERROR;
8804 }
Eric Laurent59255e42011-07-27 19:49:51 -07008805 mEnabled = false;
8806
8807 if (mEffect->suspended()) {
8808 return NO_ERROR;
8809 }
8810
8811 status_t status = mEffect->setEnabled(false);
8812
8813 sp<ThreadBase> thread = mEffect->thread().promote();
8814 if (thread != 0) {
8815 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8816 }
8817
8818 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008819}
8820
8821void AudioFlinger::EffectHandle::disconnect()
8822{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008823 disconnect(true);
8824}
8825
Glenn Kasten58123c32012-02-03 10:32:24 -08008826void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008827{
Glenn Kasten58123c32012-02-03 10:32:24 -08008828 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008829 if (mEffect == 0) {
8830 return;
8831 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008832 // restore suspended effects if the disconnected handle was enabled and the last one.
8833 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008834 sp<ThreadBase> thread = mEffect->thread().promote();
8835 if (thread != 0) {
8836 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8837 }
Eric Laurent59255e42011-07-27 19:49:51 -07008838 }
8839
Mathias Agopian65ab4712010-07-14 17:59:35 -07008840 // release sp on module => module destructor can be called now
8841 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008842 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008843 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008844 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008845 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8846 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008847 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008848 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008849 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8850 mClient.clear();
8851 }
8852}
8853
Eric Laurent25f43952010-07-28 05:40:18 -07008854status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8855 uint32_t cmdSize,
8856 void *pCmdData,
8857 uint32_t *replySize,
8858 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008859{
Steve Block3856b092011-10-20 11:56:00 +01008860// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008861// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008862
8863 // only get parameter command is permitted for applications not controlling the effect
8864 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8865 return INVALID_OPERATION;
8866 }
8867 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008868 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008869
8870 // handle commands that are not forwarded transparently to effect engine
8871 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8872 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8873 // no risk to block the whole media server process or mixer threads is we are stuck here
8874 Mutex::Autolock _l(mCblk->lock);
8875 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8876 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8877 mCblk->serverIndex = 0;
8878 mCblk->clientIndex = 0;
8879 return BAD_VALUE;
8880 }
8881 status_t status = NO_ERROR;
8882 while (mCblk->serverIndex < mCblk->clientIndex) {
8883 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008884 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008885 int *p = (int *)(mBuffer + mCblk->serverIndex);
8886 int size = *p++;
8887 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008888 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008889 break;
8890 }
8891 effect_param_t *param = (effect_param_t *)p;
8892 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008893 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008894 mCblk->serverIndex += size;
8895 continue;
8896 }
Eric Laurent25f43952010-07-28 05:40:18 -07008897 uint32_t psize = sizeof(effect_param_t) +
8898 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8899 param->vsize;
8900 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8901 psize,
8902 p,
8903 &rsize,
8904 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008905 // stop at first error encountered
8906 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008907 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008908 *(int *)pReplyData = reply;
8909 break;
8910 } else if (reply != NO_ERROR) {
8911 *(int *)pReplyData = reply;
8912 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008913 }
8914 mCblk->serverIndex += size;
8915 }
8916 mCblk->serverIndex = 0;
8917 mCblk->clientIndex = 0;
8918 return status;
8919 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008920 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008921 return enable();
8922 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008923 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008924 return disable();
8925 }
8926
8927 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8928}
8929
Eric Laurent59255e42011-07-27 19:49:51 -07008930void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008931{
Steve Block3856b092011-10-20 11:56:00 +01008932 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008933
8934 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008935 mEnabled = enabled;
8936
Mathias Agopian65ab4712010-07-14 17:59:35 -07008937 if (signal && mEffectClient != 0) {
8938 mEffectClient->controlStatusChanged(hasControl);
8939 }
8940}
8941
Eric Laurent25f43952010-07-28 05:40:18 -07008942void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8943 uint32_t cmdSize,
8944 void *pCmdData,
8945 uint32_t replySize,
8946 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008947{
8948 if (mEffectClient != 0) {
8949 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8950 }
8951}
8952
8953
8954
8955void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8956{
8957 if (mEffectClient != 0) {
8958 mEffectClient->enableStatusChanged(enabled);
8959 }
8960}
8961
8962status_t AudioFlinger::EffectHandle::onTransact(
8963 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8964{
8965 return BnEffect::onTransact(code, data, reply, flags);
8966}
8967
8968
8969void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8970{
Glenn Kastena0d68332012-01-27 16:47:15 -08008971 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008972
8973 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008974 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008975 mPriority,
8976 mHasControl,
8977 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008978 mCblk ? mCblk->clientIndex : 0,
8979 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008980 );
8981
8982 if (locked) {
8983 mCblk->lock.unlock();
8984 }
8985}
8986
8987#undef LOG_TAG
8988#define LOG_TAG "AudioFlinger::EffectChain"
8989
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008990AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008991 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008992 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008993 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8994 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008995{
Dima Zavinfce7a472011-04-19 22:30:36 -07008996 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008997 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008998 return;
8999 }
9000 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
9001 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009002}
9003
9004AudioFlinger::EffectChain::~EffectChain()
9005{
9006 if (mOwnInBuffer) {
9007 delete mInBuffer;
9008 }
9009
9010}
9011
Eric Laurent59255e42011-07-27 19:49:51 -07009012// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009013sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009014{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009015 size_t size = mEffects.size();
9016
9017 for (size_t i = 0; i < size; i++) {
9018 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009019 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009020 }
9021 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009022 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009023}
9024
Eric Laurent59255e42011-07-27 19:49:51 -07009025// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009026sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009027{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009028 size_t size = mEffects.size();
9029
9030 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009031 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9032 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009033 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009034 }
9035 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009036 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009037}
9038
Eric Laurent59255e42011-07-27 19:49:51 -07009039// getEffectFromType_l() must be called with ThreadBase::mLock held
9040sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9041 const effect_uuid_t *type)
9042{
Eric Laurent59255e42011-07-27 19:49:51 -07009043 size_t size = mEffects.size();
9044
9045 for (size_t i = 0; i < size; i++) {
9046 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009047 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009048 }
9049 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009050 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009051}
9052
Eric Laurent91b14c42012-05-30 12:30:29 -07009053void AudioFlinger::EffectChain::clearInputBuffer()
9054{
9055 Mutex::Autolock _l(mLock);
9056 sp<ThreadBase> thread = mThread.promote();
9057 if (thread == 0) {
9058 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9059 return;
9060 }
9061 clearInputBuffer_l(thread);
9062}
9063
9064// Must be called with EffectChain::mLock locked
9065void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9066{
9067 size_t numSamples = thread->frameCount() * thread->channelCount();
9068 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9069
9070}
9071
Mathias Agopian65ab4712010-07-14 17:59:35 -07009072// Must be called with EffectChain::mLock locked
9073void AudioFlinger::EffectChain::process_l()
9074{
Eric Laurentdac69112010-09-28 14:09:57 -07009075 sp<ThreadBase> thread = mThread.promote();
9076 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009077 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009078 return;
9079 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009080 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9081 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009082 // always process effects unless no more tracks are on the session and the effect tail
9083 // has been rendered
9084 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009085 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009086 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009087
Eric Laurent544fe9b2011-11-11 15:42:52 -08009088 if (!tracksOnSession && mTailBufferCount == 0) {
9089 doProcess = false;
9090 }
9091
9092 if (activeTrackCnt() == 0) {
9093 // if no track is active and the effect tail has not been rendered,
9094 // the input buffer must be cleared here as the mixer process will not do it
9095 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009096 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009097 if (mTailBufferCount > 0) {
9098 mTailBufferCount--;
9099 }
9100 }
9101 }
Eric Laurentdac69112010-09-28 14:09:57 -07009102 }
9103
Mathias Agopian65ab4712010-07-14 17:59:35 -07009104 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009105 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009106 for (size_t i = 0; i < size; i++) {
9107 mEffects[i]->process();
9108 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009109 }
9110 for (size_t i = 0; i < size; i++) {
9111 mEffects[i]->updateState();
9112 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009113}
9114
Eric Laurentcab11242010-07-15 12:50:15 -07009115// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009116status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009117{
9118 effect_descriptor_t desc = effect->desc();
9119 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9120
9121 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009122 effect->setChain(this);
9123 sp<ThreadBase> thread = mThread.promote();
9124 if (thread == 0) {
9125 return NO_INIT;
9126 }
9127 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009128
9129 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9130 // Auxiliary effects are inserted at the beginning of mEffects vector as
9131 // they are processed first and accumulated in chain input buffer
9132 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009133
Mathias Agopian65ab4712010-07-14 17:59:35 -07009134 // the input buffer for auxiliary effect contains mono samples in
9135 // 32 bit format. This is to avoid saturation in AudoMixer
9136 // accumulation stage. Saturation is done in EffectModule::process() before
9137 // calling the process in effect engine
9138 size_t numSamples = thread->frameCount();
9139 int32_t *buffer = new int32_t[numSamples];
9140 memset(buffer, 0, numSamples * sizeof(int32_t));
9141 effect->setInBuffer((int16_t *)buffer);
9142 // auxiliary effects output samples to chain input buffer for further processing
9143 // by insert effects
9144 effect->setOutBuffer(mInBuffer);
9145 } else {
9146 // Insert effects are inserted at the end of mEffects vector as they are processed
9147 // after track and auxiliary effects.
9148 // Insert effect order as a function of indicated preference:
9149 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9150 // another effect is present
9151 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9152 // last effect claiming first position
9153 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9154 // first effect claiming last position
9155 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9156 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9157 // already present
9158
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009159 size_t size = mEffects.size();
9160 size_t idx_insert = size;
9161 ssize_t idx_insert_first = -1;
9162 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009163
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009164 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009165 effect_descriptor_t d = mEffects[i]->desc();
9166 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9167 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9168 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9169 // check invalid effect chaining combinations
9170 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9171 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009172 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009173 return INVALID_OPERATION;
9174 }
9175 // remember position of first insert effect and by default
9176 // select this as insert position for new effect
9177 if (idx_insert == size) {
9178 idx_insert = i;
9179 }
9180 // remember position of last insert effect claiming
9181 // first position
9182 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9183 idx_insert_first = i;
9184 }
9185 // remember position of first insert effect claiming
9186 // last position
9187 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9188 idx_insert_last == -1) {
9189 idx_insert_last = i;
9190 }
9191 }
9192 }
9193
9194 // modify idx_insert from first position if needed
9195 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9196 if (idx_insert_last != -1) {
9197 idx_insert = idx_insert_last;
9198 } else {
9199 idx_insert = size;
9200 }
9201 } else {
9202 if (idx_insert_first != -1) {
9203 idx_insert = idx_insert_first + 1;
9204 }
9205 }
9206
9207 // always read samples from chain input buffer
9208 effect->setInBuffer(mInBuffer);
9209
9210 // if last effect in the chain, output samples to chain
9211 // output buffer, otherwise to chain input buffer
9212 if (idx_insert == size) {
9213 if (idx_insert != 0) {
9214 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9215 mEffects[idx_insert-1]->configure();
9216 }
9217 effect->setOutBuffer(mOutBuffer);
9218 } else {
9219 effect->setOutBuffer(mInBuffer);
9220 }
9221 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009222
Steve Block3856b092011-10-20 11:56:00 +01009223 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009224 }
9225 effect->configure();
9226 return NO_ERROR;
9227}
9228
Eric Laurentcab11242010-07-15 12:50:15 -07009229// removeEffect_l() must be called with PlaybackThread::mLock held
9230size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009231{
9232 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009233 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009234 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9235
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009236 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009237 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009238 // calling stop here will remove pre-processing effect from the audio HAL.
9239 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9240 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009241 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9242 mEffects[i]->state() == EffectModule::STOPPING) {
9243 mEffects[i]->stop();
9244 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009245 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9246 delete[] effect->inBuffer();
9247 } else {
9248 if (i == size - 1 && i != 0) {
9249 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9250 mEffects[i - 1]->configure();
9251 }
9252 }
9253 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009254 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009255 break;
9256 }
9257 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009258
9259 return mEffects.size();
9260}
9261
Eric Laurentcab11242010-07-15 12:50:15 -07009262// setDevice_l() must be called with PlaybackThread::mLock held
9263void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009264{
9265 size_t size = mEffects.size();
9266 for (size_t i = 0; i < size; i++) {
9267 mEffects[i]->setDevice(device);
9268 }
9269}
9270
Eric Laurentcab11242010-07-15 12:50:15 -07009271// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009272void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009273{
9274 size_t size = mEffects.size();
9275 for (size_t i = 0; i < size; i++) {
9276 mEffects[i]->setMode(mode);
9277 }
9278}
9279
Eric Laurentcab11242010-07-15 12:50:15 -07009280// setVolume_l() must be called with PlaybackThread::mLock held
9281bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009282{
9283 uint32_t newLeft = *left;
9284 uint32_t newRight = *right;
9285 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009286 int ctrlIdx = -1;
9287 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009288
Eric Laurentcab11242010-07-15 12:50:15 -07009289 // first update volume controller
9290 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009291 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009292 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9293 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009294 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009295 break;
9296 }
9297 }
9298
9299 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009300 if (hasControl) {
9301 *left = mNewLeftVolume;
9302 *right = mNewRightVolume;
9303 }
9304 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009305 }
9306
9307 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009308 mLeftVolume = newLeft;
9309 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009310
9311 // second get volume update from volume controller
9312 if (ctrlIdx >= 0) {
9313 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009314 mNewLeftVolume = newLeft;
9315 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009316 }
9317 // then indicate volume to all other effects in chain.
9318 // Pass altered volume to effects before volume controller
9319 // and requested volume to effects after controller
9320 uint32_t lVol = newLeft;
9321 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009322
Mathias Agopian65ab4712010-07-14 17:59:35 -07009323 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009324 if ((int)i == ctrlIdx) continue;
9325 // this also works for ctrlIdx == -1 when there is no volume controller
9326 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009327 lVol = *left;
9328 rVol = *right;
9329 }
9330 mEffects[i]->setVolume(&lVol, &rVol, false);
9331 }
9332 *left = newLeft;
9333 *right = newRight;
9334
9335 return hasControl;
9336}
9337
Mathias Agopian65ab4712010-07-14 17:59:35 -07009338status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9339{
9340 const size_t SIZE = 256;
9341 char buffer[SIZE];
9342 String8 result;
9343
9344 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9345 result.append(buffer);
9346
9347 bool locked = tryLock(mLock);
9348 // failed to lock - AudioFlinger is probably deadlocked
9349 if (!locked) {
9350 result.append("\tCould not lock mutex:\n");
9351 }
9352
Eric Laurentcab11242010-07-15 12:50:15 -07009353 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9354 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009355 mEffects.size(),
9356 (uint32_t)mInBuffer,
9357 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009358 mActiveTrackCnt);
9359 result.append(buffer);
9360 write(fd, result.string(), result.size());
9361
9362 for (size_t i = 0; i < mEffects.size(); ++i) {
9363 sp<EffectModule> effect = mEffects[i];
9364 if (effect != 0) {
9365 effect->dump(fd, args);
9366 }
9367 }
9368
9369 if (locked) {
9370 mLock.unlock();
9371 }
9372
9373 return NO_ERROR;
9374}
9375
Eric Laurent59255e42011-07-27 19:49:51 -07009376// must be called with ThreadBase::mLock held
9377void AudioFlinger::EffectChain::setEffectSuspended_l(
9378 const effect_uuid_t *type, bool suspend)
9379{
9380 sp<SuspendedEffectDesc> desc;
9381 // use effect type UUID timelow as key as there is no real risk of identical
9382 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009383 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009384 if (suspend) {
9385 if (index >= 0) {
9386 desc = mSuspendedEffects.valueAt(index);
9387 } else {
9388 desc = new SuspendedEffectDesc();
9389 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9390 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009391 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009392 }
9393 if (desc->mRefCount++ == 0) {
9394 sp<EffectModule> effect = getEffectIfEnabled(type);
9395 if (effect != 0) {
9396 desc->mEffect = effect;
9397 effect->setSuspended(true);
9398 effect->setEnabled(false);
9399 }
9400 }
9401 } else {
9402 if (index < 0) {
9403 return;
9404 }
9405 desc = mSuspendedEffects.valueAt(index);
9406 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009407 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009408 desc->mRefCount = 1;
9409 }
9410 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009411 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009412 if (desc->mEffect != 0) {
9413 sp<EffectModule> effect = desc->mEffect.promote();
9414 if (effect != 0) {
9415 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009416 effect->lock();
9417 EffectHandle *handle = effect->controlHandle_l();
9418 if (handle != NULL && !handle->destroyed_l()) {
9419 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009420 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009421 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009422 }
9423 desc->mEffect.clear();
9424 }
9425 mSuspendedEffects.removeItemsAt(index);
9426 }
9427 }
9428}
9429
9430// must be called with ThreadBase::mLock held
9431void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9432{
9433 sp<SuspendedEffectDesc> desc;
9434
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009435 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009436 if (suspend) {
9437 if (index >= 0) {
9438 desc = mSuspendedEffects.valueAt(index);
9439 } else {
9440 desc = new SuspendedEffectDesc();
9441 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009442 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009443 }
9444 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009445 Vector< sp<EffectModule> > effects;
9446 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009447 for (size_t i = 0; i < effects.size(); i++) {
9448 setEffectSuspended_l(&effects[i]->desc().type, true);
9449 }
9450 }
9451 } else {
9452 if (index < 0) {
9453 return;
9454 }
9455 desc = mSuspendedEffects.valueAt(index);
9456 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009457 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009458 desc->mRefCount = 1;
9459 }
9460 if (--desc->mRefCount == 0) {
9461 Vector<const effect_uuid_t *> types;
9462 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9463 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9464 continue;
9465 }
9466 types.add(&mSuspendedEffects.valueAt(i)->mType);
9467 }
9468 for (size_t i = 0; i < types.size(); i++) {
9469 setEffectSuspended_l(types[i], false);
9470 }
Steve Block3856b092011-10-20 11:56:00 +01009471 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009472 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9473 }
9474 }
9475}
9476
Eric Laurent6bffdb82011-09-23 08:40:41 -07009477
9478// The volume effect is used for automated tests only
9479#ifndef OPENSL_ES_H_
9480static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9481 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9482const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9483#endif //OPENSL_ES_H_
9484
Eric Laurentdb7c0792011-08-10 10:37:50 -07009485bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9486{
9487 // auxiliary effects and visualizer are never suspended on output mix
9488 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9489 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009490 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9491 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009492 return false;
9493 }
9494 return true;
9495}
9496
Glenn Kastend0539712012-01-30 12:56:03 -08009497void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009498{
Glenn Kastend0539712012-01-30 12:56:03 -08009499 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009500 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009501 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9502 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009503 }
Eric Laurent59255e42011-07-27 19:49:51 -07009504 }
Eric Laurent59255e42011-07-27 19:49:51 -07009505}
9506
9507sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9508 const effect_uuid_t *type)
9509{
Glenn Kasten090f0192012-01-30 13:00:02 -08009510 sp<EffectModule> effect = getEffectFromType_l(type);
9511 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009512}
9513
9514void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9515 bool enabled)
9516{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009517 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009518 if (enabled) {
9519 if (index < 0) {
9520 // if the effect is not suspend check if all effects are suspended
9521 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9522 if (index < 0) {
9523 return;
9524 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009525 if (!isEffectEligibleForSuspend(effect->desc())) {
9526 return;
9527 }
Eric Laurent59255e42011-07-27 19:49:51 -07009528 setEffectSuspended_l(&effect->desc().type, enabled);
9529 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009530 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009531 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009532 return;
9533 }
Eric Laurent59255e42011-07-27 19:49:51 -07009534 }
Steve Block3856b092011-10-20 11:56:00 +01009535 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009536 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009537 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9538 // if effect is requested to suspended but was not yet enabled, supend it now.
9539 if (desc->mEffect == 0) {
9540 desc->mEffect = effect;
9541 effect->setEnabled(false);
9542 effect->setSuspended(true);
9543 }
9544 } else {
9545 if (index < 0) {
9546 return;
9547 }
Steve Block3856b092011-10-20 11:56:00 +01009548 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009549 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009550 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9551 desc->mEffect.clear();
9552 effect->setSuspended(false);
9553 }
9554}
9555
Mathias Agopian65ab4712010-07-14 17:59:35 -07009556#undef LOG_TAG
9557#define LOG_TAG "AudioFlinger"
9558
9559// ----------------------------------------------------------------------------
9560
9561status_t AudioFlinger::onTransact(
9562 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9563{
9564 return BnAudioFlinger::onTransact(code, data, reply, flags);
9565}
9566
Mathias Agopian65ab4712010-07-14 17:59:35 -07009567}; // namespace android